python - 在 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 ','
解决方案
这无需使用 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()
推荐阅读
- typescript - 如何在打字稿中定义函数调用签名的实现和构造签名
- image-processing - 这个 ImageMagick 脚本如何创建 3D 模型?
- python - Sage / Python:来自非空生成器的空元组
- load-testing - Locust 负载测试:如何在所有其他 API 中为一个特定 API 分配单个用户
- javascript - How to insert React component to HTML template?
- java - Android:用左/右滑动切换活动
- javascript - 单击关闭画布菜单中的另一个链接后,如何使汉堡包按钮返回原始状态
- angular - 在 ng mat-table 上调用渲染行错误时,无法读取未定义的属性
- html - 我想在一个圆圈内放一个圆圈,但问题是我的第一层圆圈是从顶部和左侧裁剪的
- php - PHP 不会从 for 循环在数据库中插入重复项