-1

I want to check whether each file in a list of files is written in Python2 or Python3. This would greatly improve productivity and would allow teams to see what files are running on old versions of Python or new versions.

Can this be done?

Vlad
  • 1
  • 2
    generally you can't know what version of python a particular source file targets though you can detect if there's syntax errors in version and eliminate those – anthony sottile Nov 28 '21 at 01:21

1 Answers1

0
import subprocess
import exceptions
try:
    subprocess.run(["python2", "-m py_compile foo.py"])
except ValueError, e:
    # pyhon3 or bad code
    

if python2 can compile the code, it means it is a python2 compilable file, we may assume it is a python2 file. you can also check if it is a python3 in except block. just replace python2 to python3

prof_FL
  • 156
  • 9