Python:如果值 == 'null' 在读取日志时连续多次出现,我如何才能打破循环?

Python: How can I get a loop to break if the value == 'null' shows up multiple times in a row while reading a log?

正在读取 android 显示模式监视器,它给出了插入分辨率的值。如果连续多次读取“null”,我希望循环中断:

Display Mode:  720p60hz                                                                                       
Display Mode:  720p60hz                                                                                       
Display Mode:  null                                                                                       
Display Mode:  null                                                                                       
Display Mode:  null                                                                                       
Display Mode:  null

BREAK! 

CODE

import time
import subprocess

while True:

z = subprocess.getoutput("adb shell cat /sys/class/display/mode")
time.sleep(.1)
print(f'Display Mode:  {z}')

t1 = time.time()
t2 = time.time()
if z == 'null':


print(f't1 is :{t1}')

else:
continue

if z == 'null'
print(f't2 is :{t2}')
print('i am null')

if t2-t1 > .1:
  
  break

您上面的示例没有显示有效的 Python 代码。

为了您想要的结果,您可以将计数器初始化为 0,每次获得 null 时递增它,如果出现任何其他值则将其重置回 0:

counter = 0

while True: 
    if value == 'null':
        counter += 1
    else:
        counter = 0

    if counter < 5:
        # Code runs as usual here
    else:
        print("Too many null values in a row, halting")
        break

如果我能很好地理解您的代码,您正试图在 z 收到空值时打破循环。在 python 中我们使用 None 来表示空值。

尝试替换这一行:

if z == 'null'

对于这一行:

if z == None

您的代码有点难以阅读,因为缩进被遗漏了,而缩进是 Python 语法的一部分。 但这是我对您正在寻找的内容的最佳猜测:

import time
import subprocess

THRESHOLD_BAD_DISPLAY_READS = 10  # Set this to the number of bad reads in a row that you can tolerate
num_bad_display_reads = 0

while num_bad_display_reads < THRESHOLD_BAD_DISPLAY_READS:
    display_mode = subprocess.getoutput("adb shell cat /sys/class/display/mode")
    time.sleep(.1)
    if display_mode == 'null' or display_mode is None:
        num_bad_display_reads += 1  # Start counting up
    else:
        num_bad_display_reads = 0  # Reset the count
        #print(f'Display Mode:  {display_mode}')  # Uncomment this during debugging

# You have now left the display loop. Feel free to do something else.

我猜想 re-enter 如果显示恢复,则循环。如果那是真的,那么我建议您 post 在另一个 SO 问题中详细说明。

注意:我将z重命名为display_mode