首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python搜索字符串并打印下一个x行数。

Python搜索字符串并打印下一个x行数。
EN

Stack Overflow用户
提问于 2016-11-10 16:31:52
回答 1查看 57关注 0票数 1

我试图弄清楚如何发送shell命令,搜索一行中的字符串,并打印x行数。如果我使用open读取文件,但在通过shell读取文件时遇到困难,我就能够做到这一点。我希望能够发送一个shell命令并使用类似的grep -A命令。有什么毕达通的方法吗?下面是我的可测试代码。提前谢谢。

我的守则:

代码语言:javascript
复制
#!/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)

输出错误:

代码语言:javascript
复制
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的内容:

代码语言:javascript
复制
--- Fruits ---
Apple
Banana
Blueberry
Cherry
Dragonfruit

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

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-10 16:39:05

自己做迭代器,而不是让for为你做.(可能有用,也可能不起作用,我没有确切地测试这个)

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40532584

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档