简体   繁体   English

在子进程运行时读取日志文件

[英]Read a log file while a subprocess is running

I have a process that outputs logs to a file, and I'm trying to make a python script to run that process and output only the log that it generates into that log file.我有一个将日志输出到文件的进程,我正在尝试制作一个 python 脚本来运行该进程并仅将它生成的日志输出到该日志文件中。

What I wrote below seems to do what I want except for one big issue: it never exists the while loop.我在下面写的内容似乎做了我想做的事情,除了一个大问题:它从不存在 while 循环。 I've tried a few other alternatives with no luck.我尝试了一些其他的选择,但没有运气。

Any help here would be really appreciated!这里的任何帮助将不胜感激! I guess it's worth noting I could also use node script instead...我想值得注意的是,我也可以使用节点脚本代替...

import subprocess
import sh

process = subprocess.Popen(cmd)

log_tail = sh.tail("-f", log_file, _iter=True)

while process.returncode is None:
    sys.stdout.write(log_tail.next())
    sys.stdout.flush()
    process.poll()

The tail -f command is intended to run until explicitly interrupted, which is why the loop is never exited. tail -f命令旨在运行直到被明确中断,这就是循环永远不会退出的原因。 You could try this:你可以试试这个:

import subprocess

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()

which will wait until the cmd terminates and return the contents of its output streams in stdout and stderr .它将等到cmd终止并在stdoutstderr返回其输出流的内容。

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

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