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