I have a python program which I have made work in both Python 2 and 3, and it has more functionality in Python 3 (using new Python 3 features).
My script currently starts #!/usr/bin/env python, as that seems to be the mostly likely name for a python executable. However, what I'd like to do is "if python3 exists, use that, if not use python".
I would prefer not to have to distribute multiple files / and extra script (at present my program is a single distributed python file).
Is there an easy way to run the current script in python3, if it exists?
-
So you already check inside the script if it is being executed by Python 2 or 3, but need an external script to check if Python 3 exists?user8408080– user84080802018年10月30日 15:01:54 +00:00Commented Oct 30, 2018 at 15:01
-
I would like to not run an external script. What I (think) I want is a way to add to the top of my script "is this python2, but python3 is installed? If so, re-exec the script in python3".Chris Jefferson– Chris Jefferson2018年10月31日 15:25:44 +00:00Commented Oct 31, 2018 at 15:25
-
So you plan to make this program for users, that don't know how to run shell script? If not, I would just wrap the program in the shell script I posted belowuser8408080– user84080802018年10月31日 15:57:40 +00:00Commented Oct 31, 2018 at 15:57
3 Answers 3
Another better method modified from this question is to check the sys.version:
import sys
py_ver = sys.version[0]
Original answer: May not be the best method, but one way to do it is test against a function that only exist in one version of Python to know what you are running off of.
try:
raw_input
py_ver = 2
except NameError:
py_ver = 3
if py_ver==2:
... Python 2 stuff
elif py_ver==3:
... Python 3 stuff
Try with version_info from sys package
Comments
Maybe I didn't quite get what you want. I understood: You want to look if there is Python 3 installed on the Computer and if so, use it. Inside the script you can check the version with sys.version as Idlehands mentioned. To get the latest version you might want to use a small bash script like this
py_versions=($(ls /usr/bin | grep 'python[0-9]\.[0-9]$'))
${py_versions[-1]} your_script.py
This searches the output of ls for all python versions and stores them in py_versions. Thankfully the output is already sorted, so the last element in the array will be the latest version.