Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw exception if script is run with Python 2?

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

How do I do this? When I try checking the Python version, it still throws an error, as Python parses the whole file before executing my if condition.

If possible, I'd rather not make another script.

like image 922
AbdealiJK Avatar asked Jul 06 '15 08:07

AbdealiJK


4 Answers

None of these properly work as, as others have mentioned SyntaxErrors are parsed first, also doing except SyntaxError does not work either.

The best solution is a wrapper module, but if due to other technical or political reasons you cannot create another module in your code you can do the following very dirty trick:

z, *y=1,2,3,4 #This script requires requires python 3! A Syntax error here means you are running it in python2!

The result in python2.7 will be:

  File "notpython2.py", line 3
    z, *y=1,2,3,4 #This script requires requires python 3! A Syntax error here means you are running it in python2!
       ^
SyntaxError: invalid syntax

Yes the code is ugly, but if anyone can think of a better solution notwithstanding a new module please add it here.

like image 150
Benjamin Goodacre Avatar answered Oct 27 '22 22:10

Benjamin Goodacre


You can write a wrapper start-script in which you only import your actual script and catch for syntax errors:

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

Then, when real_module.py uses Python 3 syntax that would throw an exception when used with Python 3, the above message is printed out instead.

Of course, instead of just importing the script, you could also first check the version, and then import it when the version is 3. This has the benefit that you will still see syntax errors of your actual script even when you run it with 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
like image 25
poke Avatar answered Oct 27 '22 21:10

poke


Try this:

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 ")
like image 37
Haris Kovačević Avatar answered Oct 27 '22 23:10

Haris Kovačević


import sys
if (sys.version_info > (2, 0)):
   raise Exception('script should not be run with python2.x')

This will raise error if script is running under 2.x python version

like image 43
shashank verma Avatar answered Oct 27 '22 23:10

shashank verma