在while循环中使用return将会停止循环,如何解决?
ser = serial.Serial(
port='COM5',
baudrate = 9600,
timeout=1)
while 1:
x=str(ser.readline())
x = re.findall("\d+\.\d+", x)
x = float(x[0])
return(x) #loop stopped
print(x)
你能帮我吗?
在while循环中使用return将会停止循环,如何解决?
ser = serial.Serial(
port='COM5',
baudrate = 9600,
timeout=1)
while 1:
x=str(ser.readline())
x = re.findall("\d+\.\d+", x)
x = float(x[0])
return(x) #loop stopped
print(x)
你能帮我吗?
yield
。
您可以修改您的代码如下:
def func():
while 1:
x=str(ser.readline())
x = re.findall("\d+\.\d+", x)
x = float(x[0])
yield x
然后调用函数。请注意,f将是一个生成器,因此您需要像下面一样循环遍历它。
f = func()
for i in f:
print(i) # or use i for any purpose
只需取出你的
x=str(ser.readline())
x = re.findall("\d+\.\d+", x)
x = float(x[0])
return(x) #loop stopped
def foo(ser):
x=str(ser.readline())
x = re.findall("\d+\.\d+", x)
x = float(x[0])
return(x)
并将您的 while 循环简化为以下内容
while 1:
print(foo(ser))
然而,@developius提供了一个更好的解决方案,大致如下:
while 1:
x=str(ser.readline())
x = re.findall("\d+\.\d+", x)
x = float(x[0])
print(x)
你可以试试这个
while 1:
x=str(ser.readline())
x = re.findall("\d+\.\d+", x)
x = float(x[0])
return x
yield
? - tobias_kreturn
呢?在while
循环中更新显示的值不是更好吗? - developius