【问题标题】:Can I assert the python version before the interpreter parses the code?我可以在解释器解析代码之前断言 python 版本吗?
【发布时间】:2020-09-19 14:04:24
【问题描述】:

我想告诉用户他们应该使用哪个 python 版本:

import sys
assert sys.version_info >= (3, 6), "Use Python 3.6 or newer"
print(f"a format string")

但是,运行上述文件会产生语法错误:

$ python fstring.py. # default python is 2.7
  File "fstring.py", line 3
    print(f"a format string")
                           ^
SyntaxError: invalid syntax

是否可以在不将所有 f 字符串包装在 try 块内的情况下对每个文件执行此操作?

【问题讨论】:

  • 注意,您也不能将 f 字符串包装在 try 块中。 SyntaxErrors 在代码被编译时引发
  • f"If you see this in an error message, use Python 3.6 or newer"开始脚本? :-P 不会很漂亮,但可能会达到目的。

标签: python f-string version-detection


【解决方案1】:

不,这不可能在每个文件的基础上进行,因为在执行任何文件之前解析整个文件,因此在检查任何断言之前。出于同样的原因,try 也不起作用。

这可能起作用的唯一方法是,通过将代码放入字符串并调用eval,将部分代码的解析推迟到运行时,但是......不要那样做。您有两个明智的选择:根本不使用 f 字符串,或者让它失败并显示 SyntaxError 而不是您自己的自定义错误消息。

或者,如果您在 Unix 或 Linux 系统上工作,那么您可以将文件标记为可执行文件,并在开头给它一个 shebang 行,如 #!/usr/bin/python3.8,这样用户就不需要知道权限自己使用的版本。

如果您想按模块执行此操作,请参阅@Chris 的回答。

【讨论】:

  • 所有用户想要做的就是检查/打印当前运行的 Python 版本——当然他们可以使用 sys.version_info
  • @barny 这根本不是问题所在;我不明白你是如何阅读这个问题并得出这个结论的。
  • @barny 但他们不能这样做并在同一段源代码中使用 f 字符串
  • 所以,总结一下,如果您在 Python 脚本中有任何 f 字符串,您实际上无法明确告诉用户使用正确的 Python 版本,除非将所有 f 字符串更改为 format 样式.对?如果这是一个选项,您可以将文件重命名为 .py3 扩展名。不幸的是,这不是我的选择。
【解决方案2】:

如果您正在编写一个模块,您可以通过您的模块的__init__.py 来执行此操作,例如如果你有类似的东西

  • foo_module/
    • __init__.py
    • foo_module/
      • foo.py
    • setup.py

__init__.py 包含在哪里

import sys


assert sys.version_info >= (3, 6), "Use Python 3.6 or newer"

foo.py 包含

print(f"a format string")

例子:

Python 2.7.18 (default, Jun 23 2020, 19:04:42) 
[GCC 7.5.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from foo_module import foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "foo_module/__init__.py", line 4, in <module>
    assert sys.version_info >= (3, 6), "Use Python 3.6 or newer"
AssertionError: Use Python 3.6 or newer

【讨论】:

  • 这适用于每个模块,但问题是每个文件。
  • @kaya3,真的,我错过了问题中的“per-file”一词。不过,我将保留它,因为它可以帮助其他用户寻找模块的解决方案。您的答案对于单个文件的情况是正确的。
  • 这解决了我的问题,尽管我问了一个稍微不同的问题。我会接受另一个答案,但我赞成这个答案。
猜你喜欢
  • 2012-04-09
  • 2023-04-02
  • 2023-02-08
  • 2011-08-20
  • 1970-01-01
  • 1970-01-01
  • 2022-12-16
  • 2021-10-15
  • 1970-01-01
相关资源
最近更新 更多