python 3运行bash命令获取语法错误

时间:2018-10-10 11:50:25

标签: python python-3.x bash

我正在尝试从python3脚本运行bash命令,但出现错误。 命令:

#!/usr/bin/python3

import os

os.system('curl -k --header "Authorization: 3NKNRNNUrFQtu4YsER6" --header "Accept: application/json" --header "Content-Type: application/json" https://192.168.1.1/alerts/index/limit:1/page:1/sort:id/direction:desc.json |  jq -r ''{"request": {"alert": {"alert": .[0].alert, "new": "test"}}}'' > 1.json')

错误响应:

jq: error: syntax error, unexpected $end (Unix shell quoting issues?) at 
<top-level>, line 1:
{request:        
(23) Failed writing body

1 个答案:

答案 0 :(得分:1)

无需使用curljq; Python具有处理HTTP请求和JSON数据的库。 (requests是第三方库; json是标准库的一部分。)

import json
import requests

with open("1.json", "w") as fh:
    response = requests.get("https://192.168.1.1/alerts/index/limit:1/page:1/sort:id/direction:desc.json",
                            headers={"Accept": "application/json",
                                     "Content-Type": "application/json",
                                     "Authorization": "3NKNRNNUrFQtu4YsER6"
                                    }
                           ).json()
    json.dump(fh, {'request': {'alert': {'alert': response[0]['alert'], 'new': 'test'}}})

如果您坚持使用curljq,请使用subprocess模块而不是os.system

p = subprocess.Popen(["curl", "-k",
                      "--header", "Authorization: 3NKNRNNUrFQtu4YsER6",
                      "--header", "Accept: application/json",
                      "--header", "Content-Type: application/json",
                      "https://192.168.1.1/alerts/index/limit:1/page:1/sort:id/direction:desc.json"
                     ], stdout=subprocess.PIPE)

with open("1.json", "w") as fh:
    subprocess.call(["jq", "-r", '{request: {alert: {alert: .[0].alert, new: "test"}}}'], 
                    stdin=p.stdout,
                    stdout=fh)