获取磁盘空闲百分比并添加至磁盘列表的技术求助
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:
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 3filters for local hard disks (skips removable media like USB drives)Sizeis the total disk capacity in bytes,FreeSpaceis the available free space in bytes- The calculated fields convert bytes to gigabytes and compute the percentage for readability
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).
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-Objectin PowerShell, checkingpartition.devicein Python).
内容的提问来源于stack exchange,提问作者Norrin Rad

