1

ネットワーク ドライブに書き出す堅牢な方法を探しています。Win2003 サーバー上の共有への WinXP 書き込みに行き詰まっています。ネットワーク共有がダウンした場合に書き込みを一時停止したい...ネットワークリソースが利用可能になったら、再接続して書き込みを続行します。以下の最初のコードでは、ドライブがなくなると '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 に答える