Python:如何添加钩子来控制(停止/启动/暂停/恢复)第二个程序中的无限循环?

时间:2019-02-22 00:42:26

标签: python pyqt pyside2

我有一些代码可以启动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应用程序将发出适当的信号来控制执行。有一个好的/简单的例子吗?

0 个答案:

没有答案