Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you exit a python program without the error statement?

Tags:

python

exit

How do you quit or halt a python program without the error messages showing?

I have tried quit(), exit(), systemexit(), raise SystemExit, and others but they all seem to raise an error message saying the program has been halted. How do I get rid of this?

like image 532
Chris Avatar asked Sep 17 '26 17:09

Chris


2 Answers

You are trying too hard. Write your program using the regular boilerplate:

def main():
    # your real code goes here
    return

if __name__ == "__main__":
    main()

and just return from function main. That will get you back to the if-clause, and execution will fall out the bottom of the program.

You can have as many return statements in main() as you like.

like image 169
BoarGules Avatar answered Sep 21 '26 01:09

BoarGules


You would need to handle the exit in your python program. For example:

def main():
    x = raw_input("Enter a value: ")
    if x == "a value":
        print("its alright")
    else:
        print("exit")
        exit(0)

Note: This works in python 2 because raw_input is included by default there but the concept is the same for both versions.

Output:

Enter a value: a
exit

Just out of curiousity: Why do you want to prevent the message? I prefer to see that my program has been closed because the user forced a system exit.

like image 40
ItsMeTheBee Avatar answered Sep 21 '26 00:09

ItsMeTheBee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!