TypeError: string indices must be integers, not str
这个问题应该怎么修改 萌新求教
#!/usr/bin/python
# -*- coding:utf-8 -*-
import re
import sys
import os
import json
def discover():
d = {}
d['data'] = []
with os.popen("docker ps -a --format {{.ID}}") as pipe: # 找到容器ID返回给pipe
for line in pipe:
c_id = line.replace("\n", "")
info = {}
info['{#CONTAINER_ID}'] = c_id
cmd_CPU = 'docker stats %s --no-stream --format "table{{.CPUPerc}}"' % c_id
cmd_MEM = 'docker stats %s --no-stream --format "table{{.MemUsage}}"' % c_id
try:
f1 = os.popen(cmd_CPU).read()
f2 = os.popen(cmd_MEM).read()
if len(f1) == 0:
continue
info['{#CPU}'] = f1.split('\n')[1]
if len(f2) == 0:
continue
a = f2.split('\n')[1]
print(a)
MEM = a.split('/')
s = MEM[0].strip()
print("内存:"+s)
l = re.search('([-+]?[0-9]*\.?[0-9]+)([a-zA-Z]+)', s)
num = float(l.group(1))
d = l.group(2)
print("num:" + str(num))
print("单位:" + d)
if d == 'GiB':
a = str(num * 1024)
result = a + 'MiB'
print("情况1")
info['{#MEM}'] = result
elif d == 'KiB':
a = str(num / 1024)
result = a + 'MiB'
print("情况2")
info['{#MEM}'] = result
else:
print("其他情况")
info['{#MEM}'] = s
except:
print("没有取到内存")
info['{#CPU}'] = ""
info['{#MEM}'] = ""
d['data'].append(info)
print (json.dumps(d))
def status(name, action):
if action == "ping":
cmd = 'docker inspect --format="{{.State.Running}}" %s' % name
result = os.popen(cmd).read().replace("\n", "")
if result == "true":
print (1)
else:
print (0)
else:
cmd = 'docker stats %s --no-stream --format "{{.%s}}"' % (name,action)
result = os.popen(cmd).read().replace("\n", "")
if "%" in result:
print (float(result.replace("%", "")))
else:
print (result)
if __name__ == '__main__':
try:
name, action = sys.argv[1], sys.argv[2]
status(name, action)
except IndexError:
discover()
d['data'] = []
这里d是数组,不是字典,没有data
是因为
d = l.group(2)
把上面定义的
d = {}
覆盖了
所以变量命名尽量有意义,不能重名