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

标签 python python-3.x

我已经看到很多这个问题,但我对答案不满意。 我知道像 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/

相关文章:

python - 为 python/pandas 中的每一行分配组平均值

python - NMF 作为 Python Scikit 中的聚类方法

python - Jupyter Notebook 找不到 IQSharp

python - 如何将 Python 3 转换为 Python 2 代码?

python - 删除 Qt 中小部件之间的细边框

python - Plotly:如何向 Choropleth 添加数据标签

javascript - 在 PythonAnywhere 上托管基于 Tornado 的 Python 应用程序时出现 "Error running WSGI application"

python - 在python中求解联立方程

python-3.x - 如何使用 DICT 数据类型 (boto3) 更新 DynamoDB 表

python - 如何从字符串中删除特殊字符