Python cURL命令via操作系统()使用JSON PAR失败

2024-09-27 00:20:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我通过一个Python'cURL命令向一个Python-orig发送一个命令。 我正在OpenWRT上运行脚本,因此我无法安装requests或{}库,因为内存问题,另外,subprocess之类的库无法编译。所以我使用os.system()来执行cURL命令。以下是脚本代码:

import sys
import os
from urllib import urlencode
sys.path.insert(0, '/usr/lib/python2.7/bridge')
from bridgeclient import BridgeClient as bridgeclient

value = bridgeclient()


header="(curl 10.130.1.228:1026/v1/updateContext -s -S --header 'Content-Type: application/json' \
--header 'Accept: application/json'     -d @- | python -mjson.tool) <<EOF"

json_string="""
{
    "contextElements": [
        {
            "type": "Room",
            "isPattern": "false",
            "id": "R1",
            "attributes": [
                {
                    "name": "temperature",
                    "type": "float",
                    "value": "firstValue"
                },
                {
                    "name": "pressure",
                    "type": "float",
                    "value": "secondValue"
                }
            ]    
        }
    ],
    "updateAction": "UPDATE"
}
EOF""" 


while(True):

    all=value.getall()
    sentValue1=""
    sentValue2=""
    if all['Tmp'] is None:
        sentValue1=all['Tmp']
    else:
        sentValue1="NoValue"
    if all['Prs'] is None:
        sentValue2=all['Prs']
    else:
        sentValue2="NoValue"
    json_string=json_string.replace("firstValue",sentValue1)
    json_string=json_string.replace("secondValue",sentValue2)   
    os.system(header+json_string)

如果我复制并粘贴给os.system()的命令,就像它在终端窗口中一样,一切都会顺利进行,我的猎户座实例也会得到更新。但如果我通过上述脚本运行相同的命令,则会从服务器得到以下响应:

^{pr2}$

我想是一些格式问题,我已经尽了一切努力让它工作,但没有运气。在

更新:

我在contextBroker日志中发现以下消息:

from=10.130.1.1 | srv=pending | subsrv=<defalut> | comp=Orion | 
op=AlarmMenager.cpp[405]:badInput | msg=Releasing alarm BadInput 
10.130.1.1: JSON Parse Error: unspecified file(1):expected end of input

还有这个:

from=10.130.1.1 | srv=pending | subsrv=<defalut> | comp=Orion | 
op=AlarmMenager.cpp[405]:badInput | msg=Releasing alarm BadInput 
10.130.1.1: JSON Parse Error: unspecified file(1):expected object

两个都重复了我提出的每个cURL请求。在

更新2:

我设法使subprocess.call()工作,但它给出了完全相同的响应。在


Tags: fromimport命令脚本jsonstringvalueos
1条回答
网友
1楼 · 发布于 2024-09-27 00:20:13

多亏了@Shan Desai我才解决了这个问题。在

我使用json.dump文件用了pycurl。在

工作代码如下:

import sys
import os
import subprocess
import json
from urllib import urlencode
from collections import OrderedDict
import StringIO
import pycurl

sys.path.insert(0, '/usr/lib/python2.7/bridge')
from bridgeclient import BridgeClient as bridgeclient


fout = StringIO.StringIO()
value = bridgeclient()
apiurl = '10.130.1.228:1026/v1/updateContext'
headers=['Content-Type: application/json','Accept: application/json']

firstValue = 'firstValue'

secondValue = 'secondValue'

d_attributes = [{'name': 'temperature', 'type': 'float', 'value': firstValue},
            {'name': 'pressure', 'type': 'float', 'value': secondValue}]

d_context = [{'type': 'Room', 'isPattern': 'false', 'id': 'R1', 'attributes': d_attributes}]

d_json = {'contextElements': d_context, 'updateAction': 'UPDATE'}

c = pycurl.Curl()

while (True):

        all = value.getall()

        if all['Tmp'] is not None:
            firstValue = all['Tmp']
        else:
            firstValue = "NoValue"
        if all['Prs'] is not None:
            secondValue = all['Prs']
        else:
            secondValue = "NoValue"
        d_json["contextElements"][0]["attributes"][0]["value"]=firstValue
        d_json['contextElements'][0]['attributes'][1]['value']=secondValue
        c.setopt(pycurl.WRITEFUNCTION, fout.write)
        c.setopt(pycurl.URL, apiurl)
        c.setopt(pycurl.HTTPHEADER, headers)
        c.setopt(pycurl.POST, 1)
    s_json=json.dumps(d_json)
        c.setopt(pycurl.POSTFIELDS,s_json)
        c.perform()
        c.getinfo(pycurl.RESPONSE_CODE)
        print(json.dumps(OrderedDict(d_json)))
        print(fout.getvalue())

相关问题 更多 >

    热门问题