仅将最后一个shell命令的stdout放入Python变量中



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命令的stdout:

Output that I want.
I want this too.
I want this too.

我怎样才能得到这个?

Python 3.8.5

现有问题仅解决如何获得N行或类似的问题。相比之下,我只想要最后一个命令的输出。

在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())

最新更新