Is there a way to prevent a python 3 script from being called in python 2?

This is actually a harder problem to implement well that you might at first think.

Suppose you have the following code:

import platform
import sys

if platform.python_version().startswith('2'):
    # This NEVER will be executed no matter the version of Python
    # because of the two syntax errors below...
    sys.stdout.write("You're using python 2.x! Python 3.2+ required!!!")
    sys.exit()     
else:
    # big program or def main(): and calling main() .. whatever
    # later in that file/module:
    x, *y=(1,2,3)      # syntax error on Python 2...
    # or
    print 'test'       # syntax error on Python 3...

One of the two syntax errors under the else clause is generated BEFORE the if is actually executed no matter the version of Python used to run it. Therefore, the program will not gracefully exit as you might expect; it will fail with a syntax error no matter what.

The workaround is to put your actual program in an external file/module and wrap in a try/except this way:

try:
    import Py3program    # make sure it has syntax guaranteed to fail on 
                         # Python 2 like    x, *y=1,2,3
except SyntaxError:
    sys.stdout.write(error message)
    sys.exit()

# rest of the Python 3 program...

If your TA will execute the file with a shebang, that would be a better approach still. Perhaps ask the TA how he will run your script?


How about starting the program like so:

#!/usr/bin/env python
# -*- coding: utf8 -*-

import sys

if sys.version_info < (3,0,0):
    print(__file__ + ' requires Python 3, while Python ' + str(sys.version[0] + ' was detected. Terminating. '))
    sys.exit(1)

You can do:

import sys
print(sys.version_info)

As of Python 2.7 you can also use:

print(sys.version_info.major, sys.version_info.minor, sys.version_info.micro)

You can use the value of sys.version_info to print a warning when the Python version currently running isn't as desired.

You can also use:

import platform
print(platform.python_version())