问题
用python监控进程占用服务器托管网硬件资源时,手动执行正常运行,定时任务执行出错
在centos的定时任务中,用python的os模块执行top命令时终端没有输出
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()
修复
- top -n 1不能在 crontab中使用,要加一个参数top -b -n 1
- 用 /bin/top 代替 top 命令
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
源代码
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(Bx1b[mx1b[39;49mx1b(Bx1b[mx1b[39;49mx1b[K", "")
sys_out = sys_ou服务器托管网t.replace("x1b(Bx1b[mx1b[39;49mx1b[K", "")
sys_out = sys_out.replace("x1b(Bx1b[mx1b[39;49m", "")
sys_out = sys_out.replace("x1b(Bx1b[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
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
一、项目介绍 呼吸灯是一种常见的LED灯光效果,它可以模拟人类呼吸的变化,使灯光看起来更加柔和和自然。51单片机是一种广泛使用的微控制器,具有体积小、功耗低、成本低等优点,非常适合用于控制LED呼吸灯。本项目的呼吸灯将使用PWM(脉冲宽度调制)技术控制LED亮…