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

发布于 2024-10-17 20:57:05 字数 611 浏览 1 评论 0原文

我是一名 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 行输出,以便可以将它们写入日志文件或通过电子邮件发送等。

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.

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 = 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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悲歌长辞 2024-10-24 20:57:05
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
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
屋顶上的小猫咪 2024-10-24 20:57:05

如果整个输出无法存储在 RAM 中,则:

import sys

from collections import deque
from subprocess  import Popen, PIPE
from threading   import Thread

ON_POSIX = 'posix' in sys.builtin_module_names

def start_thread(func, *args):
    t = Thread(target=func, args=args)
    t.daemon = True
    t.start()
    return t

def consume(infile, output):
    for line in iter(infile.readline, ''):
        output(line)
    infile.close()

p = Popen(['cat', sys.argv[1]], stdout=PIPE, stderr=PIPE,
          bufsize=1, close_fds=ON_POSIX)

# preserve last N lines of stdout,  print stderr immediately
N = 100 
queue = deque(maxlen=N)
threads  = [start_thread(consume, *args)
            for args in (p.stdout, queue.append), (p.stderr, sys.stdout.write)]
for t in threads: t.join() # wait for IO completion

print ''.join(queue), # print last N lines
retcode = p.wait()

If the whole output can't be stored in RAM then:

import sys

from collections import deque
from subprocess  import Popen, PIPE
from threading   import Thread

ON_POSIX = 'posix' in sys.builtin_module_names

def start_thread(func, *args):
    t = Thread(target=func, args=args)
    t.daemon = True
    t.start()
    return t

def consume(infile, output):
    for line in iter(infile.readline, ''):
        output(line)
    infile.close()

p = Popen(['cat', sys.argv[1]], stdout=PIPE, stderr=PIPE,
          bufsize=1, close_fds=ON_POSIX)

# preserve last N lines of stdout,  print stderr immediately
N = 100 
queue = deque(maxlen=N)
threads  = [start_thread(consume, *args)
            for args in (p.stdout, queue.append), (p.stderr, sys.stdout.write)]
for t in threads: t.join() # wait for IO completion

print ''.join(queue), # print last N lines
retcode = p.wait()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文