简体   繁体   中英

Run virtualenvwrapper commands from python script

When I'm trying to create a new Python 3 virtual environment by using mkvirtualenv (virtualenvwrapper command) and os.system like this

import os
os.system('mkvirtualenv foo')

nothing happens.

os.system("mate-terminal -e 'workon foo'")

doesn't work either.

The point is to quickly create a new virtual env and work on it later for each project (it's an automation script). virtualenvwrapper is the most convenient option.

The mkvirtualenv and workon commands are shell functions, not executables in your PATH [0]. To make them available in the shell you execute them in, you need to source the virtualenvwrapper.sh shell script defining them. You might be better off calling virtualenv /path/to/foo directly.

How to activate that virtualenv is another story, though, and will depend on the context you want to use it in. If you activate it in a subprocess, each process using it will have to be run in or under that child.

Hth, dtk

PS In addition, you might look into the subprocess module (or even the third-party sh ) for calling external programs. Happy coding :)

[0]: See $ which workon in a terminal vs $ which bash

The following codes in the bash shell script

env_name="<your env name>"
echo "Create virtual environment"
source `which virtualenvwrapper.sh`
mkvirtualenv $env_name -p python<$version>
source $HOME/.virtualenvs/$env_name/bin/activate
workon $env_name

then run bash script (for example: test.sh ) from terminal source test.sh

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM