Reputation: 7157
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?
Upvotes: 0
Views: 86
Reputation: 2468
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.
Upvotes: 0
Reputation: 13868
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
Upvotes: 1