在混合Python 2.7/3.3环境中使用virtualenv和subprocess.call()

时间:2021-10-06 22:37:00

For some functional tests, I invoke a couple of utilities directly from the project directory, using Python's subprocess.call (or check_call which invokes the latter). This works well when the libraries (PyYAML in particular) are installed globally. Running in a virtualenv, such as under Travis-CI, causes problems, especially if the virtualenv is running Python 3.x and the global Python is 2.7.

对于某些功能测试,我使用Python的子流程直接从项目目录调用两个实用程序。调用(或调用后者的check_call)。在全局安装库(特别是PyYAML)时,这种方法非常有效。在一个virtualenv中运行(例如在travi - ci下)会导致问题,尤其是当virtualenv正在运行Python 3时。x和全局Python是2。7。

If both Pythons are 2.7, I still had to inject the location of PyYAML within the virtualenv, using the env argument to subprocess.call, in order not to cause an ImportError. However, this doesn't work when the virtualenv is 3.x. It appears the invoked utility runs outside the virtualenv because its sys.path looks as follows:

如果这两个python都是2.7,我仍然需要在virtualenv中使用env参数注入PyYAML的位置来进行子进程。打电话,以免引起恐怖。然而,当virtualenv是3.x时,这就不起作用了。它显示被调用的实用程序在virtualenv之外运行,因为它的系统。路径如下:

 '/home/travis/build/jmafc/Pyrseas/pyrseas', '/usr/local/lib/python2.7/dist-packages/distribute-0.6.35-py2.7.egg', '/usr/local/lib/python2.7/dist-packages/pip-1.3.1-py2.7.egg', '/home/travis/build/jmafc/Pyrseas', '/home/travis/virtualenv/python3.3/lib/python3.3/site-packages', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/local/lib/python2.7/dist-packages/setuptools-0.6c11-py2.7.egg-info', '/usr/lib/python2.7/dist-packages']

Notice the mixture of 2.7 and 3.3 paths, the latter being expressly injected as mentioned above.

注意2.7和3.3路径的混合,后者如上所述被明确地注入。

Is there some way from either virtualenv or in the subprocess functions to ensure the subprocess runs "within" the virtualenv?

是否有什么方法可以从virtualenv或子进程函数中确保子进程在virtualenv中运行?

1 个解决方案

#1


19  

If you pass in a copy of your environment variables and use the current Python interpreter as the target of the subprocess, the virtualenv environment should be preserved. Something like this:

如果您传递环境变量的副本并使用当前的Python解释器作为子进程的目标,那么应该保留virtualenv环境。是这样的:

subprocess.call([sys.executable, 'yourscript.py'], env=os.environ.copy())

#1


19  

If you pass in a copy of your environment variables and use the current Python interpreter as the target of the subprocess, the virtualenv environment should be preserved. Something like this:

如果您传递环境变量的副本并使用当前的Python解释器作为子进程的目标,那么应该保留virtualenv环境。是这样的:

subprocess.call([sys.executable, 'yourscript.py'], env=os.environ.copy())