How to terminate a Python script

前端 未结 10 1056
予麋鹿
予麋鹿 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:07

    A simple way to terminate a Python script early is to use the built-in quit() function. There is no need to import any library, and it is efficient and simple.

    Example:

    #do stuff
    if this == that:
      quit()
    
    0 讨论(0)
  • 2020-11-22 05:09

    You can also use simply exit().

    Keep in mind that sys.exit(), exit(), quit(), and os._exit(0) kill the Python interpreter. Therefore, if it appears in a script called from another script by execfile(), it stops execution of both scripts.

    See "Stop execution of a script called with execfile" to avoid this.

    0 讨论(0)
  • 2020-11-22 05:11

    Another way is:

    raise SystemExit
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
提交回复
热议问题