首页 > 解决方案 > 如何创建成功的消息框或相应的 Python 错误消息?

问题描述

我创建了一个脚本来处理数据并将文件保存在某个位置。如果脚本成功运行且没有错误,我想显示一条消息,显示“任务已成功完成”。如果出现错误,例如PermissionError: [Errno 13] Permission denied: 'File.xlsx'然后我希望打印实际错误。

我可以包装我的脚本try,然后将错误放入except,我只是不知道要传递什么来让 Python 错误消息显示在except.

import ctypes

try:
    #Main script
    ctypes.windll.user32.MessageBoxW(0, "The task was completed successfully!", "Success", 1)


except:    
    #If there is an error, display the error.
    ctypes.windll.user32.MessageBoxW(0, "There is an error.", "Failure", 1)

如果有更好的方法,我绝对愿意接受。任何指导将不胜感激!

标签: python

解决方案


我通过以下方式得到了我想要的结果。

import sys

try:
    #Main Script
    ctypes.windll.user32.MessageBoxW(0, "The reports were processed successfully!", "Success", 0)

except: 
    e = str(sys.exc_info()[0]) ctypes.windll.user32.MessageBoxW(0, e, "Failure", 1)
    types.windll.user32.MessageBoxW(0, e, "Failure",0)

推荐阅读