python / cpython

The Python programming language
https://www.python.org
Other
63.52k stars 30.43k forks source link

Improved signal handling initialization for embedded Python #111400

Open whitevegagabriel opened 1 year ago

whitevegagabriel commented 1 year ago

Feature or enhancement

Proposal:

If Python has been initialized via

Py_InitializeEx(0);

then importing signal as

import signal

should by default skip setting up signal handlers.


I understand that this proposal is not a small ask. Currently, the flag to skip signals is used to determine whether to init signal. If someone calls import signal later on, then the user has shown clear intent to diverge from the initial state of skipping signal handling setup in Python.

However, the problem is that while I can avoid calling import signal in this embedded environment, it is hard to avoid it as a transitive dependency.

For example, the library asyncio calls import signal.

Of course, I can change my signal handler from SIG_DFL to anything else. However, if I do that, then the usefulness of Py_InitializeEx(0); is diminished.

Ultimately, I think it is more intuitive to think that, if I initialize Python via Py_InitializeEx(0), calling import signal will also skip setting up signal handlers.

And for SIGINT, for example, users would still have the freedom to call signal.signal(signal.SIGINT, signal.default_int_handler) if they really want KeyboardInterrupt.

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

https://discuss.python.org/t/asyncio-skipping-signal-handling-setup-during-import-for-python-embedded-context/37054

BTOdell commented 9 months ago

For embedded Python, it makes even more sense (to me) to have a way to completely disable the signal module. This would allow a host environment to be confident that code running in the embedded environment cannot disrupt the host environment's signal handling.

This train of thought could go even further: Classify and disable all modules/functions that could disrupt the host environment (e.g. sys.exit, entire subprocess module?, etc). I know this is out of scope for this feature request, but just thinking out loud here.

hackhaslam commented 3 weeks ago

I agree that it's surprising that importing signal (directly or transitively) breaks Ctrl+C for applications that embed Python. I was able to make one of the workarounds work for me.

I will say that I'm not calling Py_InitializeEx(0), but Py_InitializeFromConfig with install_signal_handlers set to 0 (or the equivalent of initializing the isolated config).