3

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?

nam
  • 3,542
  • 9
  • 46
  • 68
  • To make sure you could use `execfile` instead of `os.system`. This will execute the script within the current interpreter(with all the up- *and* down-sites). – Bakuriu Feb 12 '13 at 18:45
  • It depends on which "python" it finds on your process's PATH. Perhaps you can make the script a module and run it in a thread instead? – Keith Feb 12 '13 at 21:41

2 Answers2

4

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.

julaine
  • 382
  • 3
  • 12
CppLearner
  • 16,273
  • 32
  • 108
  • 163
  • I've used `usr/bin/python` and it works under the `virtualenv`, thanks – nam Feb 13 '13 at 10:28
  • @HOAINAMNGUYEN I just want to reiterate my point briefly. The hashbang `#!/usr/bin/python` is okay as long as you run it as `/path/to/my/virtualenv/bin/python myscript.py`. If you just run `python myscript.py` and you are not running this python under an activated virtualenv, you will run it using the system-wide python. So make sure you activate your virtualenv, or always specify `/path/to/my/virtualenv/bin/python script.py` regardless of how the header looks like. – CppLearner Feb 13 '13 at 20:03
-1

e.g. use anaconda to manage virtual envs, and in Pycharm IDE:

os.system('which python') # /usr/bin/python
command = 'python3 xxxx.py' 
os.system(command) # make /usr/bin/python as interpreter

If I want to use some modules (e.g. cv2) installed in certain virtual env,

command = '/path/to/anaconda3/envs/your_env_name/bin/python3 xxxx.py' 
os.system(command) 
Lamp
  • 11
  • 1