如何在Python中使用stdout的内容?

时间:2019-04-30 11:46:50

标签: python dictionary subprocess popen

我正在尝试运行终端命令(Linux)并使用输出。

list = subprocess.Popen(
    'bgpq3 -j -A AS-FACEBOOK -m 24 -l Facebook',
    shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = list_prefixes.communicate()
print(stdout)

输出为:

 { "Facebook": [
    { "prefix": "5.45.32.0\/22", "exact": true },
    { "prefix": "185.160.58.0\/23", "exact": false, "greater-equal": 24, "less-equal": 24 },
    { "prefix": "5.57.248.0\/21", "exact": true },
    { "prefix": "5.206.208.0\/20", "exact": true },
    { "prefix": "185.54.94.0\/23", "exact": false, "greater-equal": 24, "less-equal": 24 },
    { "prefix": "31.193.104.0\/21", "exact": true },
    { "prefix": "213.233.192.0\/18", "exact": true },
    { "prefix": "217.26.96.0\/20", "exact": true }
] }

然后我尝试使用以下代码打印每一行:

for item in stdout['Facebook']:
    if item['exact'] == 'true':
        print ("{}, {}".format(item['prefix'].split('\/')[0], item['exact']))
    else:
        print ("{}, {}".format(item['prefix'].split('\/')[0], item['greater-equal']))

但是我得到这个错误:

TypeError: string indices must be integers

问题是标准输出的类类型。当我使用type(stdout)时,结果是:

<class 'str'>

有什么办法可以解决这个问题?

1 个答案:

答案 0 :(得分:0)

使用json模块将字符串转换为dict对象。

例如:

import json
stdout = """{ "Facebook": [
    { "prefix": "5.45.32.0\/22", "exact": true },
    { "prefix": "185.160.58.0\/23", "exact": false, "greater-equal": 24, "less-equal": 24 },
    { "prefix": "5.57.248.0\/21", "exact": true },
    { "prefix": "5.206.208.0\/20", "exact": true },
    { "prefix": "185.54.94.0\/23", "exact": false, "greater-equal": 24, "less-equal": 24 },
    { "prefix": "31.193.104.0\/21", "exact": true },
    { "prefix": "213.233.192.0\/18", "exact": true },
    { "prefix": "217.26.96.0\/20", "exact": true }
] }"""

stdout = json.loads(stdout)
for item in stdout['Facebook']:
    if item['exact'] == 'true':
        print ("{}, {}".format(item['prefix'].split('\/')[0], item['exact']))
    else:
        print ("{}, {}".format(item['prefix'].split('\/')[0], item.get('greater-equal')))

输出:

5.45.32.0/22, None
185.160.58.0/23, 24
5.57.248.0/21, None
5.206.208.0/20, None
185.54.94.0/23, 24
31.193.104.0/21, None
213.233.192.0/18, None
217.26.96.0/20, None

注意:某些元素没有键'greater-equal',请使用item.get('greater-equal')