Python subprocess is running a different version o

2019-07-01 20:10发布

问题:

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 is just this:

import sys
print(sys.version)

Edit: 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.

回答1:

One solution is to do:

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. This is effectively the same as your solution, but the executable position is not hard-coded.