我希望能够从 Python 运行 bash shell 脚本(使用类似 subprocess.Popen
的东西),但在我的 GUI 上显示将要执行的命令以及实时输出位于 stdout
和 stderr
中。 GUI 应显示输入(换行)输出(换行)输入
等。我目前能够为单行 bash 命令实现它,但我需要一个更复杂的解析器来处理多行命令。这是我的代码,仅适用于 bash
中的简单单行命令。
测试.sh:
ping -c 2 www.google.com
if [ "abc" = "ghi" ]; then
echo expression evaluated as true
else
echo expression evaluated as false
fi
我的Python文件:
with open("test.sh", "r") as script:
for line in script:
if not line.strip().startswith('#') and not line.strip() == "":
print("Debug: Running " + line.strip() + " ...")
proc = subprocess.Popen(shlex.split(line), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
output = str(proc.stdout.readline().strip().decode()) + ""
err = str(proc.stderr.readline().strip().decode()) + ""
if output == '' and proc.poll() is not None:
print("Debug: Command completed...")
time.sleep(1)
break
if output:
# Code for updating a Gtk TextView buffer
GLib.idle_add(self.updateConsoleText, output + "\n")
if err:
# Code for updating a Gtk TextView buffer
GLib.idle_add(self.updateConsoleText, err + "\n")
正如预期的那样,它不适用于涉及 if-else
、loops
、heredoc
等的多行代码。我正在寻找一个 bash 解析器,它至少可以识别命令何时结束,并且在使用多行命令的情况下可以将 bash 脚本拆分为单独的命令。
你认为你可以帮我找到这样的库/工具吗?
最佳答案
您可以使用 trap 命令。
这里有一个小例子来演示这个概念:
#!/bin/bash
# redirect stderr to a logfile
exec 2>/tmp/test.log
# print commands and arguments at execution
set -x
# set trap for every step, sleep one second.
# "sleep 1" could be every bash command
trap "sleep 1" DEBUG
echo -n "Name: "; read -r name
echo -n "Age: "; read -r age
echo "$name is $age years old"
与此脚本运行并行,您可以使用 tail -f/tmp/test.log
来跟踪命令及其参数的调用。
关于python - 将 bash 脚本拆分为单独的命令并一一运行它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56402805/