Take the 2-minute tour ×

I have a question regarding python and the environment variables in linux. I've been reading a lot of questions/answers here but no one is exactly my case. Here it goes:

I have a script in python that automatically installs virtualenvwrapper and several other stuff. It is running on a HPC cluster which uses module sysem. One of the steps of the installation consists on modifying some configuration files (~/.bashrc and ~/.virtualenvs/postactivate) so that new environment variables and also commands are available.

Specifically, I modify .bashrc adding a source to ~/opt/mypython/bin/virtualenvwrapper.sh, which defines a lot of useful commands to manage virtualenv. Within the same script I want to create a virtual environment, so, until now, I'm doing:

install_and_create_virtualenv ='''
    easy_install --prefix=~/opt/mypython pip &&
    pip install virtualenvwrapper --install-option="--prefix=~/opt/mypython" &&
    . ~/.bashrc &&
    module unload python &&
    mkvirtualenv --python=/sw/comp/python/2.7_kalkyl/bin/python master

check_call(install_and_create_virtualenv, shell=True, env=env)

As you can see, I do a . ~/.bashrc instide the check_call. This sources .bashrc (and therefore virtualenvwrapper.sh) and then I can call mkvirtualenv. Otherwise mkvirtualenv will not be available, as I have just installed it.

This will not be a problem If I had to do it just once. But the fact is that I do several check_calls and in every one I have to source .bashrc because otherwise I execute the check_call with a "clean" environment and I cannot go forward.

So my question is: Is there any way to update the general environment the same way as if I was leaving the script, sourcing .bashrc and entering the script again?

Thank you very much!

NOTE: the env parameter passed to the check_call has just a few general variables, I can't add to this env every command that virtualenvwrapper defines.

share|improve this question
add comment

1 Answer

As you've noted, these commands generally just manipulate the environment. I would run env as the final command in this setup process, and parse its arguments into a dict. This dict can either be added to the env variable you already have, or if you want to make it permanent and global, you can os.environ.update(virtualenv_env).

share|improve this answer
Hi bukzor, Thanks for your answer. I think though that will not work. Virtualenvwrapper.sh is a script that defines new bash functions that act as commands, so I cannot just add, for example, the command "workon" to env, but I have to source the full function. –  guillemch Sep 19 '12 at 16:19
if you want your bash functions, why not write a bash script? –  Chris Wesseling Sep 20 '12 at 8:46
In bash, at least, functions can be exported to the environment with export -f myfunc. –  bukzor Sep 20 '12 at 15:26
add comment

Your Answer


