我必须在包含多个 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/