在python中从shell命令获取返回值

在python中从shell命令获取返回值,python,shell,unix,Python,Shell,Unix,我正在用os.system跟踪一个实时文件,用grep跟踪一个字符串 当grep成功时,我如何执行某些操作? 比如说 cmd= os.system(tail -f file.log | grep -i abc) if (cmd): #Do something and continue tail 我有什么办法可以做到这一点吗?当os.system语句完成时,它只会出现在if块。您可以使用subprocess.Popen并从标准输出读取行: import subpro

我正在用
os.system
跟踪一个实时文件,用
grep
跟踪一个字符串 当grep成功时,我如何执行某些操作? 比如说

cmd=  os.system(tail -f file.log | grep -i abc)
if (cmd):     
         #Do something and continue tail

我有什么办法可以做到这一点吗?当os.system语句完成时,它只会出现在
if
块。

您可以使用
subprocess.Popen
并从标准输出读取行:

import subprocess

def tail(filename):
    process = subprocess.Popen(['tail', '-F', filename], stdout=subprocess.PIPE)

    while True:
        line = process.stdout.readline()

        if not line:
            process.terminate()
            return

        yield line
例如:

for line in tail('test.log'):
    if line.startswith('error'):
        print('Error:', line)
  • 我不确定您是否真的需要在python中执行此操作-也许将
    tail-f
    输出导入awk会更容易:

  • 如果您想在python中工作(因为您需要在之后进行一些处理),那么请查看关于如何使用
    tail-f