rem*_*ezx 5 python subprocess signals control-c
如何从python脚本运行命令并委托给它的信号如Ctrl+C?
我的意思是当我跑步时:
from subprocess import call
call(["child_proc"])
Run Code Online (Sandbox Code Playgroud)
我想child_proc处理Ctrl+C
我猜你的问题是你希望子进程接收 Ctrl-C 并且不让父 Python 进程终止?如果您的子进程为 Ctrl-C (SIGINT) 初始化了自己的信号处理程序,那么这可能会起作用:
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
Run Code Online (Sandbox Code Playgroud)
现在你可以按 Ctrl-C (它会生成 SIGINT),Python 将忽略它,但less仍然会看到它。
然而,只有当子进程正确设置其信号处理程序时,这才有效(否则这些信号处理程序是从父进程继承的)。