-1

I already have an android emulator instance open in the background. I want to write a python script that can use subprocess module to grep the logcat for a certain word, and return the latest (based on timestamp) result from that search as a string. How to do this?

adb logcat | grep keyword
>> 00:00:01 keyword
>> 00:00:02 keyword
>> 00:00:03 keyword

want python script that will return the line "00:00:03 keyword"

    proc = subprocess.Popen(['adb', 'logcat', '| grep keyword'], stdout=subprocess.PIPE)
    last_result=read_last_result(proc)
user2611836
  • 386
  • 4
  • 6
  • 17
  • Have you tried the [re](https://docs.python.org/2/library/re.html) module? There is also a "[Regular Expressions HOWTO](https://docs.python.org/2/howto/regex.html)" on the official Python site which you might find helpful. – Greg Sadetsky May 16 '16 at 18:37

1 Answers1

0

To get the last line from subprocess' stdout:

#!/usr/bin/env python3
from collections import deque
from subprocess import Popen, PIPE

with Popen('adb -d logcat <filter-spec>'.split(), stdout=PIPE) as adb:
    last_line = deque(adb.stdout, maxlen=1).pop() # get last line

See adb logcat options.

If you want to emulate the 'adb logcat | grep keyword' shell command literally, see How do I use subprocess.Popen to connect multiple processes by pipes?

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670