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

后端 未结 4 1980
挽巷
挽巷 2020-12-15 04:10

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 f

相关标签:
4条回答
  • 2020-12-15 04:16

    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
    
    0 讨论(0)
  • 2020-12-15 04:24

    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
       ...
    
    0 讨论(0)
  • 2020-12-15 04:32

    add this line to the file:

    help()
    

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

    0 讨论(0)
  • 2020-12-15 04:37

    Use this in your code:

    import platform
    print platform.python_version()
    

    outputs a string: 2.7.10

    0 讨论(0)
提交回复
热议问题