【发布时间】:2019-05-19 20:28:19
【问题描述】:
我想在运行时更改我的PYTHONPATH(使用 Python 2),放置一个新的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
有人做过类似的事情吗?我的逻辑正确吗?
P.S:我知道有像 In Python script, how do I set PYTHONPATH? 这样的线程,但它们只提供有关附加或插入的信息,这不符合我的逻辑。
【问题讨论】:
-
如果这是用于旧版 Python 2.x,请使用标签 python-2.7 或任何适合您问题的标签。除非另有说明,否则我们希望 Python 问题与当前推荐和支持的版本(即 Python 3)有关。
-
实际上两者都有关,因为问题在于在这两者之间切换。尽管如此,我还是添加了 Python 2.7 标签。
标签: python-3.x python-2.7