@@ -630,6 +630,7 @@ async def run_async(
630
630
self ,
631
631
pre_run : Optional [Callable [[], None ]] = None ,
632
632
set_exception_handler : bool = True ,
633
+ handle_sigint : bool = True ,
633
634
) -> _AppResult :
634
635
"""
635
636
Run the prompt_toolkit :class:`~prompt_toolkit.application.Application`
@@ -646,6 +647,8 @@ async def run_async(
646
647
:param set_exception_handler: When set, in case of an exception, go out
647
648
of the alternate screen and hide the application, display the
648
649
exception, and wait for the user to press ENTER.
650
+ :param handle_sigint: Handle SIGINT signal. Call the key binding for
651
+ `Keys.SIGINT`. (This only works in the main thread.)
649
652
"""
650
653
assert not self ._is_running , "Application is already running."
651
654
@@ -781,6 +784,15 @@ async def _run_async2() -> _AppResult:
781
784
self ._invalidated = False
782
785
783
786
loop = get_event_loop ()
787
+
788
+ if handle_sigint :
789
+ loop .add_signal_handler (
790
+ signal .SIGINT ,
791
+ lambda * _ : loop .call_soon_threadsafe (
792
+ self .key_processor .send_sigint
793
+ ),
794
+ )
795
+
784
796
if set_exception_handler :
785
797
previous_exc_handler = loop .get_exception_handler ()
786
798
loop .set_exception_handler (self ._handle_exception )
@@ -812,13 +824,17 @@ async def _run_async2() -> _AppResult:
812
824
if set_exception_handler :
813
825
loop .set_exception_handler (previous_exc_handler )
814
826
827
+ if handle_sigint :
828
+ loop .remove_signal_handler (signal .SIGINT )
829
+
815
830
return await _run_async2 ()
816
831
817
832
def run (
818
833
self ,
819
834
pre_run : Optional [Callable [[], None ]] = None ,
820
835
set_exception_handler : bool = True ,
821
836
in_thread : bool = False ,
837
+ handle_sigint : bool = True ,
822
838
) -> _AppResult :
823
839
"""
824
840
A blocking 'run' call that waits until the UI is finished.
@@ -843,6 +859,8 @@ def run(
843
859
`get_appp().create_background_task()`, so that unfinished tasks are
844
860
properly cancelled before the event loop is closed. This is used
845
861
for instance in ptpython.
862
+ :param handle_sigint: Handle SIGINT signal. Call the key binding for
863
+ `Keys.SIGINT`. (This only works in the main thread.)
846
864
"""
847
865
if in_thread :
848
866
result : _AppResult
@@ -852,7 +870,10 @@ def run_in_thread() -> None:
852
870
nonlocal result , exception
853
871
try :
854
872
result = self .run (
855
- pre_run = pre_run , set_exception_handler = set_exception_handler
873
+ pre_run = pre_run ,
874
+ set_exception_handler = set_exception_handler ,
875
+ # Signal handling only works in the main thread.
876
+ handle_sigint = False ,
856
877
)
857
878
except BaseException as e :
858
879
exception = e
0 commit comments