You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

获取磁盘空闲百分比并添加至磁盘列表的技术求助

Hey there! Let's tackle this problem step by step—getting disk capacity and free space values is totally doable depending on which OS you're working with, and once you have those, calculating the free space percentage is straightforward. Here's how to approach it across common platforms, plus a cross-platform script example:

1. Windows: Use PowerShell for Precision

PowerShell gives you direct access to disk metrics via Windows Management Instrumentation (WMI). Run this command to get all local disks with their total size, free space, and calculated free percentage:

Get-CimInstance Win32_LogicalDisk | Where-Object {$_.DriveType -eq 3} | 
Select-Object DeviceID, 
              @{Name='TotalSizeGB'; Expression={[math]::Round($_.Size / 1GB, 2)}},
              @{Name='FreeSpaceGB'; Expression={[math]::Round($_.FreeSpace / 1GB, 2)}},
              @{Name='FreePercent'; Expression={[math]::Round(($_.FreeSpace / $_.Size)*100, 2)}}
  • DriveType -eq 3 filters for local hard disks (skips removable media like USB drives)
  • Size is the total disk capacity in bytes, FreeSpace is the available free space in bytes
  • The calculated fields convert bytes to gigabytes and compute the percentage for readability
2. Linux/macOS: Terminal Commands

For Unix-like systems, the df command is your go-to tool.

Linux

To get raw numeric values (in kilobytes) for a specific disk (e.g., /dev/sda1):

df -P /dev/sda1 | tail -1 | awk '{print "Total: " $2 " KB, Free: " $4 " KB"}'

To directly calculate the free percentage:

df -P /dev/sda1 | tail -1 | awk '{printf "Free Space Percentage: %.2f%%\n", ($4/$2)*100}'

macOS

Similar to Linux, but you can also use diskutil for more detailed info:

diskutil info /Volumes/YourDriveName | grep -E '(Total Size|Free Space)'

Then use the numeric values (note: macOS might report in bytes or other units—adjust your calculation accordingly).

3. Cross-Platform Python Script

If you want a programmatic solution that works on all OSes, use the psutil library (a popular system monitoring tool):

First install it:

pip install psutil

Then run this script:

import psutil

def calculate_disk_free_percentages():
    # Get all disk partitions
    partitions = psutil.disk_partitions(all=False)  # all=False skips system-specific dummy partitions
    
    for partition in partitions:
        # Skip partitions without a file system (e.g., CD-ROMs)
        if not partition.fstype:
            continue
        
        try:
            # Get disk usage stats
            disk_usage = psutil.disk_usage(partition.mountpoint)
            total_gb = disk_usage.total / (1024 ** 3)  # Convert bytes to GB
            free_gb = disk_usage.free / (1024 ** 3)
            free_percent = (disk_usage.free / disk_usage.total) * 100
            
            print(f"=== Disk: {partition.device} ===")
            print(f"Total Capacity: {total_gb:.2f} GB")
            print(f"Free Space: {free_gb:.2f} GB")
            print(f"Free Space Percentage: {free_percent:.2f}%\n")
        except PermissionError:
            print(f"⚠️  No permission to access {partition.device}\n")
        except OSError:
            print(f"⚠️  Could not access {partition.device}\n")

if __name__ == "__main__":
    calculate_disk_free_percentages()

This script will loop through all accessible disks, compute the percentage, and handle common errors like permission issues.

Quick Troubleshooting Tips

  • Unit Consistency: Always make sure you're using the same unit (bytes, KB, GB) for both total capacity and free space when calculating the percentage—mixing units will give wrong results!
  • Permissions: Some system disks or encrypted volumes might require elevated privileges (run PowerShell/Terminal as admin/root) to read their stats.
  • Filtering: If you're getting extra partitions (like virtual disks or network mounts), add filters to exclude them (e.g., Where-Object in PowerShell, checking partition.device in Python).

内容的提问来源于stack exchange,提问作者Norrin Rad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:18:35