【发布时间】:2021-02-03 17:20:47
【问题描述】:
prova.sh 包含:
#!/bin/bash
echo "Output that I don't want."
echo "Output that I don't want."
echo "Output that I don't want."
echo -e "Output that I want.\nI want this too.\
\nI want this too." #This is the last command of the bash script, which is what I'm looking for.
这个解决方案:
import subprocess
output = subprocess.check_output('./prova.sh', shell=True, text=True)
print(output, end='')
将所有shell命令的标准输出放在一个变量中:
Output that I don't want.
Output that I don't want.
Output that I don't want.
Output that I want.
I want this too.
I want this too.
但我只想要最后一个 shell 命令的标准输出:
Output that I want.
I want this too.
I want this too.
我怎样才能得到这个?
Python 3.8.5
现有问题仅解决如何获得 N 行或类似的问题。相比之下,我只想要最后一个命令的输出。
【问题讨论】:
-
你认为“最后一个标准输出”是什么?最后行,还是最后batch写入stdout?
-
对于 shell 子进程,您只需执行“./prova.sh | tail -n 1”,您不必担心。如果输出不大,@MisterMiyagi 提供的示例非常好。如果您需要在 python 中执行此操作。对于大量输入,我建议可能直接使用带有环形缓冲区的 subprocess.run 管道。
-
“你认为“最后一个标准输出”是什么?最后一行,还是最后一批写入标准输出?关于这个问题,我也把问题的标题改了更清楚。
-
一般来说,你确实不能。您要求的内容没有明确定义——
stdin/stdout/stderr是字节流,它们的有效负载与它的产生方式没有明显的联系。您可以对 content 做出反应(例如换行以获得“最后 n 行”),但不能对源做出反应。 -
我很犹豫是否要重新开放;我们不再将“没有表现出基本的理解”作为密切的理由,但这真的会帮助未来的访客吗?
标签: python-3.x bash