Is there a standard way to make sure a python script will be interpreted by python2 and not python3? On my distro, I can use #!/usr/bin/env python2 as the shebang, but it se
I believe this will do what you want, namely test for a non-specific version of Python less than 3.x (as long as it doesn't contain a from __future__ import print_function
statement).
try:
py3 = eval('print')
except SyntaxError:
py3 = False
if py3: exit('requires Python 2')
...
It works by testing to see if print
is a built-in function as opposed to a statement, as it is in Python3. When it's not a function, the eval()
function will raise an exception, meaning the code is running on a pre-Python 3.0 interpreter with the caveat mentioned above.