简体   繁体   English

python为什么此子流程命令无法按预期工作

[英]python why this subprocess command doesn't work as expected

I was trying to use subprocess to extract lines from log file. 我试图使用子过程从日志文件中提取行。 The intention here is to extract the logs while some program is getting executed and wait for some time copy all the logs to another file. 目的是在执行某些程序时提取日志,并等待一段时间将所有日志复制到另一个文件。

#!/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"

This doesn't work - program gets stuck. 这不起作用-程序卡住了。

subprocess.check_output() waits for all the output. subprocess.check_output()等待所有输出。 It waits for the child process to exit or close its STDOUT stream. 它等待子进程退出或关闭其STDOUT流。

tail -f never exits and never closes its STDOUT stream. tail -f永远不会退出,也永远不会关闭其STDOUT流。 Therefore none of the lines of code below the call to check_output() will execute. 因此,check_output()调用下方的代码行均不会执行。

As the warning about deadlocks in https://docs.python.org/2/library/subprocess.html suggests, look at using Popen() and communicate() instead. 正如https://docs.python.org/2/library/subprocess.html中有关死锁的警告所建议的那样,请改用Popen()和communication()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM