Skip to content

Commit

Permalink
Fix IPython inputhook (workaround).
Browse files Browse the repository at this point in the history
  • Loading branch information
jonathanslenders committed Nov 14, 2023
1 parent 2e2175a commit 8c60193
Showing 1 changed file with 32 additions and 4 deletions.
36 changes: 32 additions & 4 deletions src/prompt_toolkit/application/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -956,10 +956,17 @@ def run_in_thread() -> None:
set_exception_handler=set_exception_handler,
handle_sigint=handle_sigint,
)
if inputhook is None:
# No loop installed. Run like usual.
return asyncio.run(coro)
else:

def _called_from_ipython() -> bool:
try:
return (
"IPython/terminal/interactiveshell.py"
in sys._getframe(3).f_code.co_filename
)
except BaseException:
return False

if inputhook is not None:
# Create new event loop with given input hook and run the app.
# In Python 3.12, we can use asyncio.run(loop_factory=...)
# For now, use `run_until_complete()`.
Expand All @@ -969,6 +976,27 @@ def run_in_thread() -> None:
loop.close()
return result

elif _called_from_ipython():
# workaround to make input hooks work for IPython until
# https://github.com/ipython/ipython/pull/14241 is merged.
# IPython was setting the input hook by installing an event loop
# previously.
try:
# See whether a loop was installed already. If so, use that.
# That's required for the input hooks to work, they are
# installed using `set_event_loop`.
loop = asyncio.get_event_loop()
except RuntimeError:
# No loop installed. Run like usual.
return asyncio.run(coro)
else:
# Use existing loop.
return loop.run_until_complete(coro)

else:
# No loop installed. Run like usual.
return asyncio.run(coro)

def _handle_exception(
self, loop: AbstractEventLoop, context: dict[str, Any]
) -> None:
Expand Down

0 comments on commit 8c60193

Please sign in to comment.