有没有更好的方法来控制子进程的 PYTHONPATH? [英] Is there a better way to control the PYTHONPATH of a subprocess?

查看:43
本文介绍了有没有更好的方法来控制子进程的 PYTHONPATH?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组脚本,必须动态修改 os.sys.path.然后脚本启动一个子流程.理想情况下,子进程将与调用者具有相同的 os.sys.path.我想避免将它作为参数传递,因为这需要修改子流程脚本.

I have a set of scripts that has to modify os.sys.path on the fly. The scripts then kick off a subprocess. Ideally, the subprocess would have the same os.sys.path as the caller. I want to avoid passing it in as an argument, since that would require a modification to the subprocess script.

我的代码可以运行并满足我的所有需求.我想知道是否有更好的方法来做到这一点,以及这种方法是否存在任何缺陷.

I have code that works and meets all of my needs. I want to know if there is a better way to do this, and if there are any pitfalls to this approach.

主要流程

import os
import sys
import subprocess

#append a dir thats not on the sys path
sys.path.append('C:/pytest2/')

#convert the sys.path into env variable format
pypath = ''
for d in sys.path:
    pypath = pypath + d + ';'

#create a temp copy of the env variables
myenv = os.environ.copy()

#set PYTHONPATH to match this scripts sys.path
myenv['PYTHONPATH'] = pypath

#setup a python command to echo the sys.path
command = 'python C:/pytest/test_subprocess.py'

#launch the subprocess with the custom env
p = subprocess.Popen(command, env=myenv)

C:/pytest/test_subprocess.py

C:/pytest/test_subprocess.py

import sys
print 'sys path'
print sys.path

运行主进程导致此控制台输出

Running the main process results in this console output

如您所见,C:/pytest2/位于 test_subprocess.py 的 os.sys.path 上

As you can see, C:/pytest2/ is on the os.sys.path for test_subprocess.py

EDIT 将 os.sys 更改为 sys

EDIT Changed os.sys to sys

推荐答案

PYTHONPATH 环境变量只是附加到 sys.path.Python 本身(和 site 模块)从各种来源初始化模块搜索路径.您只需要通过 PYTHONPATH 环境变量添加一个目录.更好的方法是将它安装在通常的 site-packages 目录中,并且已经搜索过了.这样你就不必在环境中做任何特别的事情了.

The PYTHONPATH environment variable just appends to the sys.path. Python itself (and the site module) initialize the module search path from various sources. You only need to add your one directory via the PYTHONPATH environment variable. Even better would be to just install it in the usual site-packages directory with is already searched. Then you won't have to do anything special in the environment.

这篇关于有没有更好的方法来控制子进程的 PYTHONPATH?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆