Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 930
0aslam0 Avatar asked Jul 27 '16 05:07

0aslam0


People also ask

How do I know if my Python code is 2 or 3?

If you want to determine whether Python2 or Python3 is running, you can check the major version with this sys. version_info. major . 2 means Python2, and 3 means Python3.

How do you tell what version of Python A script was written for?

You can check the version of Python that is running a program, at runtime. Then check the content of the sys. version_info property. This property returns the Python version as a tuple.

Can a program written in Python 2 run in Python 3?

We can convert Python2 scripts to Python3 scripts by using 2to3 module. It changes Python2 syntax to Python3 syntax. We can change all the files in a particular folder from python2 to python3.

Is code written in Python 3 is backward compatible with Python 2?

Python 3 is not backwards compatible with Python 2, so your code may need to be adapted. Please start migrating your existing your existing Python 2 code to Python 3.


2 Answers

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 
like image 95
Ignacio Vazquez-Abrams Avatar answered Sep 24 '22 16:09

Ignacio Vazquez-Abrams


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    ... 
like image 22
Han-Kwang Nienhuys Avatar answered Sep 22 '22 16:09

Han-Kwang Nienhuys