2016-07-22 68 views
0

我正在尝试使用子进程从日志文件中提取行。这里的意图是在某些程序正在执行时提取日志,并等待一段时间将所有日志复制到另一个文件。python为什么这个子进程命令不能按预期工作

#!/bin/python 

import threading 
import time, subprocess 


class GetLogs(threading.Thread): 
    ''' 
     Get the developer logs 
    ''' 
    def __init__(self): 
     ''' 
     init 
     ''' 
     self.stop = False 
     threading.Thread.__init__(self) 
     print "Initialised thread" 

    def run(self): 
     ''' 
      Collect the logs from devlog 
     ''' 
     command = "tail -f /var/log/developer_log | tee /tmp/log_collected" 
     response = subprocess.check_output(command.split(), shell=True) 
     print "Subprocess called"+str(response) 

     while (self.stop is False): 
      time.sleep(1) 
      print "Continuing" 
      continue 

     print "Finished the log file" 


gl = GetLogs() 
gl.start() 

##Do some activity here 
print "Sleeping for 10 sec" 
time.sleep(10) 
gl.strop = True 

print "Done" 

这不起作用 - 程序卡住了。

+0

你不能这样等待子进程 – YOU

回答

1

subprocess.check_output()等待全部的输出。它等待子进程退出或关闭其STDOUT流。

tail -f永不退出,永不关闭其STDOUT流。因此,调用check_output()之后的代码行都不会执行。

由于关于https://docs.python.org/2/library/subprocess.html中的死锁警告建议,请查看使用Popen()和communicate()来代替。

+0

非常感谢你的回复。 – user2677279

+0

我试图用Popen来做。仍然面临相同/相似的问题是我的代码 – user2677279

相关问题