回答

收藏

在 Go 中执行 shell 命令

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

我希望在 Go 中执行一个 shell 命令,并在我的程序中输出结果作为字符串。我看到了Rosetta Code版本:
* v- Q" f5 d0 g" L
    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()
    - V4 S3 I4 i* G  ?
但这并没有捕获实际的标准输出或错误实际标准输出或错误 - 那些仍然打印到常规标准输出/标准错误的人。我看到了 Pipe 作为 out 或 err 可以在其他地方提供帮助,但没有例子解释如何这样做。你有什么想法吗?
, ]5 o. q2 F$ Z% r' a; D, n7 K                                                                5 K6 J% c% D- v2 v4 H& l
    解决方案:                                                               
# j* h/ f+ h8 @7 v; m& ?8 Z  ]                                                                包“exec稍有变化。以下代码对我有用。
  V  W! ?7 k; b! y: p
    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))}
    , r* J8 \1 n( x4 P  K- k5 L
希望这有帮助!
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则