SoFunction
Updated on 2024-11-19

python3 implementation of disk space monitoring

In this article, the example for you to share the specific code of python3 disk space monitoring, for your reference, the details are as follows

software and hardware environment

python3
apscheduler

preamble

When doing python projects that frequently manipulate disks, it is common to run into a situation where there is insufficient disk space. At this time, the project should have its own processing module that warns and stops the program when disk utilization reaches a certain point. In this article, we will use the apscheduler module in Python 3 to handle such a problem.

code practice

import os
import sys
import signal
import logging

from  import BackgroundScheduler
from  import IntervalTrigger

# Enable disk space detection
sched = BackgroundScheduler()

# Open a check at 5-minute intervals
intervalTrigger = IntervalTrigger(minutes=5)

# Set an id for the checking task to make it easier to cancel the task.
sched.add_job(spaceMonitorJob, trigger=intervalTrigger, id='id_space_monitor')
()

# Disable apscheduler related information screen outputs
('').propagate = False

The method spaceMonitorJob code is as follows

def spaceMonitorJob():
 '''
 When disk (the directory where the slices are stored) utilization exceeds 90%, the program exits
 :return.
 '''

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

  # Remove tasks, sick off sched tasks
  sched.remove_job(job_id='id_space_monitor')
  (wait=False)
  (-3)

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

  # Kill the process
  ((()), )

  # Exit
  exit(-3)

This is the whole content of this article.