[英]Disable sys.stdout, err, .. to print in terminal?
我有一個 pyqt5 GUI,我從它開始。/mygui.py。 在 myguy.py 中,我添加了一個 class 以通過彈出窗口 window 處理異常(從http://timlehr.com/python-exception-boxt/hooks-with-message復制)。 然而,雖然異常現在出現在彈出窗口 window 中,但它們仍然被寫入終端。 我怎樣才能刪除這個? 這是上面鏈接中的 class,可能需要更改/添加:
import sys
import traceback
import logging
# basic logger functionality
log = logging.getLogger(__name__)
handler = logging.StreamHandler(stream=sys.stdout)
log.addHandler(handler)
def show_exception_box(log_msg):
"""Checks if a QApplication instance is available and shows a messagebox with the exception message.
If unavailable (non-console application), log an additional notice.
"""
if QtWidgets.QApplication.instance() is not None:
errorbox = QtWidgets.QMessageBox()
errorbox.setText("Oops. An unexpected error occured:\n{0}".format(log_msg))
errorbox.exec_()
else:
log.debug("No QApplication instance available.")
class UncaughtHook(QtCore.QObject):
_exception_caught = QtCore.Signal(object)
def __init__(self, *args, **kwargs):
super(UncaughtHook, self).__init__(*args, **kwargs)
# this registers the exception_hook() function as hook with the Python interpreter
sys.excepthook = self.exception_hook
# connect signal to execute the message box function always on main thread
self._exception_caught.connect(show_exception_box)
def exception_hook(self, exc_type, exc_value, exc_traceback):
"""Function handling uncaught exceptions.
It is triggered each time an uncaught exception occurs.
"""
if issubclass(exc_type, KeyboardInterrupt):
# ignore keyboard interrupt to support console applications
sys.__excepthook__(exc_type, exc_value, exc_traceback)
else:
exc_info = (exc_type, exc_value, exc_traceback)
log_msg = '\n'.join([''.join(traceback.format_tb(exc_traceback)),
'{0}: {1}'.format(exc_type.__name__, exc_value)])
log.critical("Uncaught exception:\n {0}".format(log_msg), exc_info=exc_info)
# trigger message box show
self._exception_caught.emit(log_msg)
根據您的邏輯,您將 StreamHandler 用作將日志發送到 sys.stdout(在本例中為終端)的處理程序,如果您不希望發送它,請使用 NullHandler:
log = logging.getLogger(__name__)
handler = logging.NullHandler() # StreamHandler(stream=sys.stdout)
log.addHandler(handler)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.