3.[Python]多線程程式Ctrl+C的優雅終止__Python

來源:互聯網
上載者:User

轉載請註明原始出處: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的部落格)或者為這篇文章點贊,謝謝。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.