gpt4 book ai didi

python - 如何让 python 进程保持事件状态——正确的方法

转载 作者:太空宇宙 更新时间:2023-11-04 08:25:33 25 4
gpt4 key购买 nike

我已经看到很多这个问题,但我对答案不满意。我知道像 Django 和 Flask/Werkzeug 这样的服务器程序有 startserver/run 方法,可以使进程保持事件状态,直到收到停止信号。

我想实现类似的东西,但我不知道该怎么做。我认为永恒循环是一种糟糕的方法,因为它浪费了处理时间。我宁愿不使用第三方库。

我的程序必须保持事件状态以等待回调、与服务器通信、监视其内部状态等。

伪代码:

import ...

class Main():
def __init__():
self.sensors = sensors.register()
self.database = remote.connect()
self.running = True

def start():
""" this is what I assume is bad """
while self.running:
pass

def stop():
self.running = False
self.cleanup()

def cleanup():
self.database.disconnect()
self.sensors.unregister()

最佳答案

有一个不是特定于 python 的通用范例来处理这种称为事件循环的情况。如果您在 Internet 上搜索它,您会发现几个实现它的库。如果您使用 asyncio,则不需要第三方库,因为它随 python3 一起提供。我建议您熟悉这个概念,网上有很多例子。参见例如this教程。我们从那里得到这个例子:

import asyncio

async def work():
while True:
await asyncio.sleep(1)
print("Task Executed")

loop = asyncio.get_event_loop()
try:
asyncio.ensure_future(work())
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
print("Closing Loop")
loop.close()

希望对您有所帮助。

关于python - 如何让 python 进程保持事件状态——正确的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57603548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com