The chatGPT robot helped me write a program about monitoring the network traffic of the process, and there was always an error

35 views
Skip to first unread message

王尔德(成都市高新区世纪星耀科技工作室)

unread,
Feb 19, 2023, 4:42:30 AM2/19/23
to psutil
No matter how you ask chatGPT to change the error, but this error has always been there, does anyone know why?
QQ截图20230219053001.png
所有代码:
import psutil
import time

# 设置监控的进程名称
process_name = "aDrive.exe"

# 上一次检测到进程运行的时间
last_running_time = 0

# 上一次记录的上传下载总流量
last_up_total = 0
last_down_total = 0

# 定义获取进程网络接口的函数
def get_process_nic(process_name):
    for c in psutil.net_connections(kind='inet4'):
        try:
            if c.pid and psutil.Process(c.pid).name() == process_name:
                return psutil.Process(c.pid).io_counters()
        except psutil.NoSuchProcess:
            pass
    return None

# 定义格式化输出函数
def format_output(up_total, down_total, up_speed, down_speed):
    print(f"\rUP_Total: {up_total / 1024:.2f} KB; Down_Total: {down_total / 1024:.2f} KB; UP: {up_speed / 1024:.2f} KB/s; DOWN: {down_speed / 1024:.2f} KB/s", end="")

# 主循环
while True:
    # 获取当前时间
    current_time = time.time()

    # 检查进程是否正在运行
    running = False
    for process in psutil.process_iter():
        if process.name() == process_name:
            running = True
            break

    if running:
        # 如果进程正在运行,获取当前上传下载流量
        process_nic = get_process_nic(process_name)
        if process_nic is None:
            continue  # 如果无法获取进程的网络接口,则跳过

        current_up_total = process_nic.bytes_sent
        current_down_total = process_nic.bytes_recv
        # 如果是第一次检测到进程运行,记录当前的上传下载总流量
        if last_running_time == 0:
            start_up_total = current_up_total
            start_down_total = current_down_total

        # 计算上传下载速度
        up_speed = (current_up_total - last_up_total) / (current_time - last_running_time)
        down_speed = (current_down_total - last_down_total) / (current_time - last_running_time)

        # 更新上一次记录的上传下载总流量和检测到进程运行的时间
        last_up_total = current_up_total
        last_down_total = current_down_total
        last_running_time = current_time

        # 格式化输出
        format_output(current_up_total - start_up_total, current_down_total - start_down_total, up_speed, down_speed)

    else:
        # 如果进程没有运行,显示“wait api” + 时间戳
        print(f"\rwait api {int(current_time)}", end="")

        # 清空记录的上传下载总流量和检测到进程运行的时间
        last_running_time = 0
        last_up_total = 0
        last_down_total = 0

    # 等待2秒钟
    time.sleep(2)




Reply all
Reply to author
Forward
0 new messages