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

Viewed 311

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 Answers

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