我如何使我的异步任务在后台运行并在前景中给我一个重复?

发布于 2025-02-12 03:50:55 字数 389 浏览 1 评论 0原文

我试图将我的头缠绕在Asyncio(Python 3.7)。

import asyncio
loop = asyncio.get_event_loop()
loop.set_debug(True)
async def tick():
    for i in range(3):
        print(i)
        asyncio.sleep(1)
    print("Finishing")

task = loop.create_task(tick())

目前,这似乎没有产生输出。我要做的是让它运行我的异步代码,同时在运行时将我返回回复。

我的希望是能够从Websocket接收数据,并且仍然能够在REPP中键入命令以探索收到的内容。

我在做什么错?

I'm trying to wrap my head around asyncio (Python 3.7).

import asyncio
loop = asyncio.get_event_loop()
loop.set_debug(True)
async def tick():
    for i in range(3):
        print(i)
        asyncio.sleep(1)
    print("Finishing")

task = loop.create_task(tick())

Currently, this seems to produce no output. What I'm trying to do is to get it run my async code, while simultaneously returning me to a REPL while it runs.

My hope is to be able to receive data from websockets, and still be able to type commands inside the REPL to explore what's received.

What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

以歌曲疗慰 2025-02-19 03:50:55

事实证明,除非您按以下方式启动Python,否则不可能执行异步任务。

python -m asyncio

It turns out it's not possible to run an async task while having a REPL, unless you start python as follows:

python -m asyncio
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文