Delegate signal handling to a child process in python

怎甘沉沦 提交于 2019-12-19 19:40:19

问题


How can I run a command from a python script and delegate to it signals like Ctrl+C?

I mean when I run e.g:

from subprocess import call
call(["child_proc"])

I want child_proc to handle Ctrl+C


回答1:


I'm guessing that your problem is that you want the subprocess to receive Ctrl-C and not have the parent Python process terminate? If your child process initialises its own signal handler for Ctrl-C (SIGINT) then this might do the trick:

import signal, subprocess

old_action = signal.signal(signal.SIGINT, signal.SIG_IGN)
subprocess.call(['less', '/etc/passwd'])
signal.signal(signal.SIGINT, old_action)         # restore original signal handler

Now you can hit Ctrl-C (which generates SIGINT), Python will ignore it but less will still see it.

However this only works if the child sets its signal handlers up properly (otherwise these are inherited from the parent).



来源:https://stackoverflow.com/questions/24936107/delegate-signal-handling-to-a-child-process-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!