Put only the stdout of the last shell command in a Python variable [duplicate]

两盒软妹~` 提交于 2021-02-18 07:50:07

问题


prova.sh contains:

#!/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.

This solution:

import subprocess
output = subprocess.check_output('./prova.sh', shell=True, text=True)
print(output, end='')

puts the stdout of all shell commands in a variable:

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.

but I just want the stdout of the last shell command:

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

How can I get this?

Python 3.8.5

Existing questions only address how to get N lines or similar. In contrast, I only want the output of last command.


回答1:


Throw away the output of previous commands in Bash script, coz it's impossible to identify which command is which command on Python side.

#!/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.

Another solution is writing the output of last command to file:

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


来源:https://stackoverflow.com/questions/65952314/put-only-the-stdout-of-the-last-shell-command-in-a-python-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!