python - python 3运行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
解决方案
没有必要使用curl
and jq
; Python 具有处理 HTTP 请求和 JSON 数据的库。(requests
是第 3 方库;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
and 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)
推荐阅读
- mysql - 分组并查找金额差异sql同一张表
- javascript - 如何使用额外属性初始化 Javascript 对象
- python - 如何使用 URLLib.request 循环访问 URL 并下载图像?
- java - 如何将 JAR 文件添加到现有的 WAR 文件 web-inf/lib 文件夹中?
- c# - 查找 2 次之间的记录
- mysql - MySQL内部连接返回0行
- laravel - 如何使用 laravel sanitizer 保留新行 \n
- python - 在 python FastAPI 中解析数据时出错
- objective-c - .mm 文件的 Xcode 自动完成功能损坏
- google-apps-script - Google 表格:基于生日的操作