MBasith MBasith - 27 days ago 15
Python Question

Python search for a string and print the next x number of lines

I am trying to figure out how to send a shell command, search for a string in a line, and print x number of lines. I am able to accomplish this if I use open to read the file but having difficulty doing it via the shell. I'd like to be able to send a shell command and use the similar grep -A command. Is there a Pythonic way to do this? Below is my testable code. Thanks in advance.

My Code:

#!/usr/bin/python3
import subprocess

# Works when I use open to read the file:

with open("test_file.txt", "r") as myfile:
for items in myfile:
if 'Cherry' in items.strip():
for index in range(5):
line = next(myfile)
print (line.strip())

# Fails when I try to send the command through the shell

command = (subprocess.check_output(['cat', 'test_file.txt'], shell=False).decode('utf-8').splitlines())
for items in command:
if 'Cherry' in items.strip():
for index in range(5):
line = next(command)


Output with Error:

Dragonfruit

--- Fruits ---
Artichoke
Arugula

------------------------------------------------------------------------------------------

Traceback (most recent call last):
File "/media/next_line.py", line 26, in <module>
line = next(command)
TypeError: 'list' object is not an iterator

Process finished with exit code 1


Contents of test_file.txt:

--- Fruits ---
Apple
Banana
Blueberry
Cherry
Dragonfruit

--- Fruits ---
Artichoke
Arugula
Asparagus
Broccoli
Cabbage

Answer

make the iterator yourself instead of letting for do it for you... (may or may not work, I didn't exactly test this)

command = (subprocess.check_output(['cat', 'test_file.txt'], shell=False).decode('utf-8').splitlines())
iterator = iter(command)
for items in iterator:
    if 'Cherry' in items.strip():
        for index in range(5):
            line = next(iterator)