dragon
dragon

Reputation: 9

Exit function in python doesn't work

I'm new to Python and I'm trying to use the exit function from sys, but somehow it's not working on my computer. This is my code:

from sys import exit

userResponse = input ("n or y?")
if not (userResponse =="n" or userResponse =="y") :
exit ("ERROR")

Upvotes: 0

Views: 7984

Answers (4)

Ivaylo Novakov
Ivaylo Novakov

Reputation: 905

I was running into issues while trying to exit a script without raising an exception. What worked best for my case was os._exit(exitcode).

Upvotes: 2

mrCarnivore
mrCarnivore

Reputation: 5088

You have to indent correctly:

if not (userResponse =="n" or userResponse =="y") :
    exit('Error')

You could also raise an exception to get an even more descriptive error message:

userResponse = input ("n or y?")
if not (userResponse =="n" or userResponse =="y") :
    raise ValueError('Does not work')

Upvotes: 1

en_Knight
en_Knight

Reputation: 5381

Exit raises a SystemExit exception; that's how it terminates the program. That your environment displays that exception after terminating is not a bug, it's just showing you the cause. I agree with you (as does, e.g., this PEP), that the default behaviour should be to not print out a traceback message for this exception, and for KeyboardException

But in the end, the execution halted, as it was designed to do.

See the docs for details: https://docs.python.org/2/library/sys.html#sys.exit


A few answers here initially indicated that you cannot pass a string to exit. That is false: from the docs (emphasis mine)

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0–127, and produce undefined results otherwise.... If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.


The builtin exit function does the same thing. In general, it is not great to shadow the builtin function by importing from a module, though in this case it doesn't matter. Recommended style would be

import sys
sys.exit("My exception")

If this seems unintuitive to you, you can bypass the exception handling by using os._exit. Don't do these without cause

Upvotes: 1

cer
cer

Reputation: 2005

Following up on @MrCarnivore...

from sys import exit

userResponse = raw_input("n or y?")
if not (userResponse =="n" or userResponse =="y"):
     print('Error Message Here')
     exit(1)

Upvotes: 0

Related Questions