Any check to see if the code written is in python 2.7 or 3 and above?

瘦欲@ 提交于 2019-11-27 15:42:59

问题


I have a buggy long python project that I am trying to debug. Its messy and undocumented. I am familiar with python2.7. There are no binaries in this project. The straight forward idea is to try execute it as python2.7 file.py or python3 file.py and see which works. But as I said it is already buggy at a lot of places. So none of them is working. Is there any check or method or editor that could tell me if the code was written in python2.7 or python3?


回答1:


Attempt to compile it. If the script uses syntax specific to a version then the compilation will fail.

$ python2 -m py_compile foo.py
$ python3 -m py_compile foo.py



回答2:


add this line to the file:

help()

this should automatically print the version along with the default help interface. remember to remove it later.




回答3:


Use this in your code:

import platform
print platform.python_version()

outputs a string: 2.7.10



来源:https://stackoverflow.com/questions/38604451/any-check-to-see-if-the-code-written-is-in-python-2-7-or-3-and-above

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!