增加 Golang 执行外部程序.
Signed-off-by: rick.chan <chenyang@autoai.com>
This commit is contained in:
parent
b814fa19a3
commit
d6e0a6453d
|
@ -0,0 +1,30 @@
|
||||||
|
# Golang 执行外部程序
|
||||||
|
|
||||||
|
需要使用 os/exec 包。
|
||||||
|
|
||||||
|
示例如下:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func MakeCmd(name string, arg ...string) *exec.Cmd {
|
||||||
|
cmd := exec.Command(name, arg...)
|
||||||
|
cmd.Env = append(cmd.Env, "USER=root")
|
||||||
|
cmd.Env = append(cmd.Env, "HOME=/home/root")
|
||||||
|
cmd.Env = append(cmd.Env, "SHELL=/bin/sh")
|
||||||
|
cmd.Env = append(cmd.Env, "LOGNAME=root")
|
||||||
|
cmd.Env = append(cmd.Env, "PATH=/usr/local/bin:/usr/bin:/bin:/xt/scripts:/usr/local/sbin:/usr/sbin:/sbin:/xt/scripts")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
cmd := MakeCmd("ls", "-l", "/")
|
||||||
|
output, _ := cmd.Output()
|
||||||
|
fmt.Println(output)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
exec.Cmd 有 Start、Wait、Run、Output 等方法,其中
|
||||||
|
|
||||||
|
* Start:非阻塞执行;
|
||||||
|
* Wait:阻塞进程,等待命令执行结束, 经常与 Star 配合使用;
|
||||||
|
* Run:阻塞进程,直到命令执行结束,相当于 Start+Wait 的组合;
|
||||||
|
* Output:阻塞进程,直到命令执行结束,比 Run 方法多返回程序的 stdout。
|
Loading…
Reference in New Issue