Json解析Python子进程 [英] Json parsing Python subprocess

查看:72
本文介绍了Json解析Python子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

inputDomain = subprocess.Popen("cat /etc/localdomains", shell=True,  stdout=subprocess.PIPE)
domains = inputDomain.stdout.read().splitlines()

for domain in domains:
   cmd = "whmapi1 domainuserdata domain " + domain
   output = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
   jsonS = json.dumps(output.communicate())
   print json.loads(jsonS)['data']

这里有错误

root @ server [〜/testP]#python copie.py 追溯(最近一次通话): 在第18行中输入文件"copie.py" 打印json.loads(jsonS)['data'] TypeError:列表索引必须是整数,而不是str

root@server [~/testP]# python copie.py Traceback (most recent call last): File "copie.py", line 18, in print json.loads(jsonS)['data'] TypeError: list indices must be integers, not str

这是我需要解析的json的示例:

and this is an example of the json i need to parse:

{ 
   "data":{ 
      "userdata":{ 
      "phpopenbasedirprotect":1,
      "options":"ExecCGI Includes",
     "ip":"10.0.0.1",
     "hascgi":"1",
     "group":"user",
     "usecanonicalname":"Off",
     "scriptalias":[ 
        { 
           "url":"/cgi-bin/",
           "path":"/home/user/public_html/cgi-bin"
        },
        { 
           "url":"/cgi-bin/",
           "path":"/home/user/public_html/cgi-bin/"
        }
     ],
     "user":"user",
     "ifmodulemodsuphpc":{ 
        "group":"user"
     },
     "owner":"root",
     "documentroot":"/home/user/public_html",
     "userdirprotect":"",
     "serveralias":"parkeddomain.com www.parkeddomain.com www.example.com",
     "port":"80",
     "homedir":"/home/user",
     "ifmoduleconcurrentphpc":{ 

     },
     "customlog":[ 
        { 
           "target":"/usr/local/apache/domlogs/example.com",
           "format":"combined"
        },
        { 
           "target":"/usr/local/apache/domlogs/example.com-bytes_log",
           "format":"\"%{%s}t %I .\\n%{%s}t %O .\""
        }
     ],
     "servername":"example.com",
     "serveradmin":"webmaster@example.com"
  }
}

所以我需要用户和域,但是python总是回答我需要一个int.感谢您的帮助.

So i need the user and the domaine, but python always answer that i need a int. Thanks for the help guys.

推荐答案

由于您的进程返回了json字符串,因此无需dump即可再次加载它.

since your process returns a json string, there's no need to dump it to load it again.

# stdout, stderr
jsonS,_ = output.communicate()

现在您有了一个字符串,可以使用json

now you have a string, that you can load using json

d = json.loads(jsonS)

现在d['data']会产生您想要的信息

now d['data'] yields the info you want

放在一边:正如我所说:

Aside: as I said:

inputDomain = subprocess.Popen("cat /etc/localdomains", shell=True,  stdout=subprocess.PIPE)
domains = inputDomain.stdout.read().splitlines()

可以用本机python代替:

could be replaced by native python:

with open("/etc/localdomains") as f: domains = f.read.splitlines()

这篇关于Json解析Python子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆