Is there a standard way to make sure a python script will be interpreted by python2 and not python3?

前端 未结 8 1034
旧时难觅i
旧时难觅i 2020-12-31 00:56

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

8条回答
  •  失恋的感觉
    2020-12-31 01:30

    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.

提交回复
热议问题