1

我正在寻找一种可靠的方式来写入网络驱动器。我坚持使用 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'
4

1 回答 1

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()在块中添加 a 或其他内容,except以防止代码旋转。

于 2013-01-08T17:45:25.987 回答