简体   繁体   中英

Python subprocess: How to run a python script using a different intepreter than the main thread

I am running an application that has an embedded python interpreter which is 2.7. I need to run a standalone python application as a subprocess, but that application is only compatible with python 2.6. How can I force the python application to launch with the python2.6 interpreter?

Like Dunes already said:

proc = Popen(['/path/to/executable', '-flag1', '--opt=value'])

The executable could be Python script with the shebang #!/usr/bin/env python2.6 or a bash script starting your Python2.6 interpreter.

Note, that the interpreter will not wait for the 2.6 version to finish. You have to use the .wait() method for that. Otherwise your child process can become a zombie.

# wait for the process to finish
proc.wait()

If you want to create a daemon - meaning a child process that does not terminates if the parent is killed - you need the os.fork() function. There are scripts around that takes care of all the stuff for you - eg. daemonize.py

A few complications, the python script is not a .py script, but a wrapper bash executable (with #! /usr/bin/env python2).

To run the script using python2.6, you could change its shebang to point to python2.6 executable:

#!/usr/bin/env python2.6

and run the script directly:

subprocess.check_call(['/path/to/your_script'] + sys.argv[1:])

sys.argv[1:] is used to pass command-line arguments to the child script.

If you can't change the shebang then run:

subprocess.check_call(['/usr/bin/env', 'python2.6', '/path/to/your_script'] + 
                      sys.argv[1:])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM