首页 > 解决方案 > 在 Python3 中执行链式 bash 命令,包括多个管道和 grep

问题描述

我必须在包含多个 pip 和 grep 命令的 python 脚本中使用以下 bash 命令。

 grep name | cut -d':' -f2  | tr -d '"'| tr -d ','

我尝试使用 subprocess 模块做同样的事情,但没有成功。

谁能帮我在 Python3 脚本中运行上述命令?

我必须从文件中获取以下输出file.txt

 Tom
 Jack

file.txt 包含:

"name": "Tom",
"Age": 10

"name": "Jack",
"Age": 15

实际上我想知道如何使用 Python 运行下面的 bash 命令。

    cat file.txt | grep name | cut -d':' -f2 | tr -d '"'| tr -d ','

标签: pythonpython-3.xshellgrep

解决方案


这无需使用 subprocess 库或任何其他 os cmd 相关库,仅 Python 即可工作。

my_file = open("./file.txt")
line = True
while line:
    line = my_file.readline()
    line_array = line.split()
    try:
        if line_array[0] == '"name":':
            print(line_array[1].replace('"', '').replace(',', ''))
    except IndexError:
        pass
my_file.close()

推荐阅读