stdout 从 shell 中获取超过 1 行
stdout get previous more than 1 lines from shell
我正在使用这样的子进程从 shell 获取输出。
with subprocess.Popen(['bash', '-c', '. /root/myFile.sh;',
' func ' ], stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=1,universal_newlines=True) as proc_launch:
for line in proc_launch.stdout:
print(line, end='')
它逐行输出,而我想以最后 3 或 4 行加上当前行的方式获得输出。有什么方法可以干净地做到这一点吗?
如果我理解问题:你必须记住某些列表中的前几行并使用切片 [-3:]
显示该列表的最后 3 行。
previous_lines = list()
for line in proc_launch.stdout:
#remeber previous lines
previous_lines.append(line)
# get last 3 lines with current
text = ''.join(previous_lines[-3:])
# display it
print(text, end='')
顺便说一句:您可以使用变量轻松更改要显示的行数[-count:]
# before `for`-loop
count = 3
# inside `for`-loop
text = ''.join(previous_lines[-count:])
可能最干净的方法是使用 collections.deque
.
maxlen
参数专为您的用例设计:
Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. ... They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest.
双端队列比不断增加的列表甚至固定大小的列表更有效。
所以:
from collections import deque
last_lines = deque(4)
with subprocess.Popen(...) as proc_launch:
for line in proc_launch.stdout:
last_lines.append(line)
print(''.join(last_lines), end='')
我正在使用这样的子进程从 shell 获取输出。
with subprocess.Popen(['bash', '-c', '. /root/myFile.sh;',
' func ' ], stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=1,universal_newlines=True) as proc_launch:
for line in proc_launch.stdout:
print(line, end='')
它逐行输出,而我想以最后 3 或 4 行加上当前行的方式获得输出。有什么方法可以干净地做到这一点吗?
如果我理解问题:你必须记住某些列表中的前几行并使用切片 [-3:]
显示该列表的最后 3 行。
previous_lines = list()
for line in proc_launch.stdout:
#remeber previous lines
previous_lines.append(line)
# get last 3 lines with current
text = ''.join(previous_lines[-3:])
# display it
print(text, end='')
顺便说一句:您可以使用变量轻松更改要显示的行数[-count:]
# before `for`-loop
count = 3
# inside `for`-loop
text = ''.join(previous_lines[-count:])
可能最干净的方法是使用 collections.deque
.
maxlen
参数专为您的用例设计:
Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. ... They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest.
双端队列比不断增加的列表甚至固定大小的列表更有效。
所以:
from collections import deque
last_lines = deque(4)
with subprocess.Popen(...) as proc_launch:
for line in proc_launch.stdout:
last_lines.append(line)
print(''.join(last_lines), end='')