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

编程入门 行业动态 更新时间:2024-10-16 00:21:15
本文介绍了如何获取子进程的 stderr 流输出的最后 N 行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I am a Python newbie writing a Python (2.7) script that needs to exec a number of external applications, one of which writes a lot of output to its stderr stream. What I am trying to figure out is a concise and succinct way (in Python) to get the last N lines from that subprocess' stderr output stream.

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

Currently, I am running that external application from my Python script like so:

p = subprocess.Popen('/path/to/external-app.sh', stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = pmunicate() 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 行输出,以便将它们写入日志文件或通过电子邮件发送等.

I'd like to capture the last N lines of output from its stderr stream so that they can be written to a log file or emailed, etc.

推荐答案

N = 3 # for 3 lines of output p = subprocess.Popen(['/path/to/external-app.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = pmunicate() 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

更多推荐

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

本文发布于:2023-06-11 14:50:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/637044.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:进程   stderr

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!