python network file writing in a robust manner
Question: I am looking for a robust way to write out to a network drive. I am stuck with
WinXP writing to a share on a Win2003 server. I want to pause writing if the
network share goes down... then reconnect and continue writing once the
network resource is available. With my initial code below, what happens is the
'except' catches the IOError when the drive goes away, but then when the drive
becomes available again, the outf operations continue to IOError.

    
    
    import serial
    
    with serial.Serial('COM8',9600,timeout=5) as port, open('m:\\file.txt','ab') as outf:
        while True:
            x = port.readline() # read one line from serial port
            if x:   # if the there was some data
                print x[0:-1]     # display the line without extra CR
                try:
                    outf.write(x) # write the line to the output file
                    outf.flush() # actually write the file
                except IOError: # catch an io error
                    print 'there was an io error'
    


Answer: I suspect that once an open file goes into an error state because of the
IOError that you will need to reopen it. You could try something like this:

    
    
    with serial.Serial('COM8',9600,timeout=5) as port:
        while True:
            try:
                with open('m:\\file.txt','ab') as outf:
                    while True:
                        x = port.readline() # read one line from serial port
                        if x:   # if the there was some data
                            print x[0:-1]     # display the line without extra CR
                            try:
                                outf.write(x) # write the line to the output file
                                outf.flush() # actually write the file
                    break
            except IOError:
                print 'there was an io error'
    

This puts the exception handling inside an outer loop that will reopen the
file (and continue reading from the port) in the event of an exception. In
practice you would probably want to add a `time.sleep()` or something to the
`except` block in order to prevent the code from spinning.

