open() and EOFError

Roy Smith roy at panix.com
Mon Jul 7 14:46:33 CEST 2014


In article <mailman.11587.1404735570.18130.python-list at python.org>,
 Chris Angelico <rosuav at gmail.com> wrote:

> On Mon, Jul 7, 2014 at 6:00 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> > How do people feel about code like this?
> >
> > try:
> >     name = input("Enter file name, or Ctrl-D to exit")
> >     # On Windows, use Ctrl-Z [enter] instead.
> >     fp = open(name)
> > except EOFError:
> >     sys.exit()
> > except IOError:
> >     handle_bad_file(name)
> > else:
> >     handle_good_file(fp)
> 
> Just thought of something. It's possible for input() to raise IOError,
> if I'm not mistaken; consider redirection, for instance. In that case,
> you would definitely want to split the try blocks, so you don't try to
> "handle_bad_file" when no name was entered. (As Dave says, name hasn't
> been assigned at that point, although I'd be less concerned about a
> possible cascaded NameError than about a possible handle_bad_file()
> with the previous name, if this is in a loop.)
> 
> ChrisA

My latest and greatest IOError horror story....

A guy here at work was running a Python job that was taking many days to 
complete.  He was running it on one of our production machines where we 
continually push out new releases, and clean up old ones after a few 
days.  Well, his job took longer than a few days and the directory 
containing the virtualenv he was running out of was deleted.  This 
didn't bother anything until several days later, when something deep 
inside some library function needed to open a (now missing) data file.  
Which of course, generated an IOError, which was caught in some 
unexpected place, causing all sorts of confusion trying to figure out 
WTF happened.

We've since modified our cleanup script to run lsof and skip purging any 
releases which are still in use :-)



More information about the Python-list mailing list