我正在运行一个使用PyQt创建的应用程序,它基本上从OPC服务器读取信息,并在每次有新数据时更新绘图。
我希望每次关闭应用程序时都能安全地从OPC服务器断开连接。这包括用户手动关闭窗口以及可能发生的任何运行时错误。它会是这样的:
from opcua import Client
from matplotlib.backends.qt_compat import QtWidgets
class ApplicationWindow_Realtime(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(ApplicationWindow_Realtime, self).__init__(parent)
self.opc_url = 'opc.tcp://127.0.0.1:53530/UA/Sim'
self.opc_initialize()
## DO STUFF
## Connect to OPC
def opc_initialize(self):
self.client = Client(self.opc_url)
self.client.connect()
## OTHER METHODS
# Disconnect if window is closed
def closeEvent(self, event):
self.client.disconnect()
我想知道如果在运行应用程序时运行时发生任何错误,是否有某种方法可以调用self.client.disconnect()
。我找到了this question,但接受的答案始于“警告:如果你想要这样的东西,很可能你不会......但如果你真的想......”,那么我不确定这是不是解决问题的方法。
我会做类似于你链接的答案,但我会在类本身内定义它。
from functools import wraps
def _emergency_disconnect(the_func):
@wraps(the_func)
def wrapper(*args, **kwargs):
output = None
try:
output = the_func(*args, **kwargs)
except:
#args[0] will always be self
args[0].client.disconnect()
if output != None:
return output
return wrapper
然后你可以用它来装饰你的功能
@_emergency_disconnect
def myFunction(myArg):
pass
每当方法调用导致错误时,这将导致调用self.client.disconnect()。