使用子发送“JQ”输出到文件[副本]

问题描述 投票:0回答:1

这个问题已经在这里有一个答案:

我不能完全肯定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?

python bash subprocess jq
1个回答
1
投票

无壳,你需要两个子进程。

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?

© www.soinside.com 2019 - 2024. All rights reserved.