I am creating a wrapper around a few python scripts and have run into a slight issue when there are multiple versions of python installed on the computer. For example on my Mac there is python 2.7 accessible via "python" at the command line and python 3.4 available "python3". Is there anyway to determine how the current python instance was started so that I can be sure the subprocess will be using the right version?
import subprocess
def main():
pythonCommand = determineCommand() #What is python install as on this computer
argArray = [pythonCommand, "test.py"] #requires python 3.4
subprocess.call(argArray)
#What I need to figure out
def determineCommand():
#If Some Check
return "python3"
#Else some other check
return "python"
#else something weird
return "python34"
#and so on
if __name__ == "__main__":
main()
The above code will not execute properly on my computer but on a computer with only python 3.4 installed it works fine. Changing the argArray to use python3 works on my computer but breaks it on others.
-
related: Call python script with input with in a python script using subprocessjfs– jfs2015年11月17日 04:20:50 +00:00Commented Nov 17, 2015 at 4:20
2 Answers 2
To get the executable used to launch the current Python interpreter, read sys.executable. It's the absolute path to the Python interpreter binary currently running (though it can be the empty string or None in weird cases, like frozen executables and the like).
Comments
The version of Python being executed can be checked via sys.version_info:
chuck@computer:~$ python
>>> import sys; sys.version_info
sys.version_info(major=2, minor=7, micro=10, releaselevel='final', serial=0)
>>> exit()
chuck@computer:~$ python3
>>> import sys; sys.version_info
sys.version_info(major=3, minor=4, micro=3, releaselevel='final', serial=0)
>>>
The version_info attribute is available in all Python versions>= 2.0.
If you require a certain version, you can add a check in your module:
import sys
v = sys.version_info
if sys.version_info.major < 3:
raise Exception("Incompatible Python version: %d.%d" % (v.major, v.minor))
6 Comments
python -c "import sys; print sys.version_info" if you want to see the full version_info object or just python --version otherwise.export p=/usr/bin/python for instance, I can call the Python 2.7 interpreter on my system as $p.