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.
SystemExit
exception (unless you're catching it someplace else which you probably shouldn't be) ... I'm not sure what you're talking about it looking good in the output. – Secundreturn
from the current function. – Lenwoodsys.exit()
and catch theSystemExit
at the top level. (I don't see SystemExit myself; what environment are you running in?) – Heeheebiejeebiessys.exit(0)
? – Systolesys.exit
won't displaySystemExit
. IDLE does so that you know if the program finished or exited abnormally. – Balalaika