以下只展示cpu的獲取搪哪,其他的類似內(nèi)存網(wǎng)絡(luò)io常侦,同理可以通過解析
import docker
import json
# 地址 也接受tcp的
base_url="unix://var/run/docker.sock"
def get_cpu_pre(docker_stats):
cpuDelta = docker_stats.get("cpu_stats").get("cpu_usage").get("total_usage") - docker_stats.get("precpu_stats").get(
"cpu_usage").get("total_usage")
print(cpuDelta)
systemDelta = docker_stats.get("cpu_stats").get("system_cpu_usage") - docker_stats.get("precpu_stats").get(
"system_cpu_usage")
print(systemDelta)
result = cpuDelta / systemDelta *len(docker_stats.get("cpu_stats").get("cpu_usage").get("percpu_usage"))* 100
print("cpu % =",result)
def bx():
client=docker.from_env(base_url=base_url)
result=client.containers.list()
print(result)
def get_client():
client=docker.DockerClient(base_url=base_url)
result=client.containers.list()
# print(result)
# for item in result:
# # print(dir(item))
# print(item.stats(stream=False,decode=True))
# 容器id 測試時自己寫的
result=client.containers.get("9109ff7aa11b")
for i in result.stats(decode=True):
# print(i)
print(type(i))
try:
get_cpu_pre(i)
except:
print("失敗一次")
pass
# print(i)
# get_cpu_pre(json.loads(i))
get_client()