回答

收藏

在 Go 中执行 shell 命令

技术问答 技术问答 268 人阅读 | 0 人回复 | 2023-09-12

我希望在 Go 中执行一个 shell 命令,并在我的程序中输出结果作为字符串。我看到了Rosetta Code版本:
+ x8 t- P9 n0 y) r7 }8 \
    package mainimport "fmt"import "exec"func main() {  cmd,err := exec.Run("/bin/ls",[]string{"/bin/ls"},[]string{},"",exec.DevNull,exec.PassThrough,exec.PassThrough)  if (err != nil)    fmt.Println(err)    return  }  cmd.Close()! k7 _7 U& F8 V; k% S# n( d
但这并没有捕获实际的标准输出或错误实际标准输出或错误 - 那些仍然打印到常规标准输出/标准错误的人。我看到了 Pipe 作为 out 或 err 可以在其他地方提供帮助,但没有例子解释如何这样做。你有什么想法吗?
* y( E; m5 |4 h$ f( N                                                                + b) q) N  D9 Z& q
    解决方案:                                                               
1 \( ]% ~9 K0 d7 m2 V  `. F                                                                包“exec稍有变化。以下代码对我有用。3 t& c- x  m! o( v8 d/ Y" C) l0 a
    package mainimport  "fmt"    "os/exec")func main()      app := "echo"    arg0 := "-e"    arg1 := "Hello world"    arg2 := "\n\tfrom"    arg3 := "golang"    cmd := exec.Command(app,arg0,arg1,arg2,arg3)    stdout,err := cmd.Output()    if err != nil              fmt.Println(err.Error()return     Print the output    fmt.Println(string(stdout))}
    & {, |/ Y; x1 X! O* J- x5 H
希望这有帮助!
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则