Activate virtualenv via os.system()

2019-01-25 22:19发布

I'm writing a Python-based shell script to boilerplate a Django app with virtualenv, pip, and fabric. Should be straightforward enough, but it appears that I'm not able to activate and run commands in the virtualenv through the shell script.

os.system('virtualenv %s --no-site-packages' % project_name)
os.system('source %s/bin/activate' % project_name)
os.system('easy_install pip')

When running, this errors out:

$ startproject+ -s false sample
New python executable in sample/bin/python
Installing setuptools............done.
/testing
Searching for pip
Best match: pip 0.4
Processing pip-0.4-py2.6.egg
pip 0.4 is already the active version in easy-install.pth
Installing pip script to /usr/local/bin
error: /usr/local/bin/pip: Permission denied

Obviously the source line isn't being run, but why? Is it a concurrency/threading issue, or something deeper with virtualenv?

Thanks!

4条回答
孤傲高冷的网名
2楼-- · 2019-01-25 22:52

Each call to os.system runs the command in a new subshell, which has the same properties as the original python process.

Try putting the commands into one string separated by semicolons.

查看更多
劫难
3楼-- · 2019-01-25 22:58

Each os.system call creates a new process. You'll need to ensure that the activate and the easy_install are run in the same os.system or subprocess call.

查看更多
戒情不戒烟
4楼-- · 2019-01-25 22:59

You could also install virtualenvwrapper, and use the postmkvirtualenv hook. I use it to automatically bring in fresh copies of pip and IPython into virtualenvs I create (as I don't want it using my system IPython). I also use it to copy pythonw into the virtualenv, otherwise wx-based stuff won't work. Looks like this:

easy_install pip
pip install -I ipython
cd ~/bin
python install_pythonw.py ${VIRTUAL_ENV}
查看更多
Lonely孤独者°
5楼-- · 2019-01-25 23:05

Just don't use "source activate" at all. It does nothing but alter your shell PATH to put the virtualenv's bin directory first. I presume your script knows the directory of the virtualenv it has just created; all you have to do is call _virtualenv_dir_/bin/easy_install by full path. Or _virtualenv_dir_/bin/python for running any other python script within the virtualenv.

查看更多
登录 后发表回答