我正在使用Python来管理一些模拟。我使用以下代码构建参数并运行程序:
pipe = open('/dev/null', 'w')
pid = subprocess.Popen(shlex.split(command), stdout=pipe, stderr=pipe)
我的代码可以处理不同的信号。按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)
[...]
无论我做什么,程序都会接收到SIGINT信号,而我只希望我的Python脚本能够接收到。我该如何做?
我也尝试了:
signal.signal(signal.SIGINT, signal.SIG_IGN)
pid = subprocess.Popen(shlex.split(command), stdout=pipe, stderr=pipe)
signal.signal(signal.SIGINT, signal.SIG_DFL)
尝试运行程序,但结果相同:程序捕获了SIGINT信号。
谢谢!