# -*- coding: utf-8 -*-
# @Author: wangkun
# @Time: 2023/7/19
import socket
import psutil


class GetCpuMen:
    @classmethod
    def get_ip_address(cls):
        try:
            # 创建一个 UDP 套接字
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            # 连接到一个外部 IP 地址
            sock.connect(("8.8.8.8", 80))
            # 获取本地 IP 地址
            local_ip = sock.getsockname()[0]
            return local_ip
        except socket.error:
            return "无法获取本机 IP 地址"

    @classmethod
    def get_pid(cls, script):
        # 遍历所有正在运行的进程
        for proc in psutil.process_iter():
            try:
                # 获取进程的命令行参数
                cmds = proc.cmdline()
                # 检查命令行参数是否包含爬虫脚本的名称或关键字
                for cmd in cmds:
                    if script in cmd:

                        print(f"cmd:{cmd}")
                        # 获取进程的PID
                        pid = proc.pid
                        return pid
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                pass

    @classmethod
    def get_cpu_mem(cls, script):
        import psutil

        # 获取当前进程的PID
        pid = cls.get_pid(script)
        print(f"pid:{pid}")
        # 获取CPU的使用情况
        cpu_percent = round(psutil.Process(pid).cpu_percent(), 2)

        # 获取内存的使用情况
        memory_percent = round(psutil.Process(pid).memory_percent(), 2)

        print(f"CPU使用率：{cpu_percent}")
        print(f"内存使用率：{memory_percent}")

    @classmethod
    def get_all_cpu_mem(cls):
        script_list = ["run_xg_search",
                       "run_xg_author",
                       "run_xng_author",
                       "run_xng_play",
                       "run_xng_hour",
                       "run_dy_author",
                       "run_dy_recommend",
                       "run_ks_recommend",
                       "run_ks_author",
                       "run_bszf_recommend",
                       "run_ssnnyfq_recommend",
                       "run_gzh_author",
                       "run_weixinzhishu_score",
                       "get_cpu_mem"]

        for scrip in script_list:
            print(f"scrip:{scrip}")
            cls.get_cpu_mem(scrip)
            print("\n")


if __name__ == "__main__":
    # GetCpuMen.get_cpu_mem("get_cpu_mem")
    # GetCpuMen.get_all_cpu_mem()
    print(GetCpuMen.get_ip_address())

    pass
