Equivalent of python's utils.execute() in golang

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

Equivalent of python's utils.execute() in golang

问题

我是一个新手,正在学习 Golang,并且目前在使用 Python 的 utils.execute() 函数处理二进制文件。我需要将这段代码转换成 Golang,那么在 Golang 中有相应的等价函数吗?

英文:

I am newbie to golang and am currently working with binaries in python with utils.execute(). I have to convert the code to golang, what's the equivalent to it in go?

答案1

得分: 4

你可以查看golang的exec.Command,例如在os/exec/example_test.go中:

func ExampleCommand() {
    cmd := exec.Command("tr", "a-z", "A-Z")
    cmd.Stdin = strings.NewReader("some input")
    var out bytes.Buffer
    cmd.Stdout = &out
    err := cmd.Run()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("in all caps: %q\n", out.String())
}

第一个参数是你想要执行的命令,其余的是参数。

func Command(name string, arg ...string) *Cmd

在同一个os/exec/example_test.go中,你会找到关于如何读取输出、启动命令甚至进行管道操作的示例。

英文:

You can check golang exec.Command, as in os/exec/example_test.go

func ExampleCommand() {
	cmd := exec.Command("tr", "a-z", "A-Z")
	cmd.Stdin = strings.NewReader("some input")
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("in all caps: %q\n", out.String())
}

First parameter is the command you want to execute, the rest are the parameters.

func Command(name string, arg ...string) *Cmd

In that same os/exec/example_test.go, you will find examples on how to read the output, start a command or even do a pipe.

huangapple
  • 本文由 发表于 2015年9月28日 16:23:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/32818593.html
匿名

发表评论

匿名网友

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

确定