你如何在 Go 中获得系统命令的输出? [英] How do you get the output of a system command in Go?

查看:21
本文介绍了你如何在 Go 中获得系统命令的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想在 go 程序中运行 'ls',并将结果存储在一个字符串中.似乎有一些命令可以在 exec 和 os 包中 fork 进程,但是它们需要 stdout 等的文件参数.有没有办法将输出作为字符串?

Let's say I want to run 'ls' in a go program, and store the results in a string. There seems to be a few commands to fork processes in the exec and os packages, but they require file arguments for stdout, etc. Is there a way to get the output as a string?

推荐答案

此答案已过时.请参阅下面的Fatih Arslan 的回答.

This answer is obsolete. Please see Fatih Arslan's answer below.

通过指定 exec.Run/golang.org/pkg/exec/#Constants" rel="nofollow noreferrer">Pipe 作为标准输出(如果需要,还可以使用标准输出).它将返回 cmd,其中在 Stdout(和 Stderr)字段中包含一个 os.File.然后你可以使用例如 ioutil.ReadAll 来阅读它.

Use exec.Run by specifying Pipe as the stdout (and stderr if you want). It will return cmd, which contains an os.File in the Stdout (and Stderr) fields. Then you can read it using for example ioutil.ReadAll.

示例:

package main

import (
    "exec";
    "io/ioutil";
)

func main() {
    if cmd, e := exec.Run("/bin/ls", nil, nil, exec.DevNull, exec.Pipe, exec.MergeWithStdout); e == nil {
        b, _ := ioutil.ReadAll(cmd.Stdout)
        println("output: " + string(b))
    }
}

这篇关于你如何在 Go 中获得系统命令的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆