Linux环境Python语言 计算磁盘分区容量、使用率,文件夹大小、文件大小总结,读取ini配置文件

1、计算所有分区以及各个分区使用率

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 脚本作用:获取系统所有分区和分区已使用空间占总空间的百分比。
# 注意事项:该脚本只能在Linux系统下执行,适用于Python 2。
import os
import re
# 获取系统所有分区
def getAllPartitionOfSystem():
result = []
f = os.popen('mount')
text = f.readlines()
f.close()
for line in text:
  if re.search(r'\bext\d', line):
  result.append(line.split()[2])
  return result


# 获取分区已使用空间占总空间的百分比
def getUsedOfPartition(path):
  sv = os.statvfs(path)
  free = (sv.f_bavail * sv.f_frsize)
  total = (sv.f_blocks * sv.f_frsize)
  used = (sv.f_blocks - sv.f_bfree) * sv.f_frsize
  return (float(used) / total) * 100

2、os计算某个分区容量

#os获取某个分区总容量和
def getTotalOfPartition(path):
  sv = os.statvfs(path)
  total = (sv.f_blocks * sv.f_frsize)
  return total

3、递归计算一个文件夹内所有文件容量之和

import os
def file_size(path):
   total_size = 0
   path=os.path.abspath(path)
   file_list=os.listdir(path)
   for i in file_list:
       i_path = os.path.join(path, i)
       if os.path.isfile(i_path):
           total_size += os.path.getsize(i_path)
       else:
           try:
              total_size += file_size(i_path)
           except RecursionError:
               print('递归操作时超出最大界限')
   return total_size

4、获取文件大小,两种方法

#获取文件大小 方法1
import subprocess
def getFileSize(self, file):
    linuxCommand = "ls -l " + file + " | awk '{print $5}'"
    output = self.executeShell(linuxCommand)
    return output

# 执行linux命令获取返回结果与返回码
def executeShell(self, command, universal_newlines=True):
    p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,
                         universal_newlines=universal_newlines)
    output = p.stdout.read()
    p.wait()
    p.stdout.close()
    return str(output)
    
    
  
#获取文件大小 方法2
import os
def file_size(path):
   total_size = os.path.getsize(path)
   return total_size

5、读取ini配置文件

参考博客

from configparser import ConfigParser
 
cfg = ConfigParser()
cfg.read('config.ini')
 
print(cfg.sections())
print(cfg.get('debug', 'log_errors'))
 
print(cfg.getint('server', 'port'))
 
 
#result:
['debug', 'server']
true
8080

 

你可能感兴趣的:(Linux知识)