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())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)