我有一個巨大的 Python 腳本,它的執行需要很長時間,在后臺運行,并且以我看不到它的列印輸出的方式啟動。
為了能夠在腳本完成時收到通知,我提出了一個適當的訊息框,但如果腳本由于錯誤而退出,我將不會收到通知。
下面是演示我所說的內容的最小代碼:
import math
try:
i = int('Oxff')
except ValueError:
... # some code handling the exception
... ; pass ; ... # some further code
import no_such_module # in code not handled unexpected error
... ; pass ; ... # some further code
# Message box notifying about successfull script run:
from tkinter import Tk
root = Tk()
root.geometry('10x10 ' str(root.winfo_screenwidth()-10) ' ' str(root.winfo_screenheight()-10))
from tkinter.messagebox import Message
Message(title="Success", message="No Error", master=root).show()
因此,當我的 Python 腳本由于意外而失敗并且因此不在代碼處理錯誤中時,我根本不會收到通知。
我不想包含整個腳本代碼try: ... except: ...
以處理意外和未處理的代碼錯誤。
在 Python 中是否有一種方法可以撰寫一個函式,該函式將在意外錯誤終止腳本的情況下運行并顯示一個訊息框?
uj5u.com熱心網友回復:
換成你自己的
uj5u.com熱心網友回復:
atexit您可以在 Python 中撰寫一個通知函式,該函式將在 Python 退出時運行,因為使用內置模塊的代碼未處理錯誤
。借助此模塊,您可以注冊將在 Python 腳本退出時執行的函式。
下面的函式代碼如果在 Python 腳本開始時執行,將在 Python 腳本退出時引發一個訊息框:
def get_notified_about_error():
import atexit
global atexit_handler
def atexit_handler():
print("Script EXIT because of an ERROR")
from tkinter import Tk
root = Tk()
root.geometry('10x10 ' str(root.winfo_screenwidth()-10) ' ' str(root.winfo_screenheight()-10))
from tkinter.messagebox import Message
Message(title="atexit_handler()", message="Error occured", master=root).show()
atexit.register(atexit_handler)
get_notified_about_error()
為了避免atexit_handler()在 Python 腳本無錯誤退出時運行已注冊的函式,請使用以下命令在 Python 腳本的最后一行取消注冊該函式:
import atexit
atexit.unregister(atexit_handler)
在演示解決方案的整個代碼下方:
# REQUIRED HEADER:
def get_notified_about_error():
import atexit
global atexit_handler
def atexit_handler():
print("Script EXIT because of an ERROR")
from tkinter import Tk
root = Tk()
root.geometry('10x10 ' str(root.winfo_screenwidth()-10) ' ' str(root.winfo_screenheight()-10))
from tkinter.messagebox import Message
Message(title="atexit_handler()", message="Error occured", master=root).show()
atexit.register(atexit_handler)
get_notified_about_error()
# SCRIPT CODE:
import math
try:
i = int('Oxff')
except ValueError:
... # some code handling the exception
... ; pass ; ... # some further code
import no_such_module # in code not handled unexpected error
... ; pass ; ... # some further code
# Message box notifying about successfull script run:
from tkinter import Tk
root = Tk()
root.geometry('10x10 ' str(root.winfo_screenwidth()-10) ' ' str(root.winfo_screenheight()-10))
from tkinter.messagebox import Message
Message(title="Success", message="No Error", master=root).show()
# REQUIRED TRAILER:
import atexit
atexit.unregister(atexit_handler)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/504281.html
