2016-11-10 76 views
1

我想弄清楚如何发送shell命令,搜索一行中的字符串,并打印x行。如果我使用open来读取文件,但是很难通过shell来完成,我能够完成此操作。我希望能够发送一个shell命令并使用类似的grep -A命令。有没有Pythonic的方式来做到这一点?以下是我的可测试代码。提前致谢。Python搜索字符串并打印下一个x行

我的代码:

#!/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) 

输出与错误:

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 

test_file.txt的内容:

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

--- Fruits --- 
Artichoke 
Arugula 
Asparagus 
Broccoli 
Cabbage 
+0

你已经将一个列表包装在一个生成器中。删除'subprocess.check_output'行周围的多余的parens。 (这需要'check_output'返回的列表,并将其包裹在一个生成器中,这不是你想要的,我确定,哈哈。) –

+1

@PierceDarragh我不认为它确实如此。你需要一个生成器表达式。 –

+0

@Pierce Darragh,删除括号并没有帮助。它仍在评估为具有相同错误的列表。 – MBasith

回答

0

使自己,而不是让for迭代器为你做...(可能或可能不工作,我没有完全测试这个)

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) 
+0

这也没有完全做到。我得到一个空输出。 – MBasith

+0

我错过了打印声明!这很好。谢谢。 – MBasith

+0

@MBasith对不起,我大概可以推断你会有一个打印声明,并把它放在..很高兴我可以帮助 – Aaron

相关问题