简体   繁体   English

在 virtualenv 中执行 os.system('python')

[英]execute os.system('python ') inside a virtualenv

I'm using a virtualenv to execute a script, in this script I call:我正在使用virtualenv来执行脚本,在这个脚本中我调用:

os.system('python anotherScript.py')

My question is whether the script is executed in the same virtualenv as the caller script?我的问题是脚本是否与调用者脚本在同一个virtualenv执行?

It's hard to tell, but if you are running this script under an activated virtualenv, you should be under that virutla environment.很难说,但如果你在激活的 virtualenv 下运行这个脚本,你应该在那个 virutla 环境下。 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你应该看到它在newvirtualenv/bin/python

Usually, you want to put an exectuable header to use the current environment:通常,您希望放置一个 exectuable 标头以使用当前环境:

#!/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 .这并不是说使用newvirtualenv ,但如果脚本在newvirtualenv下执行,它会让你更有信心,它肯定会是newvirtualenv

If you use /usr/bin/python this is still okay under virtualenv.如果您使用/usr/bin/python这在 virtualenv 下仍然可以。 But for advanced programmers, they tend to have multiple virtual environments and multiple python version.但是对于高级程序员来说,他们往往有多个虚拟环境和多个 python 版本。 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.如果您运行newvirtualenv/bin/python script.py它将无论如何都在 virtualenv 下。

As long as the python binary is pointing at the virtualenv's version, you are good.只要python二进制文件指向 virtualenv 的版本,你就很好。

eg use anaconda to manage virtual envs, and in Pycharm IDE:例如使用 anaconda 来管理虚拟环境,在 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 (eg cv2) installed in certain virtual env,如果我想使用安装在某些虚拟环境中的某些模块(例如 cv2),

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM