如何在python中生成另一个进程并捕获输出?

我只是在学习 Python,但在PERL和PHP方面有大约16年的经验.

我正在尝试获取ngrep的输出并使用Python将其写入日志文件,同时还会拖尾日志文件.我在网上看过一些例子,但有些看起来过时而且过时了,其他人使用shell = True,这是不鼓励的.

在perl中我只使用类似于以下内容的东西

#!/usr/bin/perl
open(NGFH,"ngrep -iW byline $filter");
while ($line = <NGFH>) {
    open(LOG,">> /path/to/file.log")
    // highlighting, filtering, other sub routine calls
    print LOG $line
}

我已经开始工作,但ngrep没有.我想能够无限地运行它并在过滤后将流从ngrep输出到日志文件.我无法从ngrep获得输出以显示在stdout中,所以这就是我已经得到的.我希望能够在更新日志文件时看到数据文件尾部,并查看ngrep的输出.现在我只是使用bash运行以下内容.

echo "." >> /path/to/ngrep.log

谢谢!

这是我到目前为止所得到的……

更新
这似乎现在有效.我不知道如何改进它.

import subprocess
import select
import re

log = open('/path/to/ngrep.log','a+',0)
print log.name

n = subprocess.Popen(['ngrep', '-iW', 'byline'],\
    stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
p = select.poll()
p.register(n.stdout)

f = subprocess.Popen(['tail','-F','-n','0','/path/to/tailme.log'],\
    stdout=subprocess.PIPE,stderr=subprocess.PIPE)
p2 = select.poll()
p2.register(f.stdout)

def srtrepl(match):
    if match.group(0) == 'x.x.x.x':
        # do something
    if match.group(0) == 'x.x.y.y':
        # do something else

    return '\033[92m'+ match.group(0) + '\033[0m'

while True:
    if p.poll(1):
        line = n.stdout.readline()
        s = re.compile(r'(8.8.(4.4|8.8)|192.168.[0-9]{1,3}.[0-9]{1,3})' )
        print s.sub( srtrepl, line )
        log.write(n.stdout.readline())

    if p2.poll(1):
        print f.stdout.readline().rstrip('\n')

最佳答案 要在Python中模拟perl代码:

#!/usr/bin/env python3
from subprocess import Popen, PIPE

with Popen("ngrep -iW byline".split() + [filter_], stdout=PIPE) as process, \
     open('/path/to/file.log', 'ab') as log_file:
    for line in process.stdout: # read b'\n'-separated lines
        # highlighting, filtering, other function calls
        log_file.write(line)

它启动ngrep进程传递filter_变量并将输出附加到日志文件,同时允许您在Py​​thon中修改它.请参阅Python: read streaming input from subprocess.communicate()(可能存在缓冲问题:检查ngrep是否支持 – 像grep这样的–line-buffered选项,如果你想在post_file.write(line)之后拖尾file.log然后调用log001,或者调用log_file.flush()).

您也可以在纯Python中模拟ngrep.

如果你想同时读取几个进程的输出(在你的情况下为ngrep,tail),你需要能够read pipes without blocking e.g., using threads, async.io.

点赞