繁体   English   中英

如果未使用所需的 python 版本,如何优雅退出?

[英]How to graceful exit if the required verion of python is not used?

我想制作 python 脚本来检查 python 解释器版本并仅执行所需版本的 python。

我想使用仅在 3.6 版之后可用的 f 字符串格式,因此准备了如下版本检查代码:

import sys

# Python version check
major, minor, micro, _, _ = sys.version_info
if (major, minor) < (3, 6):
    print("current python version: %d.%d" % (major, minor))
    print("this code requires python 3.6 for operation")
    sys.exit()
else:
    print(f"current python version:{major}.{minor:d}")

# use of f-string feature available from 3.6 version
pi = 3.141592
print(f"pi with precision 2 is {pi:.2f}")

我的意图是在未使用所需的 python 版本时优雅地退出并显示错误消息。 但请检查具有不同版本 python 的脚本,如下所示:

$ python --version
Python 2.7.12
$ python ./python_version_check.py
  File "./python_version_check.py", line 16
    print(f"current python version:{major}.{minor:d}")
                                                    ^
SyntaxError: invalid syntax

$ python3 --version
Python 3.5.2
$ python3 ./python_version_check.py
  File "./python_version_check.py", line 16
    print(f"current python version:{major}.{minor:d}")
                                                    ^
SyntaxError: invalid syntax

$ conda activate python3
$ python --version
Python 3.6.6 :: Anaconda, Inc.
$ python ./python_version_check.py
current python version:3.6
pi with precision 2 is 3.14

它不是优雅退出,而是在 3.6 版本 python 下生成 SyntaxErr。

我还尝试在版本检查部分使用 assert 语句,如下所示:

assert sys.version_info >= (3, 6), \
        "this code requires python 3.6 for operation"

但此代码无法按预期工作,因为“在编译时请求优化时,当前代码生成器不会为断言语句发出任何代码。”

文档说断言表达式可以更好地描述为等同于

if __debug__:
   if not expression: raise AssertionError

如何修改上面的代码以在 3.6 下的 python 版本上按预期顺利退出并打印错误消息?

您可以在 try catch 中使用 print,用于不同的 python 打印版本。

import sys

# Python version check
major, minor, micro, _, _ = sys.version_info
if (major, minor) < (3, 6):
    try:
        print("current python version: %d.%d" % (major, minor))
        print("this code requires python 3.6 for operation")
    except:
        print "current python version: %d.%d" % (major, minor)
        print "this code requires python 3.6 for operation"
    finally:
        exit()
else:
    print(f"current python version:{major}.{minor:d}")

# use of f-string feature available from 3.6 version
pi = 3.141592
print(f"pi with precision 2 is {pi:.2f}")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM