在IPython 8.22.1 / Python 3.11中设置事件循环失败

0 投票
1 回答
49 浏览
提问于 2025-04-14 18:16

下面这个反应是正常的吗?还是我的Python安装有问题?我刚刚花了几个小时阅读相关内容,感觉这应该是可以正常工作的。要不然,我到底哪里做错了呢?

Python 3.11.6 (main, Oct  8 2023, 05:06:43) [GCC 13.2.0]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.22.2 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import asyncio

In [2]: asyncio.get_event_loop()
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[2], line 1
----> 1 asyncio.get_event_loop()

File /usr/lib/python3.11/asyncio/events.py:677, in BaseDefaultEventLoopPolicy.get_event_loop(self)
    674     self.set_event_loop(self.new_event_loop())
    676 if self._local._loop is None:
--> 677     raise RuntimeError('There is no current event loop in thread %r.'
    678                        % threading.current_thread().name)
    680 return self._local._loop

RuntimeError: There is no current event loop in thread 'MainThread'.

In [3]: asyncio.set_event_loop(asyncio.new_event_loop())

In [4]: asyncio.get_event_loop()
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[4], line 1
----> 1 asyncio.get_event_loop()

File /usr/lib/python3.11/asyncio/events.py:677, in BaseDefaultEventLoopPolicy.get_event_loop(self)
    674     self.set_event_loop(self.new_event_loop())
    676 if self._local._loop is None:
--> 677     raise RuntimeError('There is no current event loop in thread %r.'
    678                        % threading.current_thread().name)
    680 return self._local._loop

RuntimeError: There is no current event loop in thread 'MainThread'.

你看,[2]这一行说没有当前的事件循环。所以我在[3]创建了一个。但是在[4]那里,还是没有事件循环。

是我搞错了,还是解释器有问题呢?

1 个回答

0

我找到了问题的解决办法,希望对遇到同样问题的人有帮助。让我感到惊讶的是,问题并不出在Python本身,而是在IPython上。这让我花了很长时间才搞明白。

在我写这段话的时候,IPython里有一个未解决的bug。所以,问题真的是出在解释器上,而不是我自己:https://github.com/ipython/ipython/issues/14297

等你看到这段话的时候,这个bug可能已经修复了。

撰写回答