将信号处理委托给python中的子进程 [英] Delegate signal handling to a child process in python

查看:39
本文介绍了将信号处理委托给python中的子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 python 脚本运行命令并将信号委托给它,例如 Ctrl+C?

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"])

我想让 child_proc 处理 Ctrl+C

推荐答案

我猜您的问题是您希望子进程接收 Ctrl-C 而不是让父 Python 进程终止?如果您的子进程为 Ctrl-C (SIGINT) 初始化了自己的信号处理程序,那么这可能会奏效:

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

现在您可以按 Ctrl-C(生成 SIGINT),Python 将忽略它,但 less 仍会看到它.

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).

这篇关于将信号处理委托给python中的子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆