仅将最后一个shell命令的标准输出放入Python变量中 [英] Put only the stdout of the last shell command in a Python variable

查看:51
本文介绍了仅将最后一个shell命令的标准输出放入Python变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

prova.sh包含:

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.

此解决方案:

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

将所有shell命令的标准输出放入变量:

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.

但是我只想要最后一个shell命令的标准输出:

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

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

我怎么能得到这个?

Python 3.8.5

Python 3.8.5

现有问题仅涉及如何获得N行或类似的行.相比之下,我只想要最后一条命令的输出.

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

推荐答案

丢弃Bash脚本中先前命令的输出,因为不可能在Python端识别出哪个命令.

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.

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

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

这篇关于仅将最后一个shell命令的标准输出放入Python变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆