2016-11-10 66 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

相關問題