Skip to content

Commit 1cd8c29

Browse files
authored
gh-91880: add try/except around signal.signal (#91881)
Fixes gh-91880.
1 parent 54d068a commit 1cd8c29

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

Lib/asyncio/runners.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,13 @@ def run(self, coro, *, context=None):
100100
and signal.getsignal(signal.SIGINT) is signal.default_int_handler
101101
):
102102
sigint_handler = functools.partial(self._on_sigint, main_task=task)
103-
signal.signal(signal.SIGINT, sigint_handler)
103+
try:
104+
signal.signal(signal.SIGINT, sigint_handler)
105+
except ValueError:
106+
# `signal.signal` may throw if `threading.main_thread` does
107+
# not support signals (e.g. embedded interpreter with signals
108+
# not registered - see gh-91880)
109+
signal_handler = None
104110
else:
105111
sigint_handler = None
106112

Lib/test/test_asyncio/test_runners.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
import contextvars
44
import gc
55
import re
6+
import signal
67
import threading
78
import unittest
89

910
from unittest import mock
11+
from unittest.mock import patch
1012
from test.test_asyncio import utils as test_utils
1113

1214

@@ -374,6 +376,23 @@ async def coro():
374376
with asyncio.Runner() as runner:
375377
with self.assertRaises(asyncio.CancelledError):
376378
runner.run(coro())
379+
380+
def test_signal_install_not_supported_ok(self):
381+
# signal.signal() can throw if the "main thread" doensn't have signals enabled
382+
assert threading.current_thread() is threading.main_thread()
383+
384+
async def coro():
385+
pass
386+
387+
with asyncio.Runner() as runner:
388+
with patch.object(
389+
signal,
390+
"signal",
391+
side_effect=ValueError(
392+
"signal only works in main thread of the main interpreter"
393+
)
394+
):
395+
runner.run(coro())
377396

378397

379398
if __name__ == '__main__':

0 commit comments

Comments
 (0)