简体   繁体   English

Python在读取行时进入无限循环

[英]Python while enters an infinite loop when reading lines

I want to read the DS18B20 sensor data with the code below: 我想使用以下代码读取DS18B20传感器数据:

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. 问题是,while循环永远不会移至下一行,而在第一行继续循环。

What am I missing here? 我在这里想念什么?

PS. PS。 I'm totaly new with python, this is my very first python code 我对python完全陌生,这是我的第一个python代码

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()

As discussed in comments, the problem is sensor is never getting updated within loop. 正如评论中所讨论的那样,问题在于sensor永远不会在循环内得到更新。 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. 我建议使用for循环。 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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM