【问题标题】:Any check to see if the code written is in python 2.7 or 3 and above?是否检查编写的代码是否在 python 2.7 或 3 及更高版本中?
【发布时间】:2016-11-30 23:05:08
【问题描述】:

我有一个错误的长 python 项目,我正在尝试调试。它的混乱和无证。我熟悉python2.7。此项目中没有二进制文件。直截了当的想法是尝试将其作为python2.7 file.pypython3 file.py 执行,看看哪个有效。但正如我所说,它已经在很多地方出现了问题。所以他们都没有工作。是否有任何检查或方法或编辑器可以告诉我代码是用 python2.7 还是 python3 编写的?

【问题讨论】:

    标签: python python-3.x python-2.7 version identify


    【解决方案1】:

    尝试编译它。如果脚本使用特定于某个版本的语法,则编译将失败。

    $ python2 -m py_compile foo.py
    $ python3 -m py_compile foo.py
    

    【讨论】:

    • 可以将python2python3分别替换为py -2py -3
    • @AleSod:这就是你在 Windows 上的具体做法;在其他任何地方,py 都不存在。
    • 对 Python 初学者的提醒:这种方法不会捕获运行时错误,例如在一个 Python 版本与另一个版本中缺少模块导入。
    【解决方案2】:

    以下语句表示 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
       ...
    

    【讨论】:

      猜你喜欢
      • 2013-09-02
      • 2011-07-08
      • 2014-10-08
      • 1970-01-01
      • 2016-11-25
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      • 2016-06-17
      相关资源
      最近更新 更多