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

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

问题描述

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

解决方案

使用 exec.Run 通过指定管道作为标准输出(如果需要,还可以使用stderr)。它将返回cmd,其中包含Stdout(和Stderr)字段中的 os.File 。然后,您可以使用例如 ioutil.ReadAll 阅读它。



示例:

 包主

导入(
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))
}
}


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?

解决方案

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.

Example:

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天全站免登陆