Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a method that tells my program to quit?

Tags:

python

exit

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?

like image 649
Kudu Avatar asked May 12 '10 23:05

Kudu


People also ask

What does quit () do in Python?

Python's in-built quit() function exits a Python program by closing the Python file. Since the quit() function requires us to load the site module, it is generally not used in production code.

Which command helps in quitting the utility?

In computing, exit is a command used in many operating system command-line shells and scripting languages. The command causes the shell or program to terminate.


2 Answers

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).

like image 150
Greg Hewgill Avatar answered Sep 17 '22 02:09

Greg Hewgill


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 
like image 24
tzot Avatar answered Sep 19 '22 02:09

tzot