首页 > 解决方案 > 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

标签: pythonpython-3.xbash

解决方案


没有必要使用curland 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'}}})

如果您坚持使用curland 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)

推荐阅读