[python] Is there a method that tells my program to quit?

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

elif choice == "q":
    print()

That worked all right until I put it in an infinite loop, which kept printing blank lines. Is there a method that can quit the program? Else, can you think of another solution?

This question is related to python exit quit

The answer is


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

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


In Python 3 there is an exit() function:

elif choice == "q":
    exit()

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.