簡體   English   中英

直接從子進程輸出解析 json 輸出

[英]Parse json output directly from a subprocess output

我無法弄清楚如何直接從子進程輸出解析 json 輸出。

代碼片段

cmd = ['./mmdbinspect', '--db', '/usr/local/var/GeoIP/GeoLite2-City.mmdb', ip]
        # result returns json
        result = subprocess.run(cmd, stdout=subprocess.PIPE)
        result = json.loads(result)
        # parse & print
        print(result[0]['Lookup'])
        print(result[0]['Records'][0]['Record']['country']['iso_code'])
        print(result[0]['Records'][0]['Record']['country']['names']['en'])

如果我將結果寫入文件,然后執行 json.load 它會按預期工作,但我想合並並跳過該步驟。

回溯錯誤

TypeError: the JSON object must be str, bytes or bytearray, not CompletedProcess

從文檔返回的實例將具有屬性 args, returncode, stdout 和 stderr 要使用它,請從標准輸出加載 json 字符串。

result = json.loads(result.stdout)

這應該有效

    result = json.load(result.read())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM