Is there a method that tells my program to quit?

后端 未结 5 1026
不知归路
不知归路 2020-12-25 10:21

For the \"q\" (quit) option in my program menu, I have the following code:

elif choice == \"q\":
    print()

That worked all right until I

相关标签:
5条回答
  • 2020-12-25 10:55

    Please note that the solutions based on sys.exit() or any Exception may not work in a multi-threaded environment.

    Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted. (doc)

    This answer from Alex Martelli for more details.

    0 讨论(0)
  • 2020-12-25 11:06

    In Python 3 there is an exit() function:

    elif choice == "q":
        exit()
    
    0 讨论(0)
  • 2020-12-25 11:08

    One way is to do:

    sys.exit(0)
    

    You will have to import sys of course.

    Another way is to break out of your infinite loop. For example, you could do this:

    while True:
        choice = get_input()
        if choice == "a":
            # do something
        elif choice == "q":
            break
    

    Yet another way is to put your main loop in a function, and use return:

    def run():
        while True:
            choice = get_input()
            if choice == "a":
                # do something
            elif choice == "q":
                return
    
    if __name__ == "__main__":
        run()
    

    The only reason you need the run() function when using return is that (unlike some other languages) you can't directly return from the main part of your Python code (the part that's not inside a function).

    0 讨论(0)
  • 2020-12-25 11:10

    See sys.exit. That function will quit your program with the given exit status.

    0 讨论(0)
  • 2020-12-25 11:13

    The actual way to end a program, is to call

    raise SystemExit
    

    It's what sys.exit does, anyway.

    A plain SystemExit, or with None as a single argument, sets the process' exit code to zero. Any non-integer exception value (raise SystemExit("some message")) prints the exception value to sys.stderr and sets the exit code to 1. An integer value sets the process' exit code to the value:

    $ python -c "raise SystemExit(4)"; echo $?
    4
    
    0 讨论(0)
提交回复
热议问题