我正在尝试调试一个错误的长python项目。它凌乱而无证。我熟悉python2.7。这个项目中没有二进制文件。直截了当的想法是尝试将其作为python2.7 file.py
或python3 file.py
执行,看看哪些有效。但正如我所说,它已经在许多地方出现了问题。所以他们都没有工作。是否有任何检查或方法或编辑器可以告诉我代码是用python2.7还是python3编写的?
答案 0 :(得分:22)
尝试编译它。如果脚本使用特定于版本的语法,则编译将失败。
$ python2 -m py_compile foo.py
$ python3 -m py_compile foo.py
答案 1 :(得分:5)
以下语句表示Python 2.x:
import exceptions
for i in xrange(n):
...
print 'No parentheses'
# raw_input doesn't exist in Python 3
response = raw_input()
try:
...
except ValueError, e:
# note the comma above
...
这些建议使用Python 2,但可能会作为Python 3代码中的旧习惯出现:
'%d %f' % (a, b)
# integer divisions
r = float(i)/n # where i and n are integer
r = n / 2.0
这些很有可能是Python 3:
# f-strings
s = f'{x:.3f} {foo}'
# range returns an iterator
foo = list(range(n))
try:
...
except ValueError as e:
# note the 'as' above
...
答案 2 :(得分:-3)
将此行添加到文件中:
help()
这应该会自动打印版本以及默认的帮助界面。记得以后删除它。
答案 3 :(得分:-3)
在您的代码中使用它:
import platform
print platform.python_version()
输出一个字符串: 2.7.10