Home python End Python Program

End Python Program




How to do early program termination in Python? I found several examples in the tutorial:

exit (0)
os.abort ()

However, there was no explanation of which method is better. Which method is the most “trouble-free”?

And also: is there a concept of Autocloseable objects in Python? If I terminate the program earlier, do I need to close files, etc.?

Answer 1, authority 100%

Short answer:
Better to use sys.exit ()

Process termination in Python is implemented by throwing an exception SystemExit , so you can simply throw an exception like this and the program will exit:

raise SystemExit
# or even pass a number - the program termination error code
raise SystemExit (1)

The exit function and the analogous quit are designed for ease of use in interactive mode and are not recommended for use inside scripts:

They are useful for the interactive interpreter shell and should not be used in programs.

In fact, they also just raise an exception, and if you try to call without parentheses, they will write a hint about the correct way to exit the interpreter:

& gt; & gt; & gt; quit
Use quit () or Ctrl-D (i.e. EOF) to exit
& gt; & gt; & gt; exit
Use exit () or Ctrl-D (i.e. EOF) to exit

It is worth using sys.exit because this function is in the standard module and will always be available there. It is also a fairly explicit way of expressing your desire to terminate the program.

There is also an additional method to terminate the program immediately: os. _exit . It has a rather specific area of ​​application, and there is also a note there:

The standard way to exit is sys.exit (n)

Ie it confirms that the standard way to terminate a program is by calling sys.exit .

Function os.abort you mentioned uses a process signaling mechanism. Specifically, when this function is called, the SIGABRT signal will be transmitted, which will result in to terminate the program and create process memory dump . Such a termination is considered by the operating system to be abnormal, so you should not use it to terminate the application without crashing.

On the second part of the question. Python has an advanced system of context managers: classes that can work with the with operator. The most common use of this mechanism is probably with files.

with open ('filename') as my_file:
  print (my_file.read ())

This code will open the file, print its contents to the screen, and close the file automatically, even if an exception is thrown while printing it.

For classes that are not adapted to work with with , there is a function closing in contextlib . From the documentation:

Code like this:

with closing (& lt; module & gt; .open (& lt; arguments & gt;)) as f:
  & lt; block & gt;

is equivalent to this:

f = & lt; module & gt; .open (& lt; arguments & gt;)
  & lt; block & gt;
  f.close ()

Here is a small example of how this function works:

import contextlib
class Closeable:
  def close (self):
    print ('closed')
with contextlib.closing (Closeable ()):
# prints closed

Now a little digression on why you should use the with construct.

The program is known to terminate on any unhandled exception, not just SystemExit . Thus, if your code uses some resources that need to be properly closed before exiting, you need to wrap your work with them in try ... finally ... blocks.

However, when using the with construction, this wrapping occurs automatically, and all resources are closed correctly.

Since the exit from the program is just a thrown exception, then even if the sys.exit function is used, the resources opened in the with statement will be closed correctly:

with contextlib.closing (Closeable ()):
  sys.exit ()
# prints closed

You can also write your own classes that provide resources or classes that wrap others that you need to be able to close automatically. To do this, use the __enter__ and __exit__ methods.


  1. Similar question from English StackOverflow
  2. Functions added by the site
  3. Documentation with
  4. Function documentation closing
  5. Exception Documentation SystemExit
  6. Function documentation os._exit
  7. Function documentation sys.exit
  8. Function documentation os.abort
  9. Description of the system signal SIGABRT

Answer 2

# python 2
def sigint_handler (signum, frame):
  print (os.getpid ())
  print 'CTRL + C / Z Pressed, app is now killed!'
  os.kill (os.getpid (), 9)
signal.signal (signal.SIGINT, sigint_handler)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions