python3实现磁盘空间监控

yipeiwu_com5年前Python基础

本文实例为大家分享了python3磁盘空间监控的具体代码,供大家参考,具体内容如下

软硬件环境

python3
apscheduler

前言

在做频繁操作磁盘的python项目时,经常会碰到磁盘空间不足的情况,这个时候,工程应该要有自己的处理模块,当磁盘利用率到达某个点时,发出警告并停止程序的运行。本文就利用Python3中的apscheduler模块来处理这样的问题。

代码实践

import os
import sys
import signal
import logging

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger

# 开启磁盘空间检测
sched = BackgroundScheduler()

# 间隔5分钟开启一个检查
intervalTrigger = IntervalTrigger(minutes=5)

# 给检查任务设个id,方便任务的取消
sched.add_job(spaceMonitorJob, trigger=intervalTrigger, id='id_space_monitor')
sched.start()

# 禁止apscheduler相关信息屏幕输出
logging.getLogger('apscheduler.executors.default').propagate = False

方法spaceMonitorJob代码如下

def spaceMonitorJob():
 '''
 当磁盘(切片存储的目录)利用率超过90%,程序退出
 :return:
 '''

 try:
  st = os.statvfs('/')
  total = st.f_blocks * st.f_frsize
  used = (st.f_blocks - st.f_bfree) * st.f_frsize
 except FileNotFoundError:
  print('check webroot space error.')
  logger.error('check webroot space error.')

  # 移除任务,病关闭sched任务
  sched.remove_job(job_id='id_space_monitor')
  sched.shutdown(wait=False)
  sys.exit(-3)

 if used / total > 0.9:
  print('No enough space.')
  logger.debug('No enough space.')
  sched.remove_job(job_id='id_space_monitor')
  sched.shutdown(wait=False)

  # 杀掉进程
  os.killpg(os.getpgid(os.getpid()), signal.SIGKILL)

  # 退出
  exit(-3)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python实现全盘扫描搜索功能的方法

由用户指定需要扫描的盘符或目录,输入需要查找的文件或者文件夹名称(不包含中文名称) 代码: # encoding=utf-8 import os.path import stat #...

python中关于时间和日期函数的常用计算总结(time和datatime)

1.获取当前时间的两种方法: 复制代码 代码如下:import datetime,timenow = time.strftime("%Y-%m-%d %H:%M:%S")print no...

python实现NB-IoT模块远程控制

本来想尝试下如果不使用运营商网络应用平台情况下,只是在服务商服务器上是否可以实现对终端完全控制,如果这样可行,那么物联网应用服务端更有灵活性。实际情况下,很难实现和运营商网络对等的处理,...

python模拟事件触发机制详解

本文实例为大家分享了python模拟事件触发机制的具体代码,供大家参考,具体内容如下 EventManager.py # -*- encoding: UTF-8 -*- # 系统模...

python实现简单温度转换的方法

本文实例讲述了python实现简单温度转换的方法。分享给大家供大家参考。具体分析如下: 这是一段简单的python代码,用户转换不同单位的温度,适合初学者参考 复制代码 代码如下:def...