How to terminate a Python script

前端 未结 10 1079
予麋鹿
予麋鹿 2020-11-22 04:34

I am aware of the die() command in PHP which exits a script early.

How can I do this in Python?

10条回答
  •  再見小時候
    2020-11-22 05:11

    I've just found out that when writing a multithreadded app, raise SystemExit and sys.exit() both kills only the running thread. On the other hand, os._exit() exits the whole process. This was discussed in "Why does sys.exit() not exit when called inside a thread in Python?".

    The example below has 2 threads. Kenny and Cartman. Cartman is supposed to live forever, but Kenny is called recursively and should die after 3 seconds. (recursive calling is not the best way, but I had other reasons)

    If we also want Cartman to die when Kenny dies, Kenny should go away with os._exit, otherwise, only Kenny will die and Cartman will live forever.

    import threading
    import time
    import sys
    import os
    
    def kenny(num=0):
        if num > 3:
            # print("Kenny dies now...")
            # raise SystemExit #Kenny will die, but Cartman will live forever
            # sys.exit(1) #Same as above
    
            print("Kenny dies and also kills Cartman!")
            os._exit(1)
        while True:
            print("Kenny lives: {0}".format(num))
            time.sleep(1)
            num += 1
            kenny(num)
    
    def cartman():
        i = 0
        while True:
            print("Cartman lives: {0}".format(i))
            i += 1
            time.sleep(1)
    
    if __name__ == '__main__':
        daemon_kenny = threading.Thread(name='kenny', target=kenny)
        daemon_cartman = threading.Thread(name='cartman', target=cartman)
        daemon_kenny.setDaemon(True)
        daemon_cartman.setDaemon(True)
    
        daemon_kenny.start()
        daemon_cartman.start()
        daemon_kenny.join()
        daemon_cartman.join()
    

提交回复
热议问题