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


i trying figure out how send shell command, search string in line, , print x number of lines. able accomplish if use open read file having difficulty doing via shell. i'd able send shell command , use similar grep -a command. there pythonic way this? below testable code. in advance.

my code:

#!/usr/bin/python3 import subprocess  # works when use open read file:  open("test_file.txt", "r") myfile:     items in myfile:         if 'cherry' in items.strip():             index in range(5):                line = next(myfile)                print (line.strip())  # fails when try send command through shell  command = (subprocess.check_output(['cat', 'test_file.txt'], shell=false).decode('utf-8').splitlines()) items in command:     if 'cherry' in items.strip():         index in range(5):             line = next(command) 

output 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 not iterator  process finished exit code 1 

contents of test_file.txt:

--- fruits --- apple banana blueberry cherry dragonfruit  --- fruits --- artichoke arugula asparagus broccoli cabbage 

make iterator instead of letting for you... (may or may not work, didn't test this)

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

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -