[Tutor] Which exceptions should I be catching?

Wesley Brooks wesbrooks at gmail.com
Mon Oct 20 22:30:06 CEST 2008


Dear Users,

I've got a program that passes messages to another program in the form of
empty files, whereby the title of the file is the command. I've been
speaking to this board about this before about doing this in the quickest
possible way. Even with the code layed out as follows the code still breaks
once in a blue moon. Unfortunately due to the nature of the program the
error has normally happened hours ago and the error message has disappeared
from the buffer of the command prompt.

This is the function:

def CommandFileWriter(self, command):
  name1 = os.path.join(self.commandsdir, command + '.temp')
  name2 = os.path.join(self.commandsdir, command)
  comfile = open(name1, 'w')
  comfile.close()
  if not os.path.exists(name2):
    os.rename(name1, name2)
  else:
    os.remove(name1)

This was the best way I could come up with doing the function. So the file
is written to the correct directory with a wrong name (so the other program
will ignore it) then it's name is changed to the correct name with
os.rename. Unfortunately I think in freak occations the other program can
read and delete the file (running on a multicore processor system) during
the rename operation. Can you suggest which errors I should be trying to
catch? I guess the last four lines could also be caught by try except as
well. Although the program is currently running on windows XP I would like
any soloution to be cross platform for testing and future-proofing reasons.

Thanks in advance of any suggestions,

Wesley Brooks.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20081020/9acbc30c/attachment-0001.htm>


More information about the Tutor mailing list