0

I have a script to read messages on a mail server and save them in specific folders based on the content of the message bodies. Intermittently, usually about once or twice a day, it fails while executing this part of the code:

if not os.path.isfile(att_path) :
    # finally write the stuff
    fp = open(att_path, 'wb')
    fp.write(part.get_payload(decode=True))
    fp.close()
    ext = att_path.split(".")[-1]
    print "att_path",att_path
    f = open(att_path.replace("."+ext,".txt"),'wb')
    f.write(headers)
    f.write("\n\n\n")
    f.write(body)
    f.close()
    filelist.append(vdir+"/"+filename)
    messageReceived = True
else:
    noErrors = False
    errFiles.append(vdir+"/"+filename)

It saves the actual attachment in the expected directory, but not the subsequent text file with the headers and body information. Because an exception is thrown ("[Errno 9] Bad file descriptor"), the email is not marked for deletion and stays on the server until the saved attachment is either deleted or moved, at which point both files will be saved without any errors.

I'm stumped at what could be causing it, since it processes several hundred emails every day without any problems, except for this intermittent issue.

CCKx
  • 1,303
  • 10
  • 22
  • Do you have complete exception message or at least do you know which line causes it? – myaut Mar 05 '15 at 17:27
  • When I save the caught exception in a log file it says "[Error 9] Bad file descriptor". I just updated the except clause code to see if it will give me a line number the next time it happens, but the fact that one file is being created but the other isn't suggests to me it's happening somewhere between the fp.close() and f = open(...) lines. – CCKx Mar 05 '15 at 17:54
  • Use traceback module to get entire stack of error. – myaut Mar 05 '15 at 18:17
  • Didn't have much luck with the traceback module, but I tried getting the line number using sys.exc_info()[-1].tb_lineno and it's been giving me various lines which only have print statements in them. FWIW, I'm saving it as a .pyw file and using pythonw.exe to run it. – CCKx Mar 30 '15 at 17:20

1 Answers1

1

I encountered intermittent bad descriptor error in a script run with pywin32 (running python as Windows service). A near identical script (sans the pywin32 boilerplate) runs without issues in the cmd. The module traceback also points to various print statements, thus I commented out all the print statements, and it works!

Please correct me if I'm wrong, I suspect this is something to do with the lack of stdout. I used to use print statements to debug but switched to the logging module after this.

saubao
  • 11
  • 1