go os/exec执行外部程序

Go提供的os/exec包可以执行外部程序,比如调用系统命令等。

最简单的代码,调用pwd命令显示程序当前所在目录:

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    pwdCmd := exec.Command("pwd")
    pwdOutput, _ := pwdCmd.Output()
    fmt.Println(string(pwdOutput))
}

执行后会输出当前程序所在的目录。

如果要执行复杂参数的命令,可以这样:

exec.Command("bash", "-c", "ls -la")

或者这样:

exec.Command("ls", "-la")

或者这样:

pwdCmd := exec.Command("ls", "-l", "-a")

原文地址:https://www.cnblogs.com/baiyuxiong/p/4545019.html