Python,如何在一个脚本中创建2个循环以便它可以工作

问题描述 投票:0回答:2

我正在尝试在同一个程序中创建两个循环,但它只停留在第一个循环上而不会进入第二个循环...我正在尝试让程序在文本文件中写入温度而不会覆盖本身...这是我的计划:

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(18,GPIO.OUT)

os.system('modprobe w1-gpio')                              
os.system('modprobe w1-therm')                                                 
base_dir = '/sys/bus/w1/devices/'                          
device_folder = glob.glob(base_dir + '28*')[0]             
device_file = device_folder + '/w1_slave'                 
def read_temp_raw():
   f = open(device_file, 'r')
   lines = f.readlines()                                   
   f.close()
   return lines

def read_temp():
   lines = read_temp_raw()
   while lines[0].strip()[-3:] != 'YES':                   
      time.sleep(0.2)
      lines = read_temp_raw()
   equals_pos = lines[1].find('t=')                        
   if equals_pos != -1:
      temp_string = lines[1][equals_pos+2:]
      temp_c = float(temp_string) / 1000.0                 
      return temp_c

while True:
   print(read_temp())                                      
   time.sleep(0.5)
   if read_temp() > 25:
      GPIO.output(18, True)
   else:
      GPIO.output(18, False)

while True:
   f = open("temperatureFile.txt", "w")
   f.write(read_temp())
   f.close
python loops while-loop
2个回答
0
投票

你的第一个循环永远不会退出。如果你想将温度附加到文件,你应该在第一个循环中添加该调用,并完全摆脱第二个循环。

while True:
  time.sleep(0.5)
  temp = read_temp()
  with open("temperatureFile.txt", "a") as f:
    f.write(temp)
  if temp > 25:
     GPIO.output(18, True)
  else:
     GPIO.output(18, False)

请注意,您的原始代码将不断重写温度文件,而不是附加到它,因为您在写入模式下打开它。

更好的想法可能是将多个温度累积到列表中,然后在超过0.5秒的时间之后,批量写入这些值。我将把它作为练习留给读者。


0
投票

您的程序永远不会退出第一个while循环,因为代码中的任何地方都没有break语句。我假设你想做的事情是这样的

outfile = open("temperatureFile.txt", "a")
while True:
   temp=read_temp()
   print(temp)                                      
   time.sleep(0.5)
   if temp > 25:
      GPIO.output(18, True)
   else:
      GPIO.output(18, False)
   outfile.write(temp)
outfile.close()
© www.soinside.com 2019 - 2024. All rights reserved.