在#python IRC-Channel (Freenode)中有人帮助我指出了
preexec_fn
的参数
subprocess.Popen(...)
:
If
preexec_fn
被设置为一个可调用的
对象,这个对象将在
子进程中调用,就在
子进程中调用。(仅限Unix)
Thus, the following code solves the problem (UNIX only):
import subprocess
import signal
def preexec_function():
# Ignore the SIGINT signal by setting the handler to the standard
# signal handler SIG_IGN.
signal.signal(signal.SIGINT, signal.SIG_IGN)
my_process = subprocess.Popen(
["my_executable"],
preexec_fn = preexec_function
Note:实际上,信号并没有被阻止到达子进程。相反,该preexec_fn上面的方法覆盖了信号的默认处理程序,所以信号被忽略了。因此,这个解决方案可以 not work if the subprocess overwrites the SIGINT处理程序再次。
另一个说明。这个解决方案适用于各种子进程,也就是说,它不限于用Python编写的子进程。例如,我正在为之编写的专用服务器实际上是用Java编写的。