2015-05-09 34 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)