【修复】centos定时任务python top不能输出

问题

用python监控进程占用硬件资源时,手动执行正常运行,定时任务执行出错

在centos的定时任务中,用python的os模块执行top命令时终端没有输出

python 复制代码
cmd = 'top -d 1 -n 1 -p {} | grep -E "PID|{}|%Cpu|buff/cache" '.format(process_id, process_id, )
sys_out = os.popen(cmd)
sys_out = sys_out.read()

修复

  1. top -n 1不能在 crontab中使用,要加一个参数top -b -n 1
  2. 用 /bin/top 代替 top 命令
python 复制代码
cmd = '/bin/top -b -d 1 -n 1 -p {} | grep -E "PID|{}|%Cpu|buff/cache" '.format(process_id, process_id, )

sys_out = os.popen(cmd)
sys_out = sys_out.read()  

引用

https://blog.51cto.com/zdz8207/3552214

源代码

python 复制代码
def record_process_occupy(process_id=0, process_log_file="", ):
    """
    记录一条这个进程的资源占用情况
    :param process_id: 进程的ID
    :param log_file: 保存top输出的文件
    :return: None
    """

    cmd = '/bin/top -b -d 1 -n 1 -p {} | grep -E "PID|{}|%Cpu|buff/cache" '.format(process_id, process_id, )

    sys_out = os.popen(cmd)
    print(cmd)
    sys_out = sys_out.read()
    sys_out = sys_out.replace("\x1b[7m", "")
    sys_out = sys_out.replace("\x1b(B\x1b[m\x1b[39;49m\x1b(B\x1b[m\x1b[39;49m\x1b[K", "")
    sys_out = sys_out.replace("\x1b(B\x1b[m\x1b[39;49m\x1b[K", "")
    sys_out = sys_out.replace("\x1b(B\x1b[m\x1b[39;49m", "")
    sys_out = sys_out.replace("\x1b(B\x1b[m", '')
    sys_out = sys_out.replace("\x1b[1m", "")
    sys_out = sys_out.split('\n')

    assert len(sys_out) >= 4
    # print(sys_out)
    first_line = "time,"
    first_line += "us,sy,ni,id,wa,hi,si,st,"
    first_line += "total, free, used, buff/cache,"
    first_line += "PID,USER,PR,NI,VIRT,RES,SHR,S,%CPU,%MEM,TIME+,COMMAND"
    line = ",".join([
        datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        ",".join([x for x in sys_out[0].replace(",", " ").split(" ") if x.replace(".", "").isdigit()]),  # cpu
        ",".join([x for x in sys_out[1].replace(",", " ").split(" ") if x.replace(".", "").isdigit()]),  # mem
        ",".join([x for x in sys_out[3].split(" ") if x]),  # 进程
    ])
    # print(first_line)
    # print(line)
    print("process_log_file", process_log_file)
    if not process_log_file:
        process_log_file = os.path.join(BACKUP_PATH, "process_{}_resource_occupy.csv".format(process_id))
        print()
    print("process_log_file:", process_log_file)
    is_new_file = not os.path.exists(process_log_file)
    with open(process_log_file, 'a') as f:
        if is_new_file:
            f.write(first_line + "\n")
        f.write(line + "\n")

    return True
相关推荐
被遗忘的旋律.17 小时前
Linux驱动开发笔记(二十四)——(下)IIO + MPU6050驱动
linux·驱动开发·笔记
optimistic_chen18 小时前
【Redis系列】Redis缓存
linux·数据库·redis·mysql·缓存·火山引擎
BlockChain88818 小时前
Spring框架终极入门指南(12000字深度解析)
java·后端·python·spring
czliutz18 小时前
Windows系统创建启动Flask虚拟环境
windows·python·flask
我想发发发18 小时前
.deb格式软件包安装方式(Ubuntu 22.04为例)
linux·运维·ubuntu
cyber_两只龙宝18 小时前
LVS-NAT模式实验配置以及详解
linux·运维·云原生·lvs
GIS萬事通18 小时前
基于arcgis制作深度学习标签并基于python自动化预处理样本
python·深度学习·arcgis·边缘计算
海涛高软18 小时前
vmware虚拟机 ubuntu20.4手动设置静态IP
linux·运维·服务器
布局呆星18 小时前
面向对象中的封装-继承-多态
开发语言·python
sxy_976118 小时前
AX86u官方固件温度监控(CPU,WIFI芯片)
python·docker·curl·nc·nas·温度·ax86u