环境:
Windows: 10
Python: 2.7.13 and 3.8.1
default Python launcher: py -3
Default python: 2.7.13
> python -V
> Python 2.7.13
> py -3 -V
> Python 3.8.1launcher.py:
import subprocess
subprocess.call(['python', '-V'])py -3 launcher.py输出:Python3.8.1(如何!)py -2 launcher.py输出:Python2.7.13输出只应该是Python 2.7.13,即使是启动程序运行在py 3下!
请注意,添加shell=True将有效,但想法是不使用它,如果我运行
subprocess.call(['python', 'script_under_py_2.py']) # Will run python 3 with script python 2!谢谢
亚当
发布于 2020-03-09 21:02:23
此行为是由于在Windows和Unix上调用PATH环境变量时对Popen环境变量的处理不一致。
Windows使用CreateProcess函数创建其子进程。CreateProcess 包括父进程目录的搜索路径,这可能是执行不同二进制文件的原因。
在Windows上,只有在传递shell=True时才考虑路径。
您可以在这里了解有关此问题的更多信息:
发布于 2020-03-09 22:02:56
如果问题是subprocess.call没有遵守os.environ['PATH'],那么始终可以显式地搜索要调用的可执行文件的路径,然后按其绝对路径调用它,如下所示:
# Manually search the operating system's PATH for python[.exe]
import os, sys
ospath = os.environ['PATH'].split(os.path.pathsep)
_, extension = os.path.splitext(sys.executable)
target = 'python' + extension
matches = [os.path.join(directory, target) for directory in ospath]
matches = [match for match in matches if os.path.isfile(match)]
if not matches: raise OSError('{!r} was not found in any PATH directory'.format(target))
python = matches[0]
# Test:
import subprocess
print('I am Python {} and I am calling "{}" -V'.format(sys.version.split()[0], python))
subprocess.call([python, '-V'])当然,如果py -3包装器通过在启动Python之前实际更改路径来工作,这将不能满足您的要求.我不熟悉那个包装,所以我不知道这会不会是个问题。
https://stackoverflow.com/questions/60607561
复制相似问题