14

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.

6
  • I am not very experienced with that module but wonder if it is being directed to use 2.7... stackoverflow.com/questions/11170827/… Commented Apr 8, 2015 at 19:13
  • What is the behavior when running testprint.py from the command line without specifying the python executable to use? Commented Apr 8, 2015 at 19:16
  • I was going to suggest execfile, but then realized that got removed (though you could look at stackoverflow.com/questions/6357361/…). Commented Apr 8, 2015 at 19:40
  • Huh, so if I run 'python testprint.py' I get 3.4 back. But if I only say 'testprint.py' I get 2.7 back. Commented Apr 8, 2015 at 20:03
  • Don't use 'shell=True' unless it it needed because you are running a shell command instead of a file. Commented Apr 8, 2015 at 21:00

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.