python - 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 应用程序将发出适当的信号来控制执行。有没有一个好的/简单的例子?
解决方案
推荐阅读
- javascript - 如何确保我的函数一次只作用于一个元素?(转发更多细节)
- javascript - JavaScript:递归函数无法正确处理 Promise
- c - pow() 有时有时在 gcc 中找不到 w/o -lm 开关
- r - SAS proc 表示 R 中的等价物
- java - 通过保留现有规则向单例 KieContainer 添加新规则
- jquery - jQuery在滚动之前获取滚动位置以在全屏时使用scrollTop()位置临时禁用滚动
- django - 在 Django 中,如何重命名用户模型?
- r - 计算每行超过 60 的值的数量
- firebase - FIRESTORE :具有多个 where 子句的查询流
- json - Flutter/Dart Json 序列化