python-slack-sdk: Jupyter lab - "RuntimeError: Cannot run the event loop while another loop is running"
Bug Report
Reproducible in:
slackclient version: 2.0.1
python version: 3.7
OS version(s): MACOSX
Description
The code below, produces an error (see screenshot) when run in Jupyter Lab, and not when run from a simple python script. This comes after trying to upgrade slack client from a previous version, when I was successfully able to run from my Jupyter lab notebook
from slack import WebClient
sc = WebClient(token='<my-token>')
sc.chat_postMessage(channel='<my-channel>', text='testing2')
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 7
- Comments: 26 (14 by maintainers)
I’m running into similar issues in Jupyter notebooks with no clear workaround. It seems that the default way to use the client (i.e.
run_async=False
) should completely sidestep any async operations. Instead, it seems like the client is trying to define all operations as async operations and then manage the loop itself whenrun_async=False
. Unfortunately, there are all kinds of issues when a library tries to manage the loop itself because that often conflicts with parent packages that also manage the loop. (This is an annoying aspect of Python, I think.)For what it’s worth, I’ve run into this before and found that nest_asyncio handles this situation quite nicely. For packages that I manage that use
asyncio
I just sticknest_asyncio.apply()
in the__init__.py
and things mostly just work, including in notebooks.Alternatively, for users who don’t control the
slack
package, the following will likely workThanks for reporting this! I believe the reason you’re seeing this error is due to the fact that Jupyter lab creates and runs the main event loop. Therefore all async functions (i.e. “API calls”) must be scheduled for execution on the event loop instead of attempting to create a new loop in the same thread.
I’m currently working on a patch to resolve this. I’ll update this once it’s shipped.
@c-goosen Thanks for diving into this issue. Your troubleshooting helped guide me to an underlying issue where I attempted to create an event loop when there was one running already. I’ve since removed this code in #466 (specifically this code.).
@ecatkins I believe if you update to 2.1.0 it’ll resolve your issues. One thing to keep in mind is that if Jupyter lab runs and manages the event loop then running the WebClient in async mode may be necessary. I’d try it without it first though.
I’ll keep this issue open for a little while to confirm it’s fixed.
I can confirm @stevenmanton’s workaround works for me:
Let me share the updates on this issue. My pull request #662 is going to be the solution to this issue. The fix will be included in the next minor version - 2.6.0. The version will be out within two weeks. Refer to https://github.com/slackapi/python-slackclient/issues/476#issuecomment-620645518 for more info.