Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit gracefully if file doesn't exist

I have following script in Python 3.2.3:

try:     file = open('file.txt', 'r') except IOError:     print('There was an error opening the file!')     sys.exit()  #more code that is relevant only if the file exists 

How do I exit gracefully, if the file doesn't exist (or there is simply an error opening it)?

I can use exit(), but that opens a dialog panel asking if I want to kill the application.

I can use sys.exit(), but that raises a SystemExit exception which doesn't looks great in output. I get

Traceback (most recent call last):    File "file", line 19, in <module>     sys.exit() SystemExit 

I can use os.exit(), but that kills the Python on C level, without any cleanups I might be performing.

I can use a boolean variable and wrap all subsequent code in if... but that is ugly, and this is not the only check I am performing. So I would have like six nested ifs...

I just want to print the 'There was an error...' and exit. I am working in IDLE.

like image 731
Jakub Zaverka Avatar asked Nov 16 '12 21:11

Jakub Zaverka


People also ask

How do you exit gracefully in Python?

Graceful exit You can use the bash command echo $? to get the exit code of the Python interpreter.

Which commands would you use to gracefully exit in case of an error Python?

exit() is always available but exit() and quit() are only available if the site module is imported (docs). The os. _exit() function is special, it exits immediately without calling any cleanup functions (it doesn't flush buffers, for example).

How do I exit 1 in Python?

The standard convention for all C programs, including Python, is for exit(0) to indicate success, and exit(1) or any other non-zero value (in the range 1.. 255) to indicate failure. Any value outside the range 0.. 255 is treated modulo 256 (the exit status is stored in an 8-bit value).


1 Answers

This is a very graceful way to do it. The SystemExit traceback won't be printed outside of IDLE. Optionally you can use sys.exit(1) to indicate to the shell that the script terminated with an error.

Alternatively you could do this in your "main" function and use return to terminate the application:

def main():     try:         file = open('file.txt', 'r')     except IOError:         print('There was an error opening the file!')         return      # More code...  if __name__ == '__main__':     main() 

Here the main execution code of the application is encapsulated in a single function called "main", then executed only if the script is executed directly by the Python interpreter, or in other words, if the script it not being imported by another script. (The __name__ variable is set to "__main__" if the script is being executed directly from the command line. Otherwise it will be set to the name of the module.)

This has the advantage of gathering all script execution logic into a single function, making your script cleaner, and enables you to cleanly exit your script using the return statement, just like in most compiled languages.

like image 99
Hubro Avatar answered Oct 24 '22 00:10

Hubro