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.

3

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
subprocess and sh don't solve the general problem, however they are nicer interfaces for calling external programs.
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 👍
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.