Skip to main content
 首页 » 编程设计

python之在所有错误消息中打印 python 版本

2024年10月01日9sharpest

我有一个由用户调用的 python 脚本,例如 python script.py 或 python3 script.py。如果此脚本引发错误,则使用哪个 python 版本很重要。

当然,我可以向用户询问用于执行 script.py 的命令,但这可能无法解析 python 版本。 python 可以是 python3.4 或 python2.7 的别名。

我知道我可以在脚本中打印 sys.version。但我不想在每次运行该脚本时都打印它,只是在发生错误的情况下。

所以另一个想法是将整个脚本简单地包装在 try, except block 中。

import sys 
try: 
    # original content of script.py 
except: 
    print("Using python version {0}".format(sys.version)) 
    raise 

然而,这对我来说看起来不是很 pythonic。那么是否有更优雅的解决方案,即在每条错误信息中添加sys.version?

这个问题不是 How do I check what version of Python is running my script? 的重复问题,因为我不想检查版本信息。我的脚本应该与所有版本的 python 一起运行。但是,应将自定义消息(在本例中为 sys.version)附加到堆栈跟踪。

请您参考如下方法:

是的。

>>> import sys 
>>> sys.version 

I do not want to print it in every run of that script, just in the case where an error has occurred.

使用try, except声明