0

Python スクリプトを使用して、3 つのファイルの内容を別の 3 つのファイルに転送しています。元のファイルは、raspian を実行している RPI に接続した 3 つの温度計からのデータです。スクリプトが行うことになっているのは、ファイルの内容を取得して移動し、別のプログラム (ComScript) がそれらを読み取って解析できるようにすることだけです。

私の問題は、スクリプトが開始する前に 1 つまたは複数の温度計が切断されると、スクリプトがフリーズすることです。スクリプトの実行中に温度計を外してもフリーズしません。

ここにコードがあります

import time
a = 1
while a == 1:
 try:
    tfile = open("/sys/bus/w1/devices/28-000004d2ca5e/w1_slave")
    text = tfile.read()
    tfile.close()
    temperature = text



    tfile2 = open("/sys/bus/w1/devices/28-000004d2fb20/w1_slave")
    text2 = tfile2.read()
    tfile2.close()
    temperature2 = text2


    tfile3 = open("/sys/bus/w1/devices/28-000004d30568/w1_slave")
    text3 = tfile3.read()
    tfile3.close()
    temperature3 = text3



    textfile = open("/home/pi/ComScriptPi/profiles/Temperature_parse/w1_slave1", "w ")
    textfile2 = open("/home/pi/ComScriptPi/profiles/Temperature_parse/w1_slave2", "w ")
    textfile3 = open("/home/pi/ComScriptPi/profiles/Temperature_parse/w1_slave3", "w ")
    temperature = str(temperature)
    temperature2 = str(temperature2)
    temperature3 = str(temperature3)
    textfile.write(temperature)
    textfile2.write(temperature2)
    textfile3.write(temperature3)
    textfile.close()
    textfile2.close()
    textfile3.close()
    print temperature
    print temperature2
    print temperature3
    time.sleep(3)

 except:
  pass

例外パスを追加したのは、値が悪くても実行し続ける必要があるためです。温度計の1つが切断されると、Pythonが読み取ろうとしているファイルは空白ですが、まだそこにあります。

4

2 に答える 2

4

毛布を除いて取り外します。

スクリプトはフリーズしていませんが、発生したエラーは無限ループで無視されています。ブランケットを使用するため、キーボード割り込み例外を含むすべてのexcept:例外をキャッチします。KeyboardInterrupt

少なくとも例外をログExceptionに記録し、キャッチのみ:

except Exception:
    import logging
    logging.exception('Oops: error occurred')

KeyboardInterruptBaseException、notのサブクラスであり、Exceptionこの except ハンドラによってキャッチされることはありません。

shutilファイルをコピーするためのモジュールを見てください。あまりにも多くの作業を行っています。

import time
import shutil
import os.path

paths = ('28-000004d2ca5e', '28-000004d2fb20', '28-000004d30568')

while True:
    for i, name in enumerate(paths, 1):
        src = os.path.join('/sys/bus/w1/devices', name, 'w1_slave')
        dst = '/home/pi/ComScriptPi/profiles/Temperature_parse/w1_slave{}'.format(i)
        try:
            shutil.copyfile(src, dst)
        except EnvironmentError:
            import logging
            logging.exception('Oops: error occurred')

    time.sleep(3)

ファイルの処理は、発生させるか、そのサブクラスのみにする必要があります。ここですべてをキャッチする必要はありませEnvironmentError

于 2013-07-29T21:22:41.740 に答える
0

デバイスが存在しない場合、デバイス ドライバーは開かないため、プラグを抜いたデバイスを開くと、ブロックされる可能性が高くなります。

Unix システム コール「open」に相当する os.open を使用し、フラグ O_NONBLOCK を指定してリターン コードを確認する必要があります。その後、os.fdopen を使用して、os.open の戻り値を通常の Python ファイル オブジェクトに変換できます。

于 2013-07-29T21:32:07.733 に答える