将上一个shell命令的标准输出存入Python变量中

3

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行或类似内容。与此相反,我只想要上一个命令的输出。


你认为“最后的stdout”是什么?是最后一行还是最后一批写入stdout? - MisterMiyagi
对于一个 shell 子进程,你只需要执行 "./prova.sh | tail -n 1",就不用担心了。@MisterMiyagi 提供的示例非常好,如果输出不是很大的话。如果你需要在 Python 中执行此操作,对于大量输入,我建议直接使用 subprocess.run 管道和环形缓冲区。 - petrch
你认为“最后的stdout”是什么?是最后一行,还是最后一批写入stdout的内容?关于这个问题,我也已经更改了我的问题标题以使其更清晰。 - Mario Palumbo
一般来说,你实际上是无法做到的。你所要求的并没有明确定义 - “stdin” /“stdout” /“stderr”是字节流,它们的有效负载与其生成方式没有明显的联系。你可以对内容(例如换行符以获取“最后n行”)做出反应,但不能对源进行反应。 - MisterMiyagi
1
我对重新开放投票持有相当犹豫的态度;虽然我们不再将“没有展示基本理解”作为关闭问题的原因,但这真的会帮助未来的访问者吗? - tripleee
显示剩余4条评论
1个回答

1

在Bash脚本中丢弃先前命令的输出,因为在Python端无法识别哪个命令是哪个命令。

#!/bin/bash
echo "Output that I don't want." >/dev/null
echo "Output that I don't want." >/dev/null
echo "Output that I don't want." >/dev/null
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.

另一个解决方案是将上一个命令的输出写入文件:

# Modify the Bash script
import io, re
with io.open("prova.sh","r") as f:
    script  = f.read().strip()
    script  = re.sub(r"#.*$","",script).strip() # Remove comment
    script += "\x20>out.txt"                    # Add output file

with io.open("prova.sh","w") as f:
    f.write(script)

# Execute it
import subprocess
output = subprocess.check_output("./prova.sh", shell=True)
# print(output.decode("utf-8"))

# Get output
with io.open("out.txt","r") as f:
    print(f.read())

1
这只是一个例子,这个Bash脚本非常复杂,我希望避免将其重定向到null,这是我最先考虑的事情。 - Mario Palumbo
我已经添加了一些解决方法。 - Dee
1
你不必在每个命令后面添加 > /dev/null。相反,将除了最后一个命令以外的所有内容都包裹在一个单独的组内; { ...; } > /dev/null - Socowi
1
这是一个不错的解决方案。随着文件未来的发展,我将不得不了解它是否适合我。 - Mario Palumbo
1
我已经意识到我的问题还没有一个真正的解决方案,我相信你在评论中提供的解决方案是最接近的。因此,我投票选你为最佳答案。 - Mario Palumbo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接