Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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:

defmain():
    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.

Solution 2:

Using sys.exit() is fine. If you're that concerned with output, you can always add an extra try/except block within your error handling section to catch the SystemExit and stop it from being directed to console output.

try:
    file = open('file.txt', 'r')
except IOError:
    try:
        print('There was an error opening the file!')
        sys.exit()
    except SystemExit:
        #some code here that won't impact on anything

Post a Comment for "Exit Gracefully If File Doesn't Exist"