3

我想告诉用户他们应该使用哪个 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 块中?

4

2 回答 2

6

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

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

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

如果您想在每个模块的基础上执行此操作,请参阅@Chris 的答案。

于 2020-09-19T14:11:01.447 回答
3

如果你正在编写一个模块,你可以通过你的模块来做到这一点__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
于 2020-09-19T14:17:10.983 回答