douquanhui5735 2018-10-22 07:43
浏览 107

在Go中执行二进制文件时获取输入

I am using below code snippet :-

command:= exec.Command("./"+order)

out, err := command.Output()
if err != nil {
   log.Println(err)
}

fmt.Println(string(out))

here, "order" is the variable with name of binary in the current directory. When I run this code it doesn't ask for input and run through the binary till the end of it printing output statement. How do I get input for my binary executable while running it?

I have tried using python in go also but to no effect.

  • 写回答

1条回答 默认 最新

  • doufu4333 2018-10-22 08:35
    关注

    This code asks for your name and then passes it to ./hello binary which reads first argument and outputs the first argument.

    package main
    
    import (
        "bufio"
        "fmt"
        "log"
        "os"
        "os/exec"
    )
    
    func main() {
        reader := bufio.NewReader(os.Stdin)
        fmt.Print("What's your name: ")
        name, _ := reader.ReadString('
    ')
        command := exec.Command("./hello", name)
    
        out, err := command.Output()
        if err != nil {
            log.Println(err)
        }
        fmt.Println(string(out))
    }
    

    hello.go:

    package main
    
    import (
        "fmt"
        "os"
    )
    
    func main() {
        fmt.Println(fmt.Sprintf("hello %s", os.Args[1]))
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程