首页 > 解决方案 > Python:如何添加钩子以控制(停止/启动/暂停/恢复)第二个程序的无限循环?

问题描述

我的代码启动了一个 while 循环并一直运行,直到我用 Control-C 硬杀死它。我想通过添加一些与代码进行通信的方式使其更优雅地停止,从而使它变得更好。最后,我想通过一个带有开始/停止按钮和暂停/恢复按钮的 PyQt 应用程序来控制它。我如何在代码中添加一些钩子以允许这种控制?

当前代码如下所示:

def handle_notifications(dao_notifications):

    # fetch notifications
    while True:

        try:
            # store received notifications into the database
            for notification in next(notifications_generator):
                dao_notifications.insert(notification)

        except StopIteration:
            continue


def notifications_generator():

    # create a socket to listen for notification events
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sockt:

        # bind the listener port of the local host to the socket instance
        sockt.bind((_LOCAL_IP_ADDRESS, _LISTENER_PORT))

        # start the socket listening
        sockt.listen()

        # continually receive notifications and yield
        while True:

            # accept a communication connection on the socket
            connection, connection_address = sockt.accept()
            with connection:

                # receive bytes of data from the socket, decode as Unicode string
                xml = connection.recv(20480).decode("utf-8")

                # only try to yield values if we've actually received data
                if len(xml) > 0:

                    # parse the XML into a dictionary
                    notifications_soap = xmltodict.parse(xml)

                    # yield the notification messages as an iterable
                    notifications = \
                        notifications_soap["SOAP-ENV:Envelope"]["SOAP-ENV:Body"]["wsnt:Notify"]["wsnt:NotificationMessage"]
                    yield notifications

也许这是信号处理的用例?例如,我可以为 SIGINT 编写一个处理程序来暂停/暂停执行(保持睡眠直到另一个恢复信号到达),并为 SIGTERM 在退出前优雅地清理一个处理程序,然后 PyQt 应用程序将发出适当的信号来控制执行。有没有一个好的/简单的例子?

标签: pythonpyqtpyside2

解决方案


推荐阅读