How do I list block devices in Go?

huangapple go评论70阅读模式
英文:

How do I list block devices in Go?

问题

我想获取在Linux 64位系统中通过lsblk命令显示的数据。显然,我可以调用lsblk并解析输出。我的问题是是否有更好的方法在Go语言中实现这个功能?

谢谢。

英文:

I want to get the data shown by lsblk command in Linux 64-bit systems. Obviously I can call lsblk and parse the output. My question is if there is a better way to do this in Go?

Thanks.

答案1

得分: 1

由于lsblk已经可用并且已经可以实现你想要的功能(从系统中收集信息并将该信息合成为你想要的形式),我认为使用它可能是最好的方法。

lsblk的源代码在这里:https://github.com/karelzak/util-linux/blob/master/misc-utils/lsblk.c。乍一看,个人认为在Go中复制这个功能似乎并不容易,并且可能值得解析输出并在util-linux软件包更新时测试是否会出现问题。

这最终是一个基于你个人项目的决策,根据你的特定标准来做出。

英文:

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.

The lsblk source code is here: <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.

That's ultimately a decision that has to be made for your individual project based on your particular criteria.

答案2

得分: 0

我只需要顶级设备的名称,所以我简单地列出了/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
}

这不是一个非常健壮或可移植的解决方案,但对我所需的功能来说是有效的。

你也可以考虑解析/proc/diskstats/proc/partitions的内容。

英文:

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.

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

	files := make([]string, 0)

	for _, f := range dir {
		if strings.HasPrefix(f.Name(), &quot;loop&quot;) {
			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.

huangapple
  • 本文由 发表于 2017年3月30日 11:45:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/43108180.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定