将 bash 脚本拆分为单独的命令,并逐个运行它们



我希望能够从 Python 运行 bash shell 脚本(使用 subprocess.Popen 之类的东西(,但在我的 GUI 上显示命令,该命令将与输出一起实时执行,因为它以stdoutstderr出现。GUI 应显示Input (newline) Output (newline) Input等等。我目前能够为单行 bash 命令实现它,但我需要一个更复杂的多行命令解析器。这是我的代码,仅适用于bash中的简单单行命令。

test.sh:

ping -c 2 www.google.com
if [ "abc" = "ghi" ]; then
    echo expression evaluated as true
else
    echo expression evaluated as false
fi

我的蟒蛇文件:

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-elseloopsheredoc s 等的多行代码。我正在寻找一个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来跟踪命令及其参数的调用。

最新更新