2015-05-09 36 views
3

我在做os.system来为活动文件添加尾部并为grep添加一个字符串 如何在grep成功时执行某些操作? 例如在python中从shell命令获取返回值

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

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

回答

0

您可以使用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)