gpt4 book ai didi

python-3.x - 仅将最后一个 shell 命令的标准输出放入 Python 变量中

转载 作者:行者123 更新时间:2023-12-04 13:29:28 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to get the last N lines of a subprocess' stderr stream output?

(2 个回答)


9 个月前关闭。




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 行或类似问题。相比之下,我只想要最后一个命令的输出。

最佳答案

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

关于python-3.x - 仅将最后一个 shell 命令的标准输出放入 Python 变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65952314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com