简体   繁体   English

如何在 Go 中列出块设备?

[英]How do I list block devices in Go?

I want to get the data shown by lsblk command in Linux 64-bit systems.我想在Linux 64位系统中获取lsblk命令显示的数据。 Obviously I can call lsblk and parse the output.显然我可以调用lsblk并解析输出。 My question is if there is a better way to do this in Go?我的问题是在 Go 中是否有更好的方法来做到这一点?

Thanks.谢谢。

Since lsblk is already available and already does what you want (gathering information from the system and synthesizing that information into the form you want), I'd think using it would be the best way.由于lsblk已经可用并且已经完成了您想要的操作(从系统收集信息并将该信息合成为您想要的形式),我认为使用它是最好的方法。

The lsblk source code is here: https://github.com/karelzak/util-linux/blob/master/misc-utils/lsblk.c . lsblk源代码在这里: https : //github.com/karelzak/util-linux/blob/master/misc-utils/lsblk.c At first glance, personally, this seems nontrivial to replicate in Go, and probably worth the hassle of parsing output and testing for breakage when the util-linux package is updated.乍一看,就个人而言,这在 Go 中复制似乎很重要,并且可能值得在 util-linux 包更新时解析输出和测试损坏的麻烦。

That's ultimately a decision that has to be made for your individual project based on your particular criteria.这最终是必须根据您的特定标准为您的个人项目做出的决定。

I just needed the names of the top-level devices and ended up simply listing the contents of /sys/block , which was convenient because it requires neither running a command, nor parsing output.我只需要顶级设备的名称,最后只列出/sys/block的内容,这很方便,因为它不需要运行命令,也不需要解析输出。

func GetDevices() []string {
    dir, err := ioutil.ReadDir("/sys/block")
    if err != nil {
        panic(err)
    }

    files := make([]string, 0)

    for _, f := range dir {
        if strings.HasPrefix(f.Name(), "loop") {
            continue
        }
        files = append(files, f.Name())
    }

    return files
}

Neither a very robust or portable solution, but worked for what I needed.既不是一个非常强大或便携的解决方案,也不是我需要的。

You could also conceive parsing the contents of /proc/diskstats or /proc/partitions .您还可以设想解析/proc/diskstats/proc/partitions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM