1

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.

  • 1
    Related: https://stackoverflow.com/questions/6943208/activate-a-virtualenv-with-a-python-script – colidyre Sep 15 '18 at 17:18
  • Possible duplicate of [subprocess.Popen: mkvirtualenv not found](https://stackoverflow.com/questions/18337767/subprocess-popen-mkvirtualenv-not-found) – phd Sep 15 '18 at 17:43
  • https://stackoverflow.com/search?q=%5Bvirtualenvwrapper%5D+mkvirtualenv+subprocess – phd Sep 15 '18 at 17:44

2 Answers2

2

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

dtk
  • 2,197
  • 2
  • 26
  • 19
  • 1
    Unfortunately, neither subprocess nor sh doesn't help (can't find a perfect solution). However, os.system('python3 -m venv foo') works well, the only con is that it just can't activate it automatically. os.system("mate-terminal -e '. bin/activate'") fails (permission denied). In other words, everything is almost perfect for now, except I need to type 'workon foo' in the popped-out terminal window each time. Thank you for your suggestions. – Alexander Lavrenko Sep 16 '18 at 13:53
  • `subprocess` and `sh` don't solve the general problem, however they are nicer interfaces for calling external programs. – dtk Sep 16 '18 at 14:11
  • The `permission denied` problem seems to be related to how you execute your command with `-e`/`-x` (and maybe `source`/`.` being shell built-ins instead of executables ;)). And since the terminal you spawned that way will close anyway after it finishes the provided command, you might wanna open a new question for this problem – dtk Sep 16 '18 at 14:47
0

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