这个问题已经在这里有一个答案:
我不能完全肯定JQ如何在这里工作与子所以有误会,但我试图使用命令行(jq > file.json
)子与JQ上得到extact格式。这是我有,但以下产生一个空文件。
os.makedirs(os.path.dirname(filePath))
open(filePath, 'a').close()
call(["bw", "list", "--session", session_key, \
"collections", "|", "jq", ".", ">", filePath])
我也曾尝试
with open(filePath, "w+") as output:
call(["bw", "list", "--session", session_key, \
"collections", "|", "jq", "."], stdout=output)
但是,这只是产生一个字符串,而不是JQ的实际格式。有我的方式来获得在命令行到使用python文件中的标准输出JQ?
无壳,你需要两个子进程。
os.makedirs(os.path.dirname(filePath))
dst = open(filePath, 'a')
p0 = Popen(["bw", "list", "--session", session_key, "collections"],
stdout=PIPE, check=True)
p1 = Popen(["jq", "."], stdout=dst, stdin=p0.stdout, check=True)
p1.communicate()
dst.close()
这是几乎从字面上documentation.有在一定程度上简化了这一点,虽然这可以说是笨重的标准库pipes
模块解除;因此,也有一些第三方替换。
在另一方面,也许这就是那些你可以保卫shell=True
情况之一。
os.makedirs(os.path.dirname(filePath))
dst = open(filePath, 'a')
subprocess.run("""
bw list --session '{}' collections |
jq .""".format(session_key),
stdout=dst, shell=True, check=True)
dst.close()
在第三个方面,如果你真的想一个shell脚本,你为什么要编写Python?