Chris
Chris

Reputation: 363

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

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?

Upvotes: 2

Views: 7331

Answers (4)

Yashi Aggarwal
Yashi Aggarwal

Reputation: 405

you can try the following code to terminate the program.

import sys
sys.exit()

Upvotes: -1

BoarGules
BoarGules

Reputation: 16952

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.

Upvotes: 8

Joseph Holland
Joseph Holland

Reputation: 144

you can structure your program within a function then return when you wish to halt/end the program

ie

def foo():
    # your program here
    if we_want_to_halt:
        return

if __name__ == "__main__":
    foo()

Upvotes: 1

ItsMeTheBee
ItsMeTheBee

Reputation: 373

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.

Upvotes: 2

Related Questions