python - 将 bash 脚本拆分为单独的命令并一一运行它们

标签 python bash shell subprocess gtk

我希望能够从 Python 运行 bash shell 脚本(使用类似 subprocess.Popen 的东西),但在我的 GUI 上显示将要执行的命令以及实时输出位于 stdoutstderr 中。 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-elseloopsheredoc 等的多行代码。我正在寻找一个 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/

相关文章:

arrays - shell将字符串添加到数组

mysql - 避免在从脚本运行 MySQL 的每个命令中添加用户名和密码

python - 计算字段自己的类和不同的类? - Openerp

python - ValueError : Dimensions must be equal, 但对于 '{{node mean_squared_error/SquaredDifference}} = SquaredDifference[T=DT_FLOAT] 是 68 和 10

python - 正则表达式意外结束

bash - 正确转义 sed 字符串

python - Pandas 出现在很多专栏上

linux - 为什么 "find"命令在 shell 脚本中不起作用

bash - 访问 bash 函数中的命令行参数?

c - 在 C 中,如何复制字符串数组的一部分以用作 execve 中的 argv?