You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyCharm报‘Coroutine create_task未等待’警告的原因与解决疑问

asyncio创建异步任务时PyCharm警告的疑问

场景说明

我正在使用Python和PyCharm,尝试通过asyncio实现数据库写入的异步卸载,过程中遇到了IDE警告问题。

核心代码逻辑

  1. 主任务启动方式:
db_logging_monitoring_task = asyncio.create_task(start_logging_jobs_sniffer())
tasks.append(db_logging_monitoring_task)
await gather(*tasks)

其中start_logging_jobs_sniffer是一个包含无限循环的异步函数,负责从队列中获取任务:

# 等待jobs_queue中的任务
async def start_logging_jobs_sniffer(self):
    while True:
        try:
            job = await self.logging_jobs_queue.get()

# 向jobs_queue添加任务的异步函数
async def make_logging_job(self, params):
    job = self.LoggingJob(params)
    await self.logging_jobs_queue.put(job)
  1. 后台轮询任务:
    有一个每5秒执行一次的后台监控任务,轮询后会调用make_logging_job生成日志任务:
async def poll(self, interval: int):
    if self.is_config_applied:
        while True:
            # ... 此处省略轮询并生成polling_results的逻辑

            asyncio.create_task(make_logging_job(
                params={
                    **self.polling_results
                },
            ))

问题详情

PyCharm对上述asyncio.create_task的调用抛出警告:

Coroutine 'create_task' is not awaited

我特意不使用await,因为希望make_logging_job能和其他任务并行执行,实际运行也符合预期——该任务确实在后台并行运行,不会阻塞其他操作。

我不理解PyCharm为何会触发这个警告,有没有更规范的创建后台任务的方式?

另外我发现,把创建的任务赋值给一个变量就能抑制警告,且任务依然正常在后台运行:

test = asyncio.create_task(make_logging_job(
    params={
        **self.polling_results
    },
))

但我不清楚为什么这样会有效,毕竟赋值变量并不会触发协程的等待操作。


内容的提问来源于stack exchange,提问作者Vanillaice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 22:28:16