How to throw an exception if a script is running with Python 2?

I have a script that should only run with Python 3. I want to give a good error message saying that this script should not run with python2 if the user tries to run it with Python 2.x

How should I do it? When I try to check the version of Python, it still throws an error, since Python parses the entire file before fulfilling my condition if.

If possible, I would prefer to do another script.

+4
source share
3 answers

You can write a start-script shell in which you import the actual script and catch errors for the syntax:

try:
    import real_module
except SyntaxError:
    print('You need to run this with Python 3')

, real_module.py Python 3, Python 3, .

, , script, , , 3. , script Python 3:

import sys
if sys.version_info[0] < 3:
    print('You need to run this with Python 3')
    sys.exit(1)

import real_module
+9

:

import sys
#sys.version gives you version number in this format
#(2, 5, 2, 'final', 0)
version=sys.version_info[0]

if version == 2:
   sys.exit("This script shouldn't be run by python 2 ")
+1
import sys
if (sys.version_info > (2, 0)):
   raise Exception('script should not be run with python2.x')

This will throw an error if the script runs under python version 2.x

+1
source

All Articles