Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

Reading an android display mode monitor which gives the value of the plugged in resolution. I want the loop to break if it reads "null" multiple times in a row:

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your code is a bit hard to read because the indentation was left out, and indentation is a part of Python syntax.
But here’s my best guess for what you’re looking for:

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:
        display_mode = 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.

My guess is that you would like to re-enter the loop if the display recovers. If that’s true, then I recommend that you post some specifics about that in another SO question.

Note: I renamed z to display_mode.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading