我有一些需要能夠處理SIGINT的Python代碼。爲此我使用的是這樣的:在Python中處理SIGINT以外的信號的「正確」方式?
def mymethod(*params):
obj = MyObj(params)
try:
obj.do_some_long_stuff()
except KeyboardInterrupt:
obj.cleanup()
真棒,真的很簡單。耶,Python很棒!
但是,我現在還需要處理其他信號,即SIGTSTP和SIGQUIT。我想要做的是類似的事情。下面是一些僞證明什麼,我想用SIGTSTP(我希望這是很清楚)做:
def mymethod(*params):
obj = MyObj(params)
try:
obj.do_some_long_stuff()
catch SIGINT:
obj.cleanup()
catch SIGTSTP:
log_stop(obj) # Log that we stopped obj (add info about stop signal happening in obj-specific log file)
raise SIGTSTP # Do normal SIGTSTP behavior as if we didn't catch the signal
看來,去這裏的方法是使用信號模塊。不過,我的問題是,然後我就可以再也不能盡我所能與訪問對象狀態KeyboardInterruptException
:
import os
import signal
def handler(signum, frame):
print "I can't access obj from here anymore!" # How to access obj from here?
signal.signal(signum, signal.SIG_DFL)
os.kill(os.getpid(), signum) # Rethrow signal, this time without catching it
def mymethod(*params):
obj = MyObj(params)
signal.signal(signal.SIGTSTP, handler)
obj.do_some_long_stuff()
那麼,如何解決這個問題,即處理同時還具有一些訪問對象的信號我正在與?
有趣,沒想到那個!這似乎是最優雅的解決方案。謝謝。 – jjst
剛剛實施,是的:優雅和工作。 – bux