在Python字符串中找到一行(不是文件)

jdb*_*org 1 python regex grep

我知道如何使用文件执行此操作,您只需执行file = file.open(f)f

file = open("file.txt")
for line in file.readlines():
  if line.startswith("foo"):
    print line
Run Code Online (Sandbox Code Playgroud)

但现在我正在阅读这样一个过程的输出

log = os.popen("log.sh").read()
Run Code Online (Sandbox Code Playgroud)

这输出为一个字符串,可以与打印精细一起使用,但是如果我执行"for log in log"它会分割每个字符,而不是行.而且,作为一个字符串,没有.readlines()属性.

我的最终目标是能够"grep"日志中的修订号并打印该行(以及上方和下方)

Sve*_*ach 9

for line in log.splitlines():
    # whatever
Run Code Online (Sandbox Code Playgroud)

请注意,您不需要使用f.readlines()文件f.

for line in f:
    # whatever
Run Code Online (Sandbox Code Playgroud)

会很好的.


NPE*_*NPE 6

你有几个选择:

选项1:

log = os.popen("log.sh").readlines()
Run Code Online (Sandbox Code Playgroud)

这给出了一个字符串列表,您可以像处理文件时那样处理它.

选项2:

log = os.popen("log.sh").read()
for line in log.splitlines(True):
   ...
Run Code Online (Sandbox Code Playgroud)