virtualenvwrapper functions unavailable in shell s

2020-01-28 02:44发布

So, once again, I make a nice python program which makes my life ever the more easier and saves a lot of time. Ofcourse, this involves a virtualenv, made with the mkvirtualenv function of virtualenvwrapper. The project has a requirements.txt file with a few required libraries (requests too :D) and the program won't run without these libraries.

I am trying to add a bin/run-app executable shell script which would be in my path (symlink actually). Now, inside this script, I need to switch to the virtualenv before I can run this program. So I put this in

#!/bin/bash
# cd into the project directory
workon "$(cat .venv)"
python main.py

A file .venv contains the virtualenv name. But when I run this script, I get workon: command not found error.

Of course, I have the virtualenvwrapper.sh sourced in my bashrc but it doesn't seem to be available in this shell script.

So, how can I access those virtualenvwrapper functions here? Or am I doing this the wrong way? How do you launch your python tools, each of which has its own virtualenv!?

8条回答
2楼-- · 2020-01-28 02:58

If your Python script requires a particular virtualenv then put/install it in virtualenv's bin directory. If you need access to that script outside of the environment then you could make a symlink.

main.py from virtualenv's bin:

#!/path/to/virtualenv/bin/python
import yourmodule

if __name__=="__main__":
   yourmodule.main()

Symlink in your PATH:

pymain -> /path/to/virtualenv/bin/main.py

In bin/run-app:

#!/bin/sh
# cd into the project directory
pymain arg1 arg2 ...
查看更多
相关推荐>>
3楼-- · 2020-01-28 02:58

You can also call the virtualenv's python executable directly. First find the path to the executable:

$ workon myenv
$ which python
/path/to/virtualenv/myenv/bin/python

Then call from your shell script:

#!/bin/bash

/path/to/virtualenv/myenv/bin/python myscript.py
查看更多
beautiful°
4楼-- · 2020-01-28 03:00

add these lines to your .bashrc or .bash_profile

export WORKON_HOME=~/Envs
source /usr/local/bin/virtualenvwrapper.sh

and reopen your terminal and try

查看更多
放我归山
5楼-- · 2020-01-28 03:01

It's a known issue. As a workaround, you can make the content of the script a function and place it in either ~/.bashrc or ~/.profile

function run-app() {
  workon "$(cat .venv)"
  python main.py
} 
查看更多
Summer. ? 凉城
6楼-- · 2020-01-28 03:01

Apparently, I was doing this the wrong way. Instead of saving the virtualenv's name in the .venv file, I should be putting the virtualenv's directory path.

(cdvirtualenv && pwd) > .venv

and in the bin/run-app, I put

source "$(cat .venv)/bin/activate"
python main.py

And yay!

查看更多
戒情不戒烟
7楼-- · 2020-01-28 03:14

I can't find the way to trigger the commands of virtualenvwrapper in shell. But this trick can help: assume your env. name is myenv, then put following lines at the beginning of scripts:

ENV=myenv
source $WORKON_HOME/$ENV/bin/activate
查看更多
登录 后发表回答