我在Python中有一个if
/ elif
语句,但我希望接下来执行这两个命令。我想每秒显示AD0
和AD1
,但代码只显示AD1
(未在elif
上输入。)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import serial
from time import sleep
import datetime
now = datetime.datetime.now()
port = '/dev/ttyUSB0'
ser = serial.Serial(port, 9600, timeout=0)
while True:
arquivo = open('temperatura.txt','r')
conteudo = arquivo.readlines()
now = datetime.datetime.now()
data = ser.read(9999)
if len(data) > 0:
if 'AD0'in data:
temp = data[4:7]
#print 'Got:', data
#string = str('A temperatura é',temp,'ºC')
conteudo.append(now.strftime("%Y-%m-%d %H:%M"))
conteudo.append(' ')
conteudo.append('[AD0]A temperatura é')
conteudo.append(temp)
conteudo.append('ºC')
print '[AD0]A temperatura é',temp,'ºC'
#print string
conteudo.append('\n')
arquivo = openarquivo = open('temperatura.txt','w')
arquivo.writelines(conteudo)
continue
elif 'AD1'in data:
temp = data[4:7]
#print 'Got:', data
#string = str('A temperatura é',temp,'ºC')
conteudo.append(now.strftime("%Y-%m-%d %H:%M"))
conteudo.append(' ')
conteudo.append('[AD1]A temperatura é')
conteudo.append(temp)
conteudo.append('ºC')
print '[AD1]A temperatura é',temp,'ºC'
#print string
conteudo.append('\n')
arquivo = openarquivo = open('temperatura.txt','w')
arquivo.writelines(conteudo)
sleep(1)
#print 'not blocked'
arquivo.close()
ser.close()
答案 0 :(得分:0)
Python将从一系列if..elif..
测试中选择第一个匹配条件,并将仅执行一个代码块。
如果您的两个测试应该独立并且两者都应该考虑,请将elif
块替换为单独的if
语句:
if 'AD0'in data:
# ...
if 'AD1'in data:
# ...
现在两个条件将被独立测试,如果两者都匹配,则两者都将被执行。