dsyk33753 2015-11-28 06:42
浏览 32
已采纳

将命令输出默认为stdout吗?

I started learning and playing around with Go to see what it is like to make some more complex console/cli type tools instead of using shells or Python. I want to execute commands and display the output. I figured out how to print the output like this:

out, err := exec.Command("pwd").Output()
print(string(out))

Is there a way to execute the commands and have it default to stdout like a shell script, or do I need to make a helper function for this?

Update: After getting IntelliJ and the Go plugin, I poked around in the Go source and agree there is currently no way to do with without a helper method.

It is not possible to reuse a Cmd object as per this comment in the exec.go source code:

// A Cmd cannot be reused after calling its Run, Output or CombinedOutput
// methods.

I did incorporate the stdout option into my own helper, including other options like shell integration. I will try turn that into open source if I can make it useful. An interesting first day of Go.

  • 写回答

2条回答 默认 最新

  • douyan2680 2015-11-28 11:08
    关注

    The solution

    Actually, it is pretty easy. You can set the stdout of the command to os.Stdout and Bob's your uncle:

    package main
    
    import (
      "os"
      "os/exec"
    )
    
    func main() {
    
      cmd := exec.Command("pwd")
    
      cmd.Stdout = os.Stdout
    
      err := cmd.Run()
    
      if err != nil {
        panic(err)
      }
    }
    

    What's happening here?

    By default, the output of a command is stored in a bytes.Buffer if cmd.Stdout is not set to another io.Writer. The call of cmd.Output() then runs the command and saves the output to said buffer.

    Since os.Stdout implements io.Writer interface, we simply set cmd.Stdout to be os.Stdout. Now when .Run() is called, the output of the command gets written to the io.Writer defined in cmd.Stdout, which happens to be os.Stdout and the output gets written in the shell.

    EDIT: As per comment, if all commands should write to os.Stdout, there of course is no way to prevent some helper. I'd do it like this:

    package main 
    
    import (
     "os"
     "os/exec"
    )
    
    func CmdToStdout( c string ) (err error){
      cmd := exec.Command(c)
      cmd.Stdout = os.Stdout
      err = cmd.Run()
      return
    }
    
    func main() {
    
      err := CmdToStdout("pwd")
      if err != nil {
        panic(err)
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值