Skip to main content
 首页 » 编程设计

python之信号处理程序退出,但程序继续运行

2025年05月04日9yyy_WW

显然,当我的信号处理程序退出时,我的程序继续运行。甚至在“日志完成,立即关闭”之后引发的异常也证明了这一点。 有人可以解释为什么会这样吗?注意功能已经简化

^Clog   Ctrl-C 
backup  State: not_span 328, pos 22, all_cycles 19 
backup  backup complete, you may force exit now 
log     Done, close now 
Traceback (most recent call last): 
  File "singleEdger.py", line 219, in <module> 
    mySingleEdger.outputAllCycles() 
  File "singleEdger.py", line 141, in outputAllCycles 
    r = self.returnCycle( self.dfs_tree, self.not_span[self.pos]) 
  File "singleEdger.py", line 72, in returnCycle 
    udfs = nx.Graph(dfs)                    # The trick is to make it undirected 
  File "/var/lib/python-support/python2.6/networkx/graph.py", line 86, in __init__ 
    convert.from_whatever(data,create_using=self) 
  File "/var/lib/python-support/python2.6/networkx/convert.py", line 76, in from_whatever 
    "Input is not a correct NetworkX graph." 
networkx.exception.NetworkXError: Input is not a correct NetworkX graph. 

这些是引用函数

    def sigHandler(self, arg1, arg2): 
        out('log', 'Ctrl-C') 
        self.backup() 
        out('log', 'Done, close now') 
        exit() 
 
 
    def outputAllCycles(self): 
        while self.pos < len(self.not_span): 
            r = self.returnCycle( self.dfs_tree, self.not_span[self.pos]) 
            if r: 
                self.all_cycles.append( r ) 
                for each in r:      # now it's [ (3,4), (5,6) ] 
                    each = (sellHash(each[0]), sellHash( each[1]) ) 
                    self.outfo.write( each[0] +'\t'+ each[1] ) 
                    self.outfo.write( '\n') 
                self.outfo.write( '\n') 
            self.pos += 1 
        out( "singleEdger", "outputAllCycles done") 
 
 
    def backup(self): 
        out( 'backup', 'State: not_span %i, pos %i, all_cycles %i' % ( len(self.not_span), self.pos, len(self.all_cycles)) ) 
        out( 'backup', 'backup complete, you may force exit now') 

请您参考如下方法:

我不认为你的代码还在运行。尽管它在代码中的位置,但不能保证异常输出出现在最终打印消息之前。异常输出将转到 STDERR,但您的打印语句将转到 STDOUT;在此示例中,两者都恰好写入同一终端设备。两者是独立缓冲的,所以输出的顺序不是强制的;也就是说,您无法从输出的相对位置推断出任何信息。

如果将打印语句放入单元测试中,您可以在单元测试框架中看到相同的现象。