This is a follow-up question to the solution provided in this page
This is the code in my script:
cmd = "adb logcat | sed -n '/pattern1/p;/pattern2/q'"
getLogs,error = subprocess.Popen(['/bin/bash', '-c', cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
adb logcat | sed -n '/pattern1/p;/pattern2/q'
works fine in the terminal, but sed does not quit when the same code is used in the script.
I dont want to use 'adb logcat -d |
' here because I want the script to run when I am doing something in the device and not after I have finished doing the user-action.
Wrapping sed
into bash
and then into python
is bad karma.
import subprocess
def logcat_iterator(options, display_pattern, quit_pattern):
popen = subprocess.Popen(['adb', 'shell', 'logcat {}'.format(options)], stdout=subprocess.PIPE)
iterator = iter(popen.stdout.readline, b'')
for line in iterator:
if len(line) > 0:
if line.find(quit_pattern) > 0:
break
elif line.find(display_pattern) > 0:
yield line
Use it like this:
for l in logcat_iterator('-b main -v time', 'Displayed', 'Displayed com.android.settings/.Settings'):
print l