轉載請註明原始出處:http://blog.csdn.net/a464057216/article/details/47678781
多線程編程中,經常會遇到怎麼讓程式優雅地停止的問題,舉一個簡單的例子:
#!/usr/bin/env python# -*- coding: utf-8 -*# Written by - CSDN:Mars Loo的部落格import threading, timedef printA(): while True: print 'a' time.sleep(1)def printB(): while True: print 'b' time.sleep(1)if __name__ == '__main__': try: a = threading.Thread(target = printA) b = threading.Thread(target = printB) a.start() b.start() a.join() b.join() except Exception, exc: print exc
printA和printB兩個線程分別不斷的隔1s列印字母a和b,但是這樣的程式跑起來以後用Ctrl+C根本殺不掉,只有關掉終端視窗或者kill掉這個進程:
mars@mars-Ideapad-V460:~/test$ python ctrl.py ab^C^Cab^C^Ca b^Ca bab
如果把兩個進程都設定成守護進程,倒是可以用Ctrl+C終止程式:
# Written by - CSDN:Mars Loo的部落格 a = threading.Thread(target = printA) b = threading.Thread(target = printB) a.setDaemon(True) a.start() b.setDaemon(True) b.start() while True: pass
執行結果:
mars@mars-Ideapad-V460:~/test$ python ctrl.pyabba^CTraceback (most recent call last): File "ctrl.py", line 25, in <module> while True:KeyboardInterrupt
但是上面的方法又會在螢幕上輸出醜陋的traceback資訊,下面介紹一種優雅的方法:
#!/usr/bin/env python# -*- coding: utf-8 -*# Written by - CSDN:Mars Loo的部落格import threading, time, signalimport sysdef printA(): while True: print 'a' time.sleep(1)def printB(): while True: print 'b' time.sleep(1)def quit(signum, frame): print 'You choose to stop me.' sys.exit()if __name__ == '__main__': try: signal.signal(signal.SIGINT, quit) signal.signal(signal.SIGTERM, quit) a = threading.Thread(target = printA) b = threading.Thread(target = printB) a.setDaemon(True) a.start() b.setDaemon(True) b.start() while True: pass except Exception, exc: print exc
執行結果:
mars@mars-Ideapad-V460:~/test$ python ctrl.py abb aa b^CYou choose to stop me.
如果覺得我的文章對您有協助,歡迎關注我(CSDN:Mars Loo的部落格)或者為這篇文章點贊,謝謝。