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

PyCharm调试模式下WindowsSelectorEventLoopPolicy引发Task不可调用异常

Windows下PyCharm调试模式切换Selector事件循环触发TypeError异常

问题场景

  • 代码在普通运行模式、或使用默认Proactor事件循环的调试模式下均可正常执行
  • 默认Proactor策略会导致应用中loop.add_reader()/loop.add_writer()抛出NotImplementedError,无法使用
  • 切换为WindowsSelectorEventLoopPolicy后,普通运行正常,但调试模式下触发TypeError: 'Task' object is not callable异常

简化示例代码

import asyncio
import os
import sys

if sys.version_info >= (3, 8) and os.name == "nt":
    # 用于支持loop.add_reader等方法
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    # 该策略可解决当前调试报错,但会导致add_reader/add_writer失效
    # asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())

async def main() -> None:
    print("foo")

if __name__ == '__main__':
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        pass

运行结果

  • 普通运行模式:
foo
  • 调试模式报错信息:
Exception in callback <Task pending name='Task-1'
    coro=<main() running at C:\...\a.py:21>
    cb=[_run_until_complete_cb() at C:\... Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib\asyncio\base_events.py:181]>())
handle: <Handle <Task pending name='Task-1'
    coro=<main() running at C:\...\a.py:21>
    cb=[_run_until_complete_cb() at C:\... Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib\asyncio\base_events.py:181]>())>
Traceback (most recent call last):
  File "C:\... Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib\asyncio\events.py", line 84, in _run
    self._context.run(self._callback, *self._args)
TypeError: 'Task' object is not callable

环境信息

  • Windows应用商店Python 3.11
  • PyCharm 2025.1.2(Build #PY-251.26094.141)

解决方案

1. 显式创建事件循环替代asyncio.run()

修改代码,手动创建并管理事件循环,避免调试器钩子与asyncio.run()的冲突:

import asyncio
import os
import sys

if sys.version_info >= (3, 8) and os.name == "nt":
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

async def main() -> None:
    print("foo")

if __name__ == '__main__':
    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.run_until_complete(main())
    except KeyboardInterrupt:
        pass
    finally:
        loop.close()

2. 调整PyCharm调试器配置

  • 打开Run/Debug Configurations
  • 选择当前调试配置,切换到Configuration标签页
  • 勾选Emulate terminal in output console选项
  • 保存后重新启动调试

3. 版本适配

  • 可尝试降级Python至3.10或更早版本,该兼容性问题在旧版本中可能不存在
  • 关注PyCharm官方更新,等待JetBrains修复该调试器与Selector事件循环的兼容bug

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 19:53:13