基本上,我想要df -h
的输出,其中包括卷的可用空间和总大小。解决方案需要在Windows、Linux和Mac上运作,并用Go编写。
我查阅了Go文档中的os
和syscall
,但没有找到合适方法。在Windows上,即使是命令行工具也要么不方便(dir C:\
),要么需要特权(fsutil volume diskfree C:\
)。肯定还有其他方法可以做到这一点,只是我还没有发现...
更新:
根据nemo的答案和邀请,我提供了一个跨平台Go包来实现此功能。
基本上,我想要df -h
的输出,其中包括卷的可用空间和总大小。解决方案需要在Windows、Linux和Mac上运作,并用Go编写。
我查阅了Go文档中的os
和syscall
,但没有找到合适方法。在Windows上,即使是命令行工具也要么不方便(dir C:\
),要么需要特权(fsutil volume diskfree C:\
)。肯定还有其他方法可以做到这一点,只是我还没有发现...
更新:
根据nemo的答案和邀请,我提供了一个跨平台Go包来实现此功能。
sys.unix.Statfs
。import "golang.org/x/sys/unix"
import "os"
var stat unix.Statfs_t
wd, err := os.Getwd()
unix.Statfs(wd, &stat)
// Available blocks * size per block = available space in bytes
fmt.Println(stat.Bavail * uint64(stat.Bsize))
对于Windows系统,您也需要使用系统调用的方法。示例(源代码,已更新以匹配新的sys/windows
包):
import "golang.org/x/sys/windows"
var freeBytesAvailable uint64
var totalNumberOfBytes uint64
var totalNumberOfFreeBytes uint64
err := windows.GetDiskFreeSpaceEx(windows.StringToUTF16Ptr("C:"),
&freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes)
Bavail
是非特权用户可用的块数。Bfree
只是空闲块的总数。 - nemo这是我基于github.com/shirou/gopsutil库编写的df -h
命令版本。
package main
import (
"fmt"
human "github.com/dustin/go-humanize"
"github.com/shirou/gopsutil/disk"
)
func main() {
formatter := "%-14s %7s %7s %7s %4s %s\n"
fmt.Printf(formatter, "Filesystem", "Size", "Used", "Avail", "Use%", "Mounted on")
parts, _ := disk.Partitions(true)
for _, p := range parts {
device := p.Mountpoint
s, _ := disk.Usage(device)
if s.Total == 0 {
continue
}
percent := fmt.Sprintf("%2.f%%", s.UsedPercent)
fmt.Printf(formatter,
s.Fstype,
human.Bytes(s.Total),
human.Bytes(s.Used),
human.Bytes(s.Free),
percent,
p.Mountpoint,
)
}
}
Minio有一个跨平台、似乎保持良好的磁盘使用情况展示包(GoDoc):
import (
"github.com/minio/minio/pkg/disk"
humanize "github.com/dustin/go-humanize"
)
func printUsage(path string) error {
di, err := disk.GetInfo(path)
if err != nil {
return err
}
percentage := (float64(di.Total-di.Free)/float64(di.Total))*100
fmt.Printf("%s of %s disk space used (%0.2f%%)\n",
humanize.Bytes(di.Total-di.Free),
humanize.Bytes(di.Total),
percentage,
)
}
du -h
命令输出的数据,例如目录使用情况,而不是请求的 df -h
命令提供的磁盘使用情况。无论如何,这可能是使用 minio 包的一个很好的示例。 - Roman Shishkin