Python 子流程&x2013;显示X行输出

Python 子流程&x2013;显示X行输出,python,subprocess,output,Python,Subprocess,Output,我调用运行可执行文件的子流程,该可执行文件输出如下内容: Header some text some text -------------------------------- Progress: *** | 30% I want this line too 我想要最后三行,但不要前面几行。进度会自动更新,这也是我想要的 我目前: print subprocess.call('program {options}'.format(options=options), shell

我调用运行可执行文件的子流程,该可执行文件输出如下内容:

Header
some text
some text
--------------------------------
Progress:
***           | 30%
I want this line too
我想要最后三行,但不要前面几行。进度会自动更新,这也是我想要的

我目前:

print subprocess.call('program {options}'.format(options=options), shell=True)

有没有一个简单的方法来实现这一点?

调用
方法是一个包装在
Popen
周围的方法,它等待程序完成,这可能不是您想要的。相反,您需要使用
Popen
并从它的
stdout
读取数据

答案在一定程度上取决于您使用的程序,或者更具体地说,取决于它如何更新终端。这里有一个解决方案,可以让您了解如何实现这一点。您可能需要对此进行调整。
例如,在我的示例中,实际上只更新了progressbar本身。您的示例可能会更新更多行

#!/usr/bin/env python2

from __future__ import print_function
import subprocess

proc = subprocess.Popen(['./out.py'], shell=True,
    stdout=subprocess.PIPE)

# Discard first 4 lines
for i in range(4): proc.stdout.readline()

# First set of output
output = ''.join([ proc.stdout.readline() for i in range(3) ])
print(output.strip())
print('\n\n')

# Only one line is updated now
while True:
    output = proc.stdout.readline()

    print(output.strip().replace('\x1b[1A', ''))
作为参考,这里的
out.py
使progressbar

#!/usr/bin/env python2

from __future__ import print_function
import time, sys

print('Header')
print('some text')
print('some text')
print('-' * 40)
print('Progress:')
print('')
print('I want this line too')

sys.stdout.write('\x1b[1A' * 2)
i = 1
while True:
        if i > 40: break

        print('\r', '*' * i, sep='')
        sys.stdout.write('\x1b[1A')
        sys.stdout.flush()
        i += 1
        time.sleep(2)
奖金小费 此外,您可能希望在列表中使用
subprocess
方法,如下所示:

subprocess.call(['ls', '-l', dir], shell=True)
原因是列表中的参数将被转义,即使它们包含空格、换行符或任何其他意外字符,也仍然有效。如果您使用的是
shell=True
,这尤其危险。如果由于某种原因无法将参数作为列表传递,请确保使用
shlex
模块