如果这个全局变量定义在 main 中,为什么找不到它?

Why isn't this global variable found if it's defined in the main?

我制作了这个简单的脚本来尝试一些东西。基本上,它应该捕获应用程序 运行 期间发生的任何异常并断开与服务器的连接。

import sys
import traceback
from PyQt5.QtWidgets import *

class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        layout = QVBoxLayout()
        self.setLayout(layout)
        # Generate exception
        raise Exception('Oh no!')
    def foo(self):
        print('Bar')

def error_handler(etype, value, tb):
    global ex
    error_msg = ''.join(traceback.format_exception(etype, value, tb))
    print(error_msg)
    ex.foo()
    sys.exit(1)

if __name__ == '__main__':
    sys.excepthook = error_handler
    app = QApplication([])
    ex = Window()
    ex.show()
    app.exec_()

如果变量定义在 main 中,为什么错误处理程序无法找到该变量?

我以为 error_handler 在你定义 ex 之前执行了。因为我试过这个:

def function():
    global hello 
    print(hello)

if __name__ == '__main__':
    func = function
    hello = "world"
    func() #world

所以使用前需要定义ex:

if __name__ == '__main__':
    ex = Window() #defined it first
    sys.excepthook = error_handler
    app = QApplication([])
    ex.show()
    app.exec_()

问题的原因是在 ex 分配给任何东西之前引发了异常。

如果在定义ex之前需要处理异常,处理程序不需要假定它可以使用ex

一个简单的处理方法可能是在它准备好之前将 ex 设置为 None,并在处理程序中检查它。

def error_handler(etype, value, tb):
    error_msg = ''.join(traceback.format_exception(etype, value, tb))
    print(error_msg)
    if ex: # Check if ex is ready
        ex.foo()
    sys.exit(1)

if __name__ == '__main__':
    ex = None
    sys.excepthook = error_handler
    app = QApplication([])
    ex = Window()
    ex.show()
    app.exec_()