【发布时间】:2017-03-14 22:04:00
【问题描述】:
我想运行一堆需要一段时间但不能中断的命令(固件更新)。如果之前收到信号,我想退出。我尝试将 signal.SIG_IGN 替换为每次收到 SIGINT 时都会计数的类,但在类迭代其计数器后,SIGINT 仍将通过主 Python 脚本。
忽略它很容易工作:
import subprocess
import signal
def dont_interrupt_me():
"""Run bash command."""
print "Keyboard interrupt ignored during update process."
# Stops keyboard interrupts during the Popen
sigint_stopper = signal.signal(signal.SIGINT, signal.SIG_IGN)
bash_cmd = subprocess.Popen(['sleep', '10'])
bash_cmd.wait()
install_return_code = bash_cmd.returncode
# Return signint to normal
signal.signal(signal.SIGINT, sigint_stopper)
# if ctrl_c_earlier:
# sys.exit(1)
return install_return_code
for each in range(1,10):
dont_interrupt_me()
我的 SigintIgnore 类尝试不是不起作用:
import subprocess
import signal
class SigintIgnore(object):
"""Count the number of sigint's during ignore phase."""
def __init__(self):
"""Init count to 0."""
self.count = 0
self.exit_amount = 10
def __call__(self, first, second):
"""Init count to 0."""
self.count += 1
print "\nself.count: " + str(self.count)
print "first: " + str(first)
print "second: " + str(second)
if self.count > 1:
print("Press 'ctrl + c' " +
str(self.exit_amount - self.count) +
" more times to force exit.")
if self.count > self.exit_amount:
sys.exit(EXIT_USER_CHOICE)
def dont_interrupt_me():
"""Run bash command."""
counter = SigintIgnore()
print "Keyboard interrupt ignored during update process."
sigint_stopper = signal.signal(signal.SIGINT, counter)
# Stops keyboard interrupts during the update calls
bash_cmd = subprocess.Popen(['sleep', '10'])
bash_cmd.wait()
install_return_code = bash_cmd.returncode
signal.signal(signal.SIGINT, sigint_stopper)
if counter.count > 1:
sys.exit(1)
return install_return_code
for each in range(1,10):
dont_interrupt_me()
【问题讨论】:
-
您的 SigintIgnore 课程有什么具体问题?
-
@user2357112:根据 OP 问题顶部的文字,听起来
KeyboardInterrupt仍在上升。 -
@Kevin:这可能是他们想说的,但很难说。还有其他合理的解读。无论如何,我认为不会是 KeyboardInterrupt 在这里提出的;可能是 IOError 什么的,但 KeyboardInterrupt 不太可能。
-
您使用的是哪个 Python 版本? Signal handling behavior changed in 3.5,虽然我不知道更改是否达到
subprocess.Popen.wait。 -
Python 2.7。它看起来不像 IOError,因为我没有尝试,但它仍然退出而不抛出任何东西。