代码之家  ›  专栏  ›  技术社区  ›  SLater01

如果在.py文件上运行Python2由于语法错误而失败,则尝试显示自定义错误(.py文件包含f字符串)

  •  1
  • SLater01  · 技术社区  · 5 年前

    我尝试在文件的前几行中使用版本检查来执行此操作:

    import sys
    if not sys.version_info[0] == 3:
        sys.exit('You need to run this with Python 3')
    
    # Lots of other code here....
    
    # And then...
    foo = 2
    bar = 3
    print(f"Some message that uses f-strings like this: variables are {foo} {bar}")
    

    但是,当.py文件实际使用Python2运行时,它在使用f字符串的行上返回语法错误。这不太容易理解。

    有没有办法可以强制程序在版本检查时失败,从而返回更有用的错误消息?

    谢谢

    1 回复  |  直到 5 年前
        1
  •  1
  •   Martijn Pieters    5 年前

    有没有办法可以强制程序在版本检查时失败,从而返回更有用的错误消息?

    支持的语法 在文件中,Python 2无法解析f字符串。

    您必须将项目分成多个模块,并且在 要导入的第一个模块 (比如说,最高层 __init__.py

    或者 . 相反,设置 python_requires