2

30 秒ごとに Cosm にアップロードする USB 温度ロガーがあります。私が抱えている問題は、5 分ごとにコマンドを実行すると、数値ではなくテキスト エラーが報告されることです。

そのため、数値を受け取るまでループするか、テキストを無視してスクリプトを再開する方法を見つけようとしています(それ以外の場合はエラーで終了します)。

私の非常に洗練されていない解決策は、これを行うことです:

  # convert regular error message to number
    if temp_C == "temporarily": # "temporarily" is used as it happens to be the 4th word in the error message
            temp_C = 0.0

現在のコード本体は次のとおりです。

while True:
    # read data from temper usb sensor
    sensor_reading=commands.getoutput('pcsensor')

    #extract single temperature reading from the sensor

    data=sensor_reading.split(' ') #Split the string and define temperature
    temp_only=str(data[4]) #knocks out celcius reading from line
    temp=temp_only.rstrip('C') #Removes the character "C" from the string to allow for plotting

    # calibrate temperature reading
    temp_C = temp

    # convert regular error message to number
    if temp_C == "temporarily":
            temp_C = 0.0

    # convert value to float
    temp_C = float(temp_C)

    # check to see if non-float
    check = isinstance(temp_C, float)

    #write out 0.0 as a null value if non-float
    if check == True:
            temp_C = temp_C
    else:
            temp_C = 0.0
4

2 に答える 2

7

Python では、多くの場合、許可 ( EAFP )よりも許しを求める方が簡単です。に遭遇するValueErrorcontinue、次の反復へ:

try:
    temp_C = float(temp_C)
except ValueError:
    continue # skips to next iteration

または、よりコンパクトに (ほとんどの機能を統合します):

try:
    temp_C = float(sensor_reading.split(' ')[4].rstrip('C'))
except (ValueError, IndexError):
    continue
于 2012-11-12T20:01:10.007 に答える
4

ValueError変換が失敗したときに発生する例外をキャッチするだけです。

try:
    temp_C = float(temp)
except ValueError:
    temp_C = 0.0
于 2012-11-12T20:01:29.687 に答える