【问题标题】:Put only the stdout of the last shell command in a Python variable [duplicate]仅将最后一个 shell 命令的标准输出放在 Python 变量中[重复]
【发布时间】: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


【解决方案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())

【讨论】:

  • 这只是一个例子,bash脚本很复杂,我想避免这种重定向到null,这是我首先想到的。
  • 我添加了一些解决方法
  • 您不必将> /dev/null 附加到每个命令。相反,将所有内容(最后一个命令除外)包装在一个组中; { ...; } > /dev/null.
  • 是一个很好的解决方案。随着文件的未来发展,我将不得不了解它是否适​​合我。
  • 意识到我的问题尚不存在真正的解决方案,我相信您的解决方案(写在评论中)是最接近的解决方案。为此,我投票给你作为最佳答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-29
  • 2016-09-08
  • 2021-07-24
  • 2011-12-15
  • 2014-12-11
  • 1970-01-01
  • 2011-05-16
相关资源
最近更新 更多