【问题标题】:How to run jq command in python? [duplicate]如何在python中运行jq命令? [复制]
【发布时间】:2023-04-04 22:42:01
【问题描述】:

我正在关注 bigquery 地理空间指南,我的 json 文件通过 jq 命令进行了更改。特别是这个:

cat ~/file1.json | jq -c '.features[]' > converted.json

我在 python 中运行上面的等价物时遇到了困难。我正在使用 subprocess 模块,但它不起作用。

cmd = ['cat', './sample.json', '|', 'c', '.features[]']

print(subprocess.check_output(cmd))

我得到的输出是这样的:

cat: |: No such file or directory
cat: -c: No such file or directory
cat: .features[]: No such file or directory
Traceback (most recent call last):
  File "/Users/rtom/kml2geo/main.py", line 12, in <module>
    result = subprocess.check_output(cmd)
  File "/Users/rtom/opt/anaconda3/lib/python3.8/subprocess.py", line 415, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/Users/rtom/opt/anaconda3/lib/python3.8/subprocess.py", line 516, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['cat', './sample.json', '|', '-c', '.features[]']' returned non-zero exit status 1.
(base) rtom@Ryans-MacBook-Pro kml2geo %

这里有什么帮助吗?

【问题讨论】:

  • 这里完全没有使用cat的理由,如果你不使用它会容易得多。
  • (当您希望输出直接到文件时,为什么要subprocess.check_output()?)
  • 顺便说一句,在 Python 中,与 subprocess.Popen-family 函数的 stdin=open('filename', 'r') 参数等效的 shell 是使用 &lt;filename;可以在开头也可以在结尾,所以&lt;filename jq ...jq ... &lt;filename 是等价的。

标签: python jq


【解决方案1】:

您不需要cat(您永远从单个文件读取时不需要cat;其目的是连接多个输入源一起)。把它拿出来,一切都会变得容易得多:

subprocess.run(['jq', '-c', '.features[]'],
               stdin=open(os.path.expanduser('~/file1.json'), 'r'),
               stdout=open('converted.json', 'w'))

您还可以通过在 jq 的命令行上传递输入文件名来避免 stdin= 参数(在将 ~ 替换为完全限定的路径之后,因为没有 shell 可以为您执行此操作):

subprocess.run(['jq', '-c', '.features[]',
                os.path.expanduser('~/file1.json')
               ], stdout=open('converted.json', 'w'))

如果您想将输出读取到变量而不是将其写入文件,请取出 stdout= 参数并添加 capture_output=True

【讨论】:

  • 做到了!非常感谢。朋友新年快乐。
最近更新 更多