我正在开发一个启动多个进程和数据库连接的python脚本.我偶尔想用Ctrl+ C信号杀死脚本,我想做一些清理工作.
在Perl我会这样做:
$SIG{'INT'} = 'exit_gracefully';
sub exit_gracefully {
print "Caught ^C \n";
exit (0);
}
Run Code Online (Sandbox Code Playgroud)
我如何在Python中模拟这个?
我目前正在为shell中运行的专用服务器开发包装器.包装器通过子进程生成服务器进程,并观察并响应其输出.
必须明确地为专用服务器提供一个命令才能正常关闭.因此,CTRL-C不得访问服务器进程.
如果我捕获KeyboardInterrupt异常或覆盖python中的SIGINT处理程序,服务器进程仍然会收到CTRL-C并立即停止.
所以我的问题是:如何防止子进程接收CTRL-C/Control-C/SIGINT?
我正在使用python来管理一些模拟.我构建参数并使用以下命令运行程序:
pipe = open('/dev/null', 'w')
pid = subprocess.Popen(shlex.split(command), stdout=pipe, stderr=pipe)
Run Code Online (Sandbox Code Playgroud)
我的代码处理不同的信号.Ctrl + C将停止模拟,询问我是否要保存,然后正常退出.我有其他信号处理程序(例如强制数据输出).
我想要的是向我的python脚本发送一个信号(SIGINT,Ctrl + C),它将询问用户他想要发送给程序的信号.
阻止代码工作的唯一因素是,无论我做什么,Ctrl + C都将"转发"到子进程:代码将捕获并退出:
try:
<wait for available slots>
except KeyboardInterrupt:
print "KeyboardInterrupt catched! All simulations are paused. Please choose the signal to send:"
print " 0: SIGCONT (Continue simulation)"
print " 1: SIGINT (Exit and save)"
[...]
answer = raw_input()
pid.send_signal(signal.SIGCONT)
if (answer == "0"):
print " --> Continuing simulation..."
elif (answer == "1"):
print " --> Exit and save."
pid.send_signal(signal.SIGINT)
[...]
Run Code Online (Sandbox Code Playgroud)
所以无论我做什么,程序都会收到我只希望我的python脚本看到的SIGINT.我怎样才能做到这一点???
我也尝试过: …