Execute os.system ('python') inside virtualenv

I am using virtualenv

to execute a script, in this script I am calling:

os.system('python anotherScript.py')

      

My question is, is the script executed in the same virtualenv

way as the calling script?

+3


source to share


1 answer


It's hard to say, but if you are running this script under an activated virtualenv you must be under that virutla environment. You can test your thought by doing

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

      

and from the command line

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

      

you should see that 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 is not meant to be used newvirtualenv

, but gives you a little more confidence, if the script is executed under newvirtualenv

, it definitely will newvirtualenv

.

If you are using /usr/bin/python

it is still ok virtualenv. But for advanced programmers, they tend to have multiple virtual environments and multiple python versions. So depending on where they are, they might execute the script based on the environment variable. Just a small win.

If you run it newvirtualenv/bin/python script.py

, it will be in virtual space independently.

As long as the binary python

points to the virtualenv version, you're good.

+3


source







All Articles