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

Trying to show custom error if Python2 is run on a .py file fails due to syntax error (.py file contains f-strings)

我编写了一个需要 Python 3 的程序(我们将不支持 Python 2)但是我想包含一条错误消息来通知用户,如果他们不小心 运行 Python2.

中的 .py 文件

我尝试在文件的前几行中使用版本检查来做到这一点:

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 文件实际上 运行 使用 Python 2 时,它 return 在使用 f 字符串的行上出现语法错误。这个不太好理解。

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

谢谢

Is there a way I can force the program to fail on the version check and thus, return the more useful error message?

不,因为 Python 首先必须能够解析和编译您的文件。这意味着您只能在文件中使用 支持的语法 ,Python 2 无法解析 f 字符串。

您必须将您的项目分成多个模块,并且在 要导入的第一个模块(例如,顶级 __init__.py 文件一个包),在导入依赖于 Python-3 特定语法的其他模块之前检查版本。

或者根本不包括此类检查。相反,为您的项目元数据设置 python_requires,这样它就不会首先安装在较旧的 Python 版本中。