How do I exit in Python? How do I terminate a program in Python? a blog about exiting from a python script.

I am writing a program and I want it to exit when the user hits return, but when I press return, the program doesn’t exit. How do I exit in Python? How do I terminate a program in Python?

The answer is that you need to write an exit function like this:

def exit():


if __name__ == ‘__main__’:


And then call it whenever you want to exit. (If you’re on Windows, ignore that 0 thing and just use sys.exit().)

The best way to exit or terminate a Python script is to use the exit() function.

The following code will exit when the user enters a “q”.

There are two ways of terminating a python script. The first is to use the exit() method, and the second is to simply return from your function. In either case, you can pass it a message that will be printed to stderr. The following are equivalent:

sys.exit(“It’s dead, Jim”)

raise SystemExit(“It’s dead, Jim”)

print “It’s dead, Jim”

raise SystemError(“It’s dead, Jim”)

Sometimes you want to exit from a Python program. For example, if the program has an infinite loop that cannot be broken by pressing Ctl-C, then you must type ‘kill %1’ where %1 is the job number of the Python program. This is shown in the following example:

$ python


[1]+ Stopped python

$ kill %1

You can also use the exit function from the sys module. The following shows how this works:

$ python


$ cat

import sys; sys.exit(); print “never gets here”

The sys.exit() function allows the developer to exit from Python.

The function can take an optional argument to pass back to the calling scope. The default value is zero, which means that no error has occurred. Otherwise, the number is the OS error code, and the message is the OS error message as returned by os.strerror().

For example:

import sys

sys.exit(“It’s over”)

The simplest way to exit a function in Python is to use the ‘return’ statement.

def func():


This also works in methods:

def method(self):


If you want to send a value back, just put it after the ‘return’ statement. For example:

def func():

return 1234

def method(self):

return “Hello”

Another way to exit a function (or a method) is to raise an exception. For example, if you want to exit from a function if a condition is not met:

def func():

if True:

Python 2.5 introduced the with statement (context management protocol). This allows you to do:

with open(“myfile.txt”) as f:

for line in f:

print line,

Leave a Reply

Your email address will not be published.