Was*_*aer 4 python logging subprocess python-2.7
我想使用 Pythons subprocess.Popen 启动一个应用程序,并将应用程序 stdout 和 stderr 的输出以这样的方式logging.INFO("This is whats in stdout")
发送到日志记录模块,就像每次应用程序向 stdout/stderr 发送某些东西/某行一样。
由于应用程序是一个守护进程,它确实(并且应该)不会终止。
有没有一种简单的方法可以实现这一点,或者我是否必须使用单独的线程经常检查进程输出?
小智 5
这是我从jf-sebastian 的回答中作为可重用类的内容:
import subprocess
from threading import Thread
class BackgroundPopen(subprocess.Popen):
@staticmethod
def prefix_handler(prefix, io):
return lambda line: io.write(prefix + line)
@staticmethod
def _proxy_lines(pipe, handler):
with pipe:
for line in pipe:
handler(line)
def __init__(self, out_handler, err_handler, *args, **kwargs):
kwargs['stdout'] = subprocess.PIPE
kwargs['stderr'] = subprocess.PIPE
super(self.__class__, self).__init__(*args, **kwargs)
Thread(target=self._proxy_lines, args=[self.stdout, out_handler]).start()
Thread(target=self._proxy_lines, args=[self.stderr, err_handler]).start()
Run Code Online (Sandbox Code Playgroud)