pythonvirtualenvos.system

execute os.system('python ') inside a virtualenv


I'm using a virtualenv to execute a script, in this script I call:

os.system('python anotherScript.py')

My question is whether the script is executed in the same virtualenv as the caller script?


Solution

  • It's hard to tell, but if you are running this script under an activated virtualenv, you should be under that virtual environment. You can verify your thought by doing

    #script.py
    import os
    os.system('which python')
    

    and from command-line

    virtualenv newvirtualenv
    source newvirtualenv/bin/activate
    (newvirtualenv) user@ubuntu: python script.py
    

    you should see it is under newvirtualenv/bin/python

    Usually, you want to put an exectuable header to use the current environment:

    #!/usr/bin/env python
    import os
    os.system('which python')
    

    This does not say use newvirtualenv, but gives you a little more confidence that the script is executed under newvirtualenv, it will definitely be newvirtualenv.

    If you use /usr/bin/python this is still okay under virtualenv. But for advanced programmers, they tend to have multiple virtual environments and multiple python version. So depending on where they are, they can execute the script based on the environment variable. Just a small gain.

    If you run newvirtualenv/bin/python script.py it will be under virtualenv regardless.

    As long as the python binary is pointing at the virtualenv's version, you are good.