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?

3
  • 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? Commented 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". Commented 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 below Commented Oct 31, 2018 at 15:57

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Might need to call raw_input as a function (raw_input())
It would return <built-in function raw_input>, so no, it won't fail if on Python 2.7. But the sys.version is definitely a much easier way to tell.
0

Try with version_info from sys package

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.