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

标签 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

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

最佳答案

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

关于python - 如何获取子进程的 stderr 流输出的最后 N 行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4995095/

相关文章:

linux - 如何使用 shell 脚本验证用户密码?

python - 在 python 3 中使用 pip 导入运行时安装的模块

python - 如何对暴力进行密码的所有排列?

python - 解释了两种不同合并排序实现之间的比较

python - 有效地识别发生在开始和结束时间戳之间的事件

脚本语言与编程语言

vim - 在vim中自动折叠#defines

python - 如何将此命令传递给 subprocess.call?

python3.6 - TypeError : write() argument must be str, 不是字节 - 但不涉及文件

python - Matplotlib 绘制多条线不起作用