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?
Asked
Active
Viewed 3.0k times
51
2 Answers
59
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

Ignacio Vazquez-Abrams
- 776,304
- 153
- 1,341
- 1,358
-
1It is possible to replace `python2` and `python3` with `py -2` and `py -3` respectively. – AleSod Nov 29 '17 at 13:17
-
7@AleSod: That's the way you do it on Windows specifically; anywhere else, `py` doesn't exist. – ShadowRanger Dec 17 '20 at 18:06
-
2Just a heads up for Python beginners: This approach doesn't catch runtime errors, such as missing module imports in one python version versus the other. – StephenGodderidge Sep 02 '21 at 23:18
16
The following statements indicate 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
...
These suggest Python 2, but may occur as old habits in Python 3 code:
'%d %f' % (a, b)
# integer divisions
r = float(i)/n # where i and n are integer
r = n / 2.0
These are very likely 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
...

Han-Kwang Nienhuys
- 3,084
- 2
- 12
- 31