Python网络文件写入的健壮方式



我正在寻找一种健壮的方式来写入网络驱动器。我一直在用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'

我怀疑一旦打开的文件由于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'

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

相关内容

  • 没有找到相关文章

最新更新