Python 子进程 运行 是 Python 的不同版本
Python subprocess is running a different version of Python
我正在尝试创建一个 Python 脚本来执行其他 Python 脚本,它适用于大多数脚本,但在遇到 print('anything', end='')
时会失败。这是因为子进程是运行ning 2.7,而不是3.4。我一辈子都弄不明白如何让子进程 运行 3.4.
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import subprocess
>>> sys.version
'3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)]'
>>> results = subprocess.check_output('testprint.py', shell=True)
>>> results
b'2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)]\r\n'
testprint.py就是这样:
import sys
print(sys.version)
编辑:当然,我会在发布问题后找到解决方案。我将代码修改为以下内容:
path = r'C:\Python34\python.exe'
results = subprocess.check_output([path, 'testprint.py'], shell=True)
现在我传递脚本将 运行 通过的可执行路径。不过,我还是喜欢更优雅、更永久的解决方案。
一个解决方案是:
import sys
import subprocess
subprocess.call([sys.executable, 'testprint.py'])
sys.executable
is the location of the python binary running the code executing. Note that for some reason shell=True
launches the python binary without any arguments on sys.argv
, so either omit that option, use a string or shlex.quote
。这实际上与您的解决方案相同,但可执行位置不是硬编码的。
我正在尝试创建一个 Python 脚本来执行其他 Python 脚本,它适用于大多数脚本,但在遇到 print('anything', end='')
时会失败。这是因为子进程是运行ning 2.7,而不是3.4。我一辈子都弄不明白如何让子进程 运行 3.4.
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import subprocess
>>> sys.version
'3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)]'
>>> results = subprocess.check_output('testprint.py', shell=True)
>>> results
b'2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)]\r\n'
testprint.py就是这样:
import sys
print(sys.version)
编辑:当然,我会在发布问题后找到解决方案。我将代码修改为以下内容:
path = r'C:\Python34\python.exe'
results = subprocess.check_output([path, 'testprint.py'], shell=True)
现在我传递脚本将 运行 通过的可执行路径。不过,我还是喜欢更优雅、更永久的解决方案。
一个解决方案是:
import sys
import subprocess
subprocess.call([sys.executable, 'testprint.py'])
sys.executable
is the location of the python binary running the code executing. Note that for some reason shell=True
launches the python binary without any arguments on sys.argv
, so either omit that option, use a string or shlex.quote
。这实际上与您的解决方案相同,但可执行位置不是硬编码的。