Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore non-float value

Tags:

python

I have a USB temperature logger that uploads to Cosm every 30 seconds. The issue I'm having is that every 5 minutes, when I run the command it reports a text error instead of a number.

So I'm trying to figure out a way to get it to either loop until it receives a number or just ignore the text and resume the script (it quits with an error otherwise).

My very inelegant solution is to do this:

  # 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

The current body of code is:

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
like image 361
user1813343 Avatar asked Dec 09 '25 13:12

user1813343


2 Answers

In Python, it is often easier to ask for forgiveness than permission (EAFP). When you encounter a ValueError, continue to the next iteration:

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

Or more compactly (consolidating most of your function):

try:
    temp_C = float(sensor_reading.split(' ')[4].rstrip('C'))
except (ValueError, IndexError):
    continue
like image 175
Steven Rumbalski Avatar answered Dec 13 '25 10:12

Steven Rumbalski


Just catch the ValueError exception that occurs when the conversion fails:

try:
    temp_C = float(temp)
except ValueError:
    temp_C = 0.0
like image 41
Roland Smith Avatar answered Dec 13 '25 08:12

Roland Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!