0

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?

Chris Jefferson
  • 7,225
  • 11
  • 43
  • 66
  • 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 Oct 30 '18 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 Oct 31 '18 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 below – user8408080 Oct 31 '18 at 15:57

3 Answers3

1

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
r.ook
  • 13,466
  • 2
  • 22
  • 39
  • Might need to call raw_input as a function (`raw_input()`) – Nordle Oct 30 '18 at 15:03
  • 1
    It would return ``, so no, it won't fail if on Python 2.7. But the `sys.version` is definitely a much easier way to tell. – r.ook Oct 30 '18 at 15:05
0

Try with version_info from sys package

Krilosax
  • 13
  • 2
0

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.

user8408080
  • 2,428
  • 1
  • 10
  • 19