Search code examples
pythonpython-3.xvirtualenvvirtualenvwrapper

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.


Solution

  • 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