python - 在 Python3 中执行链式 bash 命令,包括多个管道和 grep

标签 python python-3.x shell 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 ','

最佳答案

无需使用 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()

关于python - 在 Python3 中执行链式 bash 命令,包括多个管道和 grep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55177315/

相关文章:

linux - 通过读取命令在 POSIX 兼容的 shell 脚本中解析 cal 输出

python - 如何在 Python 中指定(什么)的方法返回类型列表?

python - 嵌套循环以确定两个类(class)的学生(两个)

python - pycrypto AES CBC

python - 无法使用 python Pymysql 更新 SQL 数据库

Python:在二维数组中查找所有可能的唯一双索引组合

linux - bash+dose for 循环有限制吗?

regex - 如何使用文件动态指定模式并根据该目录中的模式获取文件?

python - python中的这个ssl错误是什么意思?

python : Plot heatmap for large matrix