python网络文件以健壮的方式编写

时间:2013-01-08 17:39:36

标签: python file networking

我正在寻找一种强大的方法来写出网络驱动器。我坚持使用WinXP写入Win2003服务器上的共享。如果网络共享发生故障,我想暂停写入...然后重新连接并在网络资源可用后继续写入。使用下面的初始代码,当驱动器消失时,'except'会捕获IOError,但是当驱动器再次可用时,outf操作将继续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'

1 个答案:

答案 0 :(得分:1)

我怀疑一旦打开文件由于IOError而进入错误状态,您将需要重新打开它。你可以尝试这样的事情:

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'

这会将异常处理置于外部循环中,该外部循环将在发生异常时重新打开文件(并继续从端口读取)。实际上,您可能希望在time.sleep()块中添加except或其他内容,以防止代码旋转。