Python 子进程正在运行不同版本的 Python [英] Python subprocess is running a different version of Python
问题描述
我正在尝试创建一个 Python 脚本来执行其他 Python 脚本,它适用于大多数脚本,但在遇到 print('anything', end='')
时会失败.这是因为子进程运行的是 2.7,而不是 3.4.我一生都无法弄清楚如何让子流程运行 3.4.
I'm trying to create a Python script to execute other Python scripts, and it works on most scripts, but will fail when it encounters print('anything', end='')
. This is because the subprocess is running 2.7, rather than 3.4. I cannot for the life of me figure out how to have the subprocess run 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 就是这样:
testprint.py is just this:
import sys
print(sys.version)
当然,我会在发布问题后意识到解决方案.我将代码修改为以下内容:
And of course I would realize a solution after posting the question. I modified the code to the following:
path = r'C:\Python34\python.exe'
results = subprocess.check_output([path, 'testprint.py'], shell=True)
现在我正在传递脚本将运行的可执行路径.不过,我还是喜欢更优雅、更持久的解决方案.
Now I'm passing in the executable path the script will be run through. Still, I would love a more elegant and permanent solution.
推荐答案
一个解决方案是:
import sys
import subprocess
subprocess.call([sys.executable, 'testprint.py'])
sys.executable
是运行代码的python二进制文件的位置.请注意,由于某些原因 shell=True
在 sys.argv
上启动没有任何参数的 python 二进制文件,所以要么省略该选项,使用字符串或 shlex.quote
.这实际上与您的解决方案相同,但可执行位置不是硬编码的.
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
. This is effectively the same as your solution, but the executable position is not hard-coded.
这篇关于Python 子进程正在运行不同版本的 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!