Pregunta

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?

¿Fue útil?

Solución

It's hard to tell, but if you are running this script under an activated virtualenv, you should be under that virutla 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 confident if 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.

Otros consejos

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) 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top