我试图找出如何发送shell命令,在一行中搜索字符串,以及打印x行数。如果我使用open来读取文件但是通过shell执行它有困难,我能够完成此操作。我希望能够发送一个shell命令并使用类似的grep -A命令。是否有Pythonic方法来做到这一点?下面是我可测试的代码。提前谢谢。
我的代码:
#!/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 :(得分: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)