如何从输出中提取所需数据并将其保存到变量
这是我的计划:
import commands
cmd = curl -v -k -H "Content-Type: application/json" -X GET -u hitman:hitman <https://test.com:8181/v1/config/sipregistrar
result = commands.getoutput(cmd)
print result
现在运行程序:
python test25.py
输出
About to connect() to test.com port 8181 (#0)
Trying test.com... % Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0connected
Connected to 50.50.50.201 (50.50.50.201) port 8181 (#0)
successfully set certificate verify locations:
HTTP/1.1 200 OK
Date: Tue, 05 Jun 2012 18:27:11 GMT
Server: Jetty(6.1.22)
Content-Type: application/json;charset=UTF-8
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Set-Cookie: JSESSIONID=12buplms5odzt;Path=/config
Transfer-Encoding: chunked
Closing connection #0
SSLv3, TLS alert, Client hello (1):
} [data not shown]
{"sip_domains":{"prefix":[{"name":""}],"domain":[{"name":"k200.com"},{"name":"zinga.com"},{"name":"rambo.com"}]},"sip_security":{"level":2},"sip_trusted_hosts":{"host":[]},"sip_proxy_mode":{"handle_requests":1}}
从这个输出中,我需要的参数:
{ “sip_domains”:{ “前缀”:[{ “名称”: “”}], “结构域”:[{ “名称”: “k200.com”},{ “名称”:“zinga.com “},{” 名称 “:” rambo.com “}]},” sip_security “:{” 电平 “:2},” sip_trusted_hosts “:{” 主机 “:[]},” sip_proxy_mode “:{” handle_requests” :1}}
如何提取上述内容并将其保存到变量?
答案 0 :(得分:2)
如果您只需要一串这些参数并且所有输出始终遵循该模式,并且[数据未显示]中没有任何内容破坏了这一点,您可以尝试...
params = results[results.find('{"'):]
从{“sip_domains”开始获取部分结果 如果你最终得到另一个{“之前,那么这将会破裂。
答案 1 :(得分:0)
我已将其清除,删除eval
,并使用JSON转换结果,以确保安全:
import json
from pprint import pprint
output = '''[data extract]Set-Cookie: JSESSIONID=12buplms5odzt;Path=/config
Transfer-Encoding: chunked
Closing connection #0
SSLv3, TLS alert, Client hello (1):
} [data not shown]
{"sip_domains":{"prefix":[{"name":""}],"domain":[{"name":"k200.com"},{"name":"zinga.com"},{"name":"rambo.com"}]},"sip_security":{"level":2},"sip_trusted_hosts":{"host":[]},"sip_proxy_mode":{"handle_requests":1}}'''
output = json.loads( output.split("\n")[-1] )
pprint( output )
变量output
现在包含此词典:
{'sip_domains': {'domain': [{'name': 'k200.com'},
{'name': 'zinga.com'},
{'name': 'rambo.com'}],
'prefix': [{'name': ''}]},
'sip_proxy_mode': {'handle_requests': 1},
'sip_security': {'level': 2},
'sip_trusted_hosts': {'host': []}}
这只是一个替代方案,@ jcfollower有一个来自我的+1来提供简洁有效的解决方案。