python 2 code: if python 3 then sys.exit()

Question:

I have a large piece of Python 2 only code. It want to check for Python 3 at the beginning, and exit if python3 is used. So I tried:

import sys

if sys.version_info >= (3,0):
    print("Sorry, requires Python 2.x, not Python 3.x")
    sys.exit(1)

print "Here comes a lot of pure Python 2.x stuff ..."
### a lot of python2 code, not just print statements follows

However, the exit does not happen. The output is:

$ python3 testing.py 
  File "testing.py", line 8
        print "Here comes a lot of pure Python 2.x stuff ..."
                                                        ^
SyntaxError: invalid syntax

So, it looks like python checks the whole code before executing anything, and hence the error.

Is there a nice way for python2 code to check for python3 being used, and if so print something friendly and then exit?

Asked By: superkoning

||

Answers:

Python will byte-compile your source file before starting to execute it. The whole file must at least parse correctly, otherwise you will get a SyntaxError.

The easiest solution for your problem is to write a small wrapper that parses as both, Python 2.x and 3.x. Example:

import sys
if sys.version_info >= (3, 0):
    sys.stdout.write("Sorry, requires Python 2.x, not Python 3.xn")
    sys.exit(1)

import the_real_thing
if __name__ == "__main__":
    the_real_thing.main()

The statement import the_real_thing will only be executed after the if statement, so the code in this module is not required to parse as Python 3.x code.

Answered By: Sven Marnach
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.