python3实现磁盘空间监控

yipeiwu_com6年前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设计】。

相关文章

Python3.5装饰器典型案例分析

本文实例讲述了Python3.5装饰器。分享给大家供大家参考,具体如下: #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:...

Python赋值语句后逗号的作用分析

本文实例讲述了Python赋值语句后逗号的作用。分享给大家供大家参考。具体分析如下: IDLE 2.6.2 >>> a = 1 >>> b =...

python 中的list和array的不同之处及转换问题

python中的list是python的内置数据类型,list中的数据类不必相同的,而array的中的类型必须全部相同。在list中的数据类型保存的是数据的存放的地址,简单的说就是指针,...

python在linux中输出带颜色的文字的方法

python在linux中输出带颜色的文字的方法

在开发项目过程中,为了方便调试代码,经常会向stdout中输出一些日志,默认的这些日志就直接显示在了终端中。而一般的应用服务器,第三方库,甚至服务器的一些通告也会在终端中显示,这样就搅乱...

Python 学习教程之networkx

networkx是Python的一个包,用于构建和操作复杂的图结构,提供分析图的算法。图是由顶点、边和可选的属性构成的数据结构,顶点表示数据,边是由两个顶点唯一确定的,表示两个顶点之间的...