Last active
June 9, 2021 00:42
-
-
Save evan-burke/af32de4268948747c0765bd8913e8340 to your computer and use it in GitHub Desktop.
jupter & asyncio issues
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Jupyter runs its own event loop, so trying to work with asyncio causes problems in Jupyter. | |
# Errors are most commonly: | |
# RuntimeError: This event loop is already running | |
## NOTE: as of IPython 7.0, released in late 2018, this may not be needed, per: | |
# https://blog.jupyter.org/ipython-7-0-async-repl-a35ce050f7f7 | |
# However, await(x) can be used anywhere in Jupyter, but will error on a standalone script. | |
# Use asyncio.run(x) or something for .py scripts as described in https://docs.python.org/3/library/asyncio-task.html | |
# Solution: | |
import nest_asyncio | |
nest_asyncio.apply() | |
# However - you'll still want to avoid calling loop.close(); | |
# this package does not apply to that function, which will still error out if you try it within jupyter. | |
# If you need to use loop.close(), maybe detect if in Jupyter with something like this - | |
# Or apply nest_asyncio based on output from this. | |
def isnotebook(): | |
try: | |
shell = get_ipython().__class__.__name__ | |
if shell == 'ZMQInteractiveShell': | |
return True # Jupyter notebook or qtconsole | |
elif shell == 'TerminalInteractiveShell': | |
return False # Terminal running IPython | |
else: | |
return False # Other type (?) | |
except NameError: | |
return False # Probably standard Python interpreter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment