我制作了一个python程序,我使用.exe将其打包到auto-py-to-exe中,如果出现错误,程序将显示错误并立即关闭,因此无法读取错误。
我不想说:
try:
#code
except:
#print something我希望它打印出原来的python错误,并使它不立即关闭。
发布于 2022-07-02 15:42:21
有多种方法可以做到这一点。
使用回溯模块
使用exc的示例
import traceback
def hello():
return 1/0
def my_program():
try:
hello()
except Exception as _: # try to avoid generic exception handlers
traceback.print_exc()
if __name__ == "__main__":
my_program()使用日志记录模块
在许多情况下,使用日志模块可能很有用,例如,可以使用一些CLI标志或env变量启用更详细的日志记录。您还可以将所有日志转储到稍后可以解析的文件中。
简单测井实例
import logging
def cfg():
fmt = "%(levelname)s %(asctime)s - %(message)s"
logging.basicConfig(filename="my_program.log", filemode="w", format=fmt, level=logging.ERROR)
def hello():
return 22/0
def my_program():
try:
hello()
except Exception as _:
logging.exception("an internal error happened!")
if __name__ == "__main__":
cfg()
my_program()https://stackoverflow.com/questions/72840128
复制相似问题