服务器之家

服务器之家 > 正文

python3实现磁盘空间监控

时间:2021-03-07 00:19     来源/作者:djstavaV

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

软硬件环境

python3
apscheduler

前言

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

代码实践

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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代码如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/djstavaV/article/details/78283891

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部