Python 如何在for循环中仅显示最后N行?

Python 如何在for循环中仅显示最后N行?,python,loops,for-loop,Python,Loops,For Loop,我正在创建一个脚本,用于连接存储阵列并运行命令 stdin, stdout, stderr = ssh.exec_command("statvv -rw -iter 1") for status in stdout: result = (status) print(result) 输出如下: V90Z_10_3PAR05 t 0.00 0.00 0.0 0 0 V91A_10_3PAR05 r 0.00 0.00 0.0 0 0.0- V91A_10_3PAR05 w 0.00

我正在创建一个脚本,用于连接存储阵列并运行命令

stdin, stdout, stderr = ssh.exec_command("statvv -rw -iter 1")
for status in stdout:
    result = (status)
    print(result)
输出如下:

V90Z_10_3PAR05 t 0.00 0.00 0.0 0 0
V91A_10_3PAR05 r 0.00 0.00 0.0 0 0.0-
V91A_10_3PAR05 w 0.00 0.00 0.0 0 0.0-
V91A_10_3PAR05 t 0.00 0.00 0.0 0 0.0 0
--
309 r 1577 1577 112637 112637 1.83 1.83 71.4 71.4-
309 w 20158 20158 1125017 1125017 1.49 1.49 55.8 55.8-
309 t 21736 21736 1237653 1237653 1.52 1.52 56.9 56.9 7

但是我只想打印
--
之后的最后几行,而不想将其保存到文件中。

我对statvv不太熟悉,但是如果您知道所需的行总是在一行读取
'--'
之后,您可以保留一个布尔值,跟踪您是否看到它:

stdin, stdout, stderr = ssh.exec_command("statvv -rw -iter 1")
final_status = False
for status in stdout:
    if final_status:
        print(status)
    elif status == '--':
        final_status = True

如果您知道要跳过的行数,则可以保留一个计数器并执行以下操作:

counter = 0 
MAX_COUNT = number_of_lines_you_want_to_skip
for status in stdout:
    if counter > MAX_COUNT:
        result = (status)
        print(result)
    else:
        counter ++
如果您不知道这些行,您可以一直阅读,直到看到一个
“--”
(这就是您问题中的代码片段的样子),然后只打印
“--”后面的那些行


希望这有帮助

如果您知道预期的行数,可以跳过前N-M行并打印剩余的M行。如果您不知道,请将所有行收集到列表中,然后打印列表中的最后M行。这就像
打印(“\n”).join(list(stdout)[-M:])
一样简单。如果行数始终相同,只需通过远程主机上的
tail
管道即可。这样,您就不会传输不打算使用的数据。这些破折号是不是stdout
的一部分?@DyZ不是一个列表,而是一个(文档中描述为“类似于Unix中的尾部过滤器”)以提高效率。Hi Prune。破折号是stdouthanks的一部分。帮我听了很多:)谢谢ryanmrubin
seen_dash_flag = false
for status in stdout:
    if status.startswith("--"):
        seen_dash_flag = true
    if seen_dash_flag:             
            result = (status)
            print(result)