Alexander Lavrenko
Alexander Lavrenko

Reputation: 75

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.

Upvotes: 1

Views: 919

Answers (2)

Toan Minh Hoang
Toan Minh Hoang

Reputation: 41

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

Upvotes: 0

dtk
dtk

Reputation: 2526

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

Upvotes: 2

Related Questions