Skip to content

Instantly share code, notes, and snippets.

@mikenerone
Last active November 5, 2020 22:01
Show Gist options
  • Save mikenerone/3640fdd450b4ca55ee8df4d4da5a7165 to your computer and use it in GitHub Desktop.
Save mikenerone/3640fdd450b4ca55ee8df4d4da5a7165 to your computer and use it in GitHub Desktop.
"""
Example of running an embedded IPython shell inside an already-running trio loop with working autoawait (it's handy
to be able to start an interactive REPL with your application environment fully initialized). This works as is,
and it really should be this easy. Unfortunately, due to https://github.com/ipython/ipython/issues/680,
this currently results in an error on process exit when IPython's atexit-registered method calls fail to save the
input history. This bug should be fixed IMO (using atexit is a questionable design choice in the first place given
the embedding feature of IPython IMO). Sadly, working around it is significantly less trivial. See
https://gist.github.com/mikenerone/786ce75cf8d906ae4ad1e0b57933c23f for an example of that full solution.
"""
from functools import partial
import IPython
import trio
def trio_embedded_runner(coro):
return trio.from_thread.run(lambda: coro)
async def main():
print("In trio loop")
await trio.to_thread.run_sync(partial(IPython.embed, using=trio_embedded_runner))
print("Exiting trio loop")
trio.run(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment