Zoli
Zoli

Reputation: 1091

Python while enters an infinite loop when reading lines

I want to read the DS18B20 sensor data with the code below:

filepath = "/sys/bus/w1/devices/w1_bus_master1/w1_master_slaves"

with open(filepath) as fp:
    sensor=fp.readline()
    while sensor:
        print("Sensor: {}".format(sensor.strip()))
        with open("/sys/bus/w1/devices/" + sensor.strip() + "/w1_slave") as fp1:
            sensor_data = fp1.read()
            print(sensor_data.strip())
    sensor=fp.readline()

The problem is that the while loop never steps to the next line, keeps looping at the first one.

What am I missing here?

PS. I'm totaly new with python, this is my very first python code

Upvotes: 0

Views: 356

Answers (2)

Austin
Austin

Reputation: 26047

As discussed in comments, the problem is sensor is never getting updated within loop. It keeps looping through first read value. This can be corrected by indenting the last line of your code.

I suggest using a for loop. When we simply iterate over file handler, we iterate over lines in file.

with open(filepath) as fp:
    for sensor in fp:
        print("Sensor: {}".format(sensor.strip()))
        with open("/sys/bus/w1/devices/" + sensor.strip() + "/w1_slave") as fp1:
            sensor_data = fp1.read()
            print(sensor_data.strip())

Upvotes: 1

Mahrez BenHamad
Mahrez BenHamad

Reputation: 2096

That because sensor isn't changed within the loop, try this

filepath = "/sys/bus/w1/devices/w1_bus_master1/w1_master_slaves"

with open(filepath) as fp:
    sensor = fp.readline()
        while (sensor):
            print("Sensor: {}".format(sensor.strip()))
            with open("/sys/bus/w1/devices/" + sensor.strip() + "/w1_slave") as fp1:
                sensor_data = fp1.read()
                print(sensor_data.strip())
            sensor=fp.readline()

Upvotes: 1

Related Questions