Python with exception exit

The Many Ways to Exit in Python

It’s fundamentally useful to exit your program when it’s done. Here are five(!) ways to do so in Python.

1. raise SystemExit()

We can exit from Python code by raising a SystemExit exception:

The top level interpreter catches this special exception class and triggers its exit routine. This includes such steps as running all atexit functions, deleting all objects, and finally calling the OS exit function.

SystemExit optionally takes an integer for the exit code, where 0 represents success and any other value represents failure. We can use this to signal calling programs that an error occurred:

(When Python crashes with an exception, it uses an exit code of 1.)

If you’re looking for a quick answer, you can stop reading here. Use raise SystemExit(&LTcode>) as the obviousest way to exit from Python code and carry on with your life.

More obscurely, we can pass SystemExit any object, in which case Python will print the str() of that object to stderr and return an exit code of 1:

This can be handy, but I’d argue being explicit is clearer:

We can also call sys.exit() to exit Python, optionally with an exit code:

Underneath this only does raise SystemExit(<arg>) (in C).

Whilst sys.exit() is a little less typing than raise SystemExit() , it does require the import, which is a bit inconvenient. Also it hides the detail that an exception is raised.

Читайте также:  Slide right animation css

3. exit() and quit()

exit() and quit() are “extra builtins” added by Python’s site module. Both essentially call raise SystemExit() , optionally with an exit code, like:

This looks super convenient! We don’t need to import anything, and the names are very short.

Unfortunately, the site module is optional. We can be skip loading it by running Python with the -S flag. In which case our call to quit() or exit() can still exit, but with a NameError exception:

 python -S -c ", line 1, in <module> 

Because exit() and quit() are optional, I’d recommend avoiding using them in your programs. But they’re fine to use at the REPL, which is why they exist. They even print usage information when written without brackets, to help new users trying to exit the REPL:

4. Ctrl-D (from the REPL)

Ctrl-D is the universal keyboard shortcut for exit. It sends EOF (End of File) to the current program, telling it the user is done sending input and it should exit.

Ctrl-D works with every command line program, including python . So it’s best to learn this shortcut, rather than use the Python-specific exit() . Then you can exit bash , zsh , ipython , sqlite , and any other command line program, without giving it a second thought.

5. os._exit()

The os._exit(n) function exits Python immediately with the given exit code n . It does so by calling the underlying OS exit function directly.

Unlike raising SystemExit , using os._exit() prevents Python from running its normal exit process. This is very destructive and usually undesirable, hence the “private/danger” underscore prefx.

The only reason I’ve found for calling os._exit() is when debugging in cases where raising SystemExit doesn’t work. For example, in a thread, raising SystemExit does not exit the progarm — it only stops the thread. Directly calling os._exit() can stop the entire program, which can be combined with a few well-placed debug prints to inspect state.

So, it’s worth knowing that os._exit() exists, although you should avoid it in day-to-day life.

✨Bonus✨ 6. Directly calling the OS exit function

os._exit() is a thin wrapper around our OS’ underlying exit function. We can call this function directly through Python’s ctypes module. This doesn’t confer any advantage — in fact it’s worse, because our code won’t work on all OSs. But it’s cool to know about.

On Linux/macOS/other Unixes, the exit function is available in the C standard library as exit() . We see its details by running man 3 exit — the Linux man page is online here. We can call it with ctypes like so:

Fin

Thanks to Anthony Sottile for the tip to use raise SystemExit(. ) in this video.

I hope you have found the exit you’re looking for,

Make your development more pleasant with Boost Your Django DX.

One summary email a week, no spam, I pinky promise.

Tags: python © 2021 All rights reserved. Code samples are public domain unless otherwise noted.

Источник

Why is Python sys.exit better than other exit functions?

Python sys.exit

There are many times when we want to exit from the programs after a particular code gets executed, without even reaching the end of the program. There are many ways in python to exit from the program. Despite having so many ways, python programmers/ developers generally prefer using sys.exit in the real world.

Sys.exit is generally used in programs to raise the SystemExit Exception. With this exception, the program is closed with a proper code passed into the argument.

When sys.exit is called, it raises a SystemExit Exception. In this article, we will learn how to use sys.exit, what arguments we can pass, when it should be used, and many more important things.

Syntax of sys.exit()

Whenever we want to exit from the interpreter explicitly, it means whenever we want to exit from the program before the interpreter reaches the end of the program, we can use sys.exit.

Before using sys.exit, we first need to import the ‘sys’ module into our systems. To import use – ‘import sys.’

sys.exit([status]) 

Parameter of sys.exit in python

sys.exit accepts only one argument – status, and that too is optional. If we want to print something while exiting like why we want to exit or something, we can pass that in the argument. It can be either an integer, float, boolean, or string.

Return Type

sys.exit returns SystemExit Exception along with the passed argument.

NoteIf we are passing integer 0 as the argument, it means the termination is successful, and if we pass any other argument, it means that the termination is not successful.

How to use sys.exit in Different IDE’S

The output is different in different IDE’s. Except for string argument, the output for every other type of argument won’t work for Pycharm.

But first, let us understand to use sys.exit with argument.

Without Argument

# Importing the sys module which contains exit function import sys # Runn the loop 10 times for i in range(10): # Whenever we encounter '7' exit from the loop if i==7: sys.exit() print(i,end=" ")

python sys.exit

The output is different for different Integrated Development Environment(IDE).

0 1 2 3 4 5 6 An exception has occurred, use %tb to see the full traceback. SystemExit

Now let us learn how to use the arguments.

Using the string type argument

The output for string type argument remains mostly the same for all IDE’s.

Iterating through all the ages for age in ages: if age 
SystemExit: The minimum age for voting is 18

You can see that whatever we passed in the argument got printed after the SystemExit Exception.

Using the integer type argument

We can pass any integer we want. It can be status code too.

attendees=["manoj","sara","sanjay","ashwini"] if "ashwini" in attendees: sys.exit(0)
SystemExit: 0

In IDLE or Pycharm, the integer argument would not get printed.

import sys def call_exit(): for i in range(1,9): if i==7: print(sys.exit(1)) print(i) call_exit()

Using sys.exit along with Try block in python

We know that, if we are using try-except finally blocks, whatever we print in finally block gets printed for sure. Let us see whether it is true while using sys.exit or not.

for i in range(10): try: # if i==8, exit if i==8: sys.exit("We have encountered 8") except Exception as e: print("The value of was never 8") # Whatever happens, this will execute finally: print(i)
0 1 2 3 4 5 6 7 8 An exception has occurred, use %tb to see the full traceback. SystemExit: We have encountered 8

Raising SystemExit Exception without using python sys.exit

Another way of exiting the program by raising the SystemExit exception is by using the raise keyword.

for i in range(10): if i==5: raise SystemExit("Encountered 5") print(i)
0 1 2 3 4 An exception has occurred, use %tb to see the full traceback. SystemExit: Encountered 5

It totally depends upon you, which way you want to exit the program. Everything else is the same about the two methods except that, for sys.exit, you have to import sys.

Comparing the sys.exit function with other functions in python

Two more ways are exit() and quit(). But they should not be used in the production environment because they use the site module which is not installed everywhere.

Another Common way for exiting is by using the os._exit(). So let us see what is the difference between the two.

os._exit() method is generally used to exit the process with a specified status without calling any cleanup handlers, flushing stdio buffers, etc. Also, it does not return anything.

Note: This method is normally used in the child process after the os.fork system call. Therefore, os._exit should only be used in some special scenarios.

So, the best way of exiting the program is sys.exit().

Must Read:

Conclusion

Whenever we want to exit from the program without reaching the end of the program, we can use the different exit programs available in python. The most standard and commonly used one is the sys.exit() function. We can also usu raise SystemExit to exit out of the program.

If you still have any problem or request, do let us know in the comment section below.

Happy Coding!

Источник

Оцените статью