簡體   English   中英

在Python中暫時忽略SIGINT

[英]Temporarily ignore SIGINT in Python

我想運行一堆需要一段時間的命令,但不能中斷(固件更新)。 如果較早收到簽名,我想退出。 我嘗試用一​​個在每次接收到SIGINT時都會計數的類來替換signal.SIG_IGN,但是在類迭代其計數器之后,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()

多虧了這些評論和更多的閱讀,我認為我理解了這個問題。 SIG_IGN版本將完全阻止信號通過。 該類將在哪里捕獲SIGINT中斷,但是該中斷仍將使它進入sleep 30 / unix命令? unix命令退出,但是python代碼忽略該中斷。 我不是這方面的100%,但是殺死unix命令的中斷可能是系統調用中斷,EINTR或IOError。 因此,不一定是SIGINT本身,而是SIGINT的副產品?

我認為這些鏈接可能會提供一些其他詳細信息: 處理(在python中)IOError的正確方法是什么:[Errno 4] multiprocessing.Queue.get引發的系統調用中斷

https://www.python.org/dev/peps/pep-0475/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM