@@ -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,9 @@ 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 if possible. This will call
651
+ the `<sigint>` key binding when a SIGINT is received. (This only
652
+ works in the main thread.)
649
653
"""
650
654
assert not self ._is_running , "Application is already running."
651
655
@@ -781,6 +785,15 @@ async def _run_async2() -> _AppResult:
781
785
self ._invalidated = False
782
786
783
787
loop = get_event_loop ()
788
+
789
+ if handle_sigint :
790
+ loop .add_signal_handler (
791
+ signal .SIGINT ,
792
+ lambda * _ : loop .call_soon_threadsafe (
793
+ self .key_processor .send_sigint
794
+ ),
795
+ )
796
+
784
797
if set_exception_handler :
785
798
previous_exc_handler = loop .get_exception_handler ()
786
799
loop .set_exception_handler (self ._handle_exception )
@@ -812,12 +825,16 @@ async def _run_async2() -> _AppResult:
812
825
if set_exception_handler :
813
826
loop .set_exception_handler (previous_exc_handler )
814
827
828
+ if handle_sigint :
829
+ loop .remove_signal_handler (signal .SIGINT )
830
+
815
831
return await _run_async2 ()
816
832
817
833
def run (
818
834
self ,
819
835
pre_run : Optional [Callable [[], None ]] = None ,
820
836
set_exception_handler : bool = True ,
837
+ handle_sigint : bool = True ,
821
838
in_thread : bool = False ,
822
839
) -> _AppResult :
823
840
"""
@@ -843,6 +860,8 @@ def run(
843
860
`get_appp().create_background_task()`, so that unfinished tasks are
844
861
properly cancelled before the event loop is closed. This is used
845
862
for instance in ptpython.
863
+ :param handle_sigint: Handle SIGINT signal. Call the key binding for
864
+ `Keys.SIGINT`. (This only works in the main thread.)
846
865
"""
847
866
if in_thread :
848
867
result : _AppResult
@@ -852,7 +871,10 @@ def run_in_thread() -> None:
852
871
nonlocal result , exception
853
872
try :
854
873
result = self .run (
855
- pre_run = pre_run , set_exception_handler = set_exception_handler
874
+ pre_run = pre_run ,
875
+ set_exception_handler = set_exception_handler ,
876
+ # Signal handling only works in the main thread.
877
+ handle_sigint = False ,
856
878
)
857
879
except BaseException as e :
858
880
exception = e
0 commit comments