diff --git a/tests/signalkernel.py b/tests/signalkernel.py index 65fdb687..74e9fa42 100644 --- a/tests/signalkernel.py +++ b/tests/signalkernel.py @@ -30,7 +30,7 @@ async def shutdown_request(self, stream, ident, parent): if os.environ.get("NO_SHUTDOWN_REPLY") != "1": await super().shutdown_request(stream, ident, parent) - def do_execute( + async def do_execute( self, code, silent, store_history=True, user_expressions=None, allow_stdin=False ): code = code.strip() @@ -47,12 +47,31 @@ def do_execute( elif code == "env": reply["user_expressions"]["env"] = os.getenv("TEST_VARS", "") elif code == "sleep": - try: - time.sleep(10) - except KeyboardInterrupt: - reply["user_expressions"]["interrupted"] = True + import ipykernel + + if ipykernel.version_info < (7, 0): + # ipykernel before anyio. + try: + time.sleep(10) + except KeyboardInterrupt: + reply["user_expressions"]["interrupted"] = True + else: + reply["user_expressions"]["interrupted"] = False else: + # ipykernel after anyio. + from anyio import create_task_group, open_signal_receiver, sleep + + async def signal_handler(cancel_scope, reply): + with open_signal_receiver(signal.SIGINT) as signals: + async for _ in signals: + reply["user_expressions"]["interrupted"] = True + cancel_scope.cancel() + return + reply["user_expressions"]["interrupted"] = False + async with create_task_group() as tg: + tg.start_soon(signal_handler, tg.cancel_scope, reply) + tg.start_soon(sleep, 10) else: reply["status"] = "error" reply["ename"] = "Error"