Python查询磁盘信息,磁盘剩余可用空间

参考:https://www.iteye.com/blog/halfish-1706810

环境:

Python: 3.6

系统:server 2016

设计模块包:wmi   #pip install wmi

import wmi

def get_disk_info():
    """
    获取物理磁盘信息。
    """
    tmplist = []
    c = wmi.WMI()
    for physical_disk in c.Win32_DiskDrive():
        tmpdict = {}
        tmpdict["Caption"] = physical_disk.Caption
        tmpdict["Size"] = int(physical_disk.Size) / 1024 / 1024 / 1024
        tmplist.append(tmpdict)
    return tmplist


def get_fs_info():
    """
    获取文件系统信息
    包含分区的大小、已用量、可用量、使用率、挂载点信息
    """
    tmplist = []
    c = wmi.WMI()
    for physical_disk in c.Win32_DiskDrive():
        for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition"):
            for logical_disk in partition.associators("Win32_LogicalDiskToPartition"):
                tmpdict = {}
                tmpdict["Caption"] = logical_disk.Caption
                tmpdict["DiskTotal"] = int(logical_disk.Size) / 1024 / 1024 / 1024
                tmpdict["UseSpace"] = (int(logical_disk.Size) - int(logical_disk.FreeSpace)) / 1024 / 1024 / 1024
                tmpdict["FreeSpace"] = int(logical_disk.FreeSpace) / 1024 / 1024 / 1024
                tmpdict["Percent"] = int(
                    100.0 * (int(logical_disk.Size) - int(logical_disk.FreeSpace)) / int(logical_disk.Size))
                tmplist.append(tmpdict)
    return tmplist


if __name__ == "__main__":
    disk = get_disk_info()
    print(disk)
    #获取磁盘信息
    fs = get_fs_info()
    for f in fs:
        disk_name = f['Caption'] #磁盘名
        DiskTotal = f['DiskTotal'] #磁盘大小 单位G
        disk_UseSpace = f['UseSpace'] #已用磁盘大小 单位G
        disk_FreeSpace = f['FreeSpace'] #剩余可用磁盘大小 单位G
        print('磁盘名:{}  磁盘大小:{}G   已用空间:{}G  剩余可用空间:{}G !!'.format(disk_name,round(DiskTotal,2),round(disk_UseSpace,2),round(disk_FreeSpace,2)))
  
上一篇:【pathlib】轻松处理Windows和Linux的路径操作(路径表示的斜杠与反斜杠之争)


下一篇:知道了这些,您可以使用Python超过99%的文件操作