go os/exec执行外部程序

Go提供的os/exec包能够执行外部程序,好比调用系统命令等。bash

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

package main

import (
    "fmt"
    "os/exec"
)

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

 

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

 

若是要执行复杂参数的命令,能够这样:blog

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

或者这样:class

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

或者这样:程序

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

相关文章
相关标签/搜索