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

标签 python string python-2.7 f-string

我已经编写了一个需要 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 运行时,它会在使用 f 字符串的行上返回语法错误。这不太容易理解。

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

谢谢

最佳答案

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 版本中。

关于python - 如果 Python2 在 .py 文件上运行,则尝试显示自定义错误由于语法错误而失败(.py 文件包含 f 字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59923047/

相关文章:

python - 不那么丑陋但可靠的方法来找到嵌入在字符串中的浮点值而不需要填充?

python - 日期 : British: day-month-year 的 Python 正则表达式

python - flask : How to serve static files from under the template directory?

PHP电子邮件管道

php - PHP替换字符串中的随机词

java - 将 java 代码转换为 python,IDE 建议?

安装 EB CLI 3.0 后出现 Python DistributionNotFound 错误

python - 带有子进程模块的进程永远不会停止运行

python - 我不明白代码行为

string - Scala 从字符串末尾删除字符