我正在尝试从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
答案 0 :(得分:1)
无需使用curl
和jq
; 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'}}})
如果您坚持使用curl
和jq
,请使用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)