如果脚本运行的解释器版本比要求的早,如何让它退出?

问题描述 投票:2回答:1

我想让我的命令行脚本需要Python v3.6以上的版本。我有一个名为 quit_on_27.py 如下。

import sys

if sys.version_info < (3, 6):
    sys.exit("Please use Python 3.6+")


def hello(name:str):
    print(f'Hello, {name}!')


if __name__ == '__main__':
    hello('Jon')

当我用Python 2. 7把这个作为脚本运行时,

> python .\quit_on_27.py
  File ".\quit_on_27.py", line 7
    def hello(name:str):
                  ^
SyntaxError: invalid syntax

我也有同样的 SyntaxError 当我使用 assert sys.version_info >= (3, 6) 如上所述 我如何检查运行我的脚本的Python版本? 来代替上面的条件。

我想使用 typing 和 f 字符串以及其他在 Python 2.7 中没有的特性,我想让用户知道使用较新版本的 Python,而不是只看到一个 SyntaxError。

我怎样才能让这个脚本优雅而有帮助地退出?

这比 如何让一个python脚本安全地退出自己? 因为我在问为什么我的条件没有按照我的意图根据运行脚本的 Python 版本工作。

注意:我的脚本在Python 3.6中确实能按预期运行。

python python-2.7 typechecking
1个回答
1
投票

正如我 (和 @Klaus D.) 所建议的,处理这种情况的一种方法是,当使用的语法与早期版本的 interpeter 不兼容时,将使用该语法的代码放到一个不同的脚本中,并且只使用 import 它的版本等于或高于所需的最低版本。

话虽如此,但 另一个 的方法是将违规代码 "隐藏 "在一个字符串中,只有在版本检查通过时才执行该字符串。

这就是我的意思。

import sys

if sys.version_info < (3, 6):
    sys.exit("Please use Python 3.6+")

exec("""
    def hello(name:str):
        print(f'Hello, {name}!')
""")

if __name__ == '__main__':
    hello('Jon')

后一种方法可能与你正在使用的其他工具不兼容(比如mypy) 这取决于它们有多 "聪明"... ...

© www.soinside.com 2019 - 2024. All rights reserved.