Search code examples
pythonlogcat

python grep multiple words in logcat


Shell script:

logcat | grep -E "one|two|three"

Python Code:

key_words = [ "one", "two", "three"]
log_lines = os.popen("logcat");

for log_line in log_lines:
   for keyword in key_words:
        if keyword in log_line:
             print log_line

Is there any optimizations to above python code?


Solution

  • To emulate the exact pattern in your grep command, do

    import re
    
    pattern = re.compile('|'.join(key_words))
    
    for log_line in log_lines:
        if pattern.search(log_line):
            print log_line
    

    If you want to allow special characters, you'll have to escape them:

    pattern = re.compile('|'.join(re.escape(word) for word in key_words))
    

    As you can imagine, using regex is a bit overkill in this case. Instead, you can do a direct search. You can use any to help with the search, since it short circuits.

    for log_line in log_lines:
        if any(word in log_line for word in key_words):
            print log_line
    

    This performs a linear search of the entire line for each keyword. You can make that a bit more efficient if the keywords are intended to be actual words, especially since you already have a set for the keywords:

    for log_line in log_lines:
        if keywords.intersection(set(log_line.split()):
            print log_line