【云原生】python获取docker stats 容器cpu使用率

以下只展示cpu的获取,其他的类似内存网络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()

你可能感兴趣的:(云原生,云原生,python,docker)