我想在运行时更改我的PYTHONPATH
(使用Python2),放置一个新的PYTHONPATH
,执行一个subprocess
并运行需要Python3的特定代码,然后将其设置回原来的状态。
这是我想出来的逻辑:
# save the current PYTHONPATH to a variable
pythonpath = os.environ["PYTHONPATH"]
print('PYTHONPATH (Before Execution): ', pythonpath)
# alter the PYTHONPATH
# append or insert would not be the best
# but rather emptying it and putting the new `PYTHONPATH` each time
# use the following
# subp.Popen("")
# subp.call("") : python3 mycode.py -i receivedImgPath", shell=True
# to call the code with the new PYTHONPATH
# after the code execution is done, set the PYTHONPATH to back
# since we have saved it, use directly the variable pythonpath
有没有人做过类似的事情?我的逻辑正确吗?
附言:我知道有像In Python script, how do I set PYTHONPATH?这样的线程,但它们只提供有关附加或插入的信息,这与我的逻辑不兼容。
发布于 2018-12-19 19:00:26
subprocess
可以方便地让您在单独的环境中将其传递给子进程。
envcopy = os.environ.copy()
# Add '/home/hovercraft/eels' to the start of
# PYTHONPATH in the new copy of the environment
envcopy['PYTHONPATH'] = '/home/hovercraft/eels' + ':' + os.environ['PYTHONPATH']
# Now run a subprocess with env=envcopy
subprocess.check_call(
['python3', 'mycode.py', '-i', 'receivedImgPath'],
env=envcopy)
我们正在修改一个副本,因此父进程的PYTHONPATH
保持其原始值。
如果您需要一个非常简单的环境,那么您所需要的可能就是
subprocess.check_call(command,
env={'PYTHONPATH': '/home/myself/env3/lib'})
现代Python代码应该更喜欢(Python 3.5+ subprocess.run
而不是) subprocess.check_call
而不是subprocess.call
(通过subprocess.Popen
而不是像os.system
这样的各种遗留问题);但我猜您被Python2.x卡住了。为了(更多!)更多信息,请参阅https://stackoverflow.com/a/51950538/874188
https://stackoverflow.com/questions/53849665
复制相似问题