如何获取子进程的 stderr 流输出的最后 N 行?

ssa*_*555 2 python scripting subprocess

我是一名 Python 新手,正在编写一个 Python (2.7) 脚本,该脚本需要执行许多外部应用程序,其中一个应用程序将大量输出写入其 stderr 流。我试图找出一种简洁明了的方法(在Python中)从该子进程的stderr输出流中获取最后N行。

目前,我正在从 Python 脚本运行该外部应用程序,如下所示:

p = subprocess.Popen('/path/to/external-app.sh', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()

if p.returncode != 0:
    print "ERROR: External app did not complete successfully (error code is " + str(p.returncode) + ")"
    print "Error/failure details: ", stderr
    status = False
else:
    status = True
Run Code Online (Sandbox Code Playgroud)

我想从其 stderr 流中捕获最后 N 行输出,以便可以将它们写入日志文件或通过电子邮件发送等。

nos*_*klo 5

N = 3 # for 3 lines of output
p = subprocess.Popen(['/path/to/external-app.sh'], 
    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()

if p.returncode != 0:
    print ("ERROR: External app did not complete successfully "
           "(error code is %s)" % p.returncode)
    print "Error/failure details: ", '\n'.join(stderr.splitlines()[-N:])
    status = False
else:
    status = True
Run Code Online (Sandbox Code Playgroud)