登录
首页 >  Golang >  Go问答

Golang exec.命令 - 对话框

来源:stackoverflow

时间:2024-04-11 11:03:36 106浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《Golang exec.命令 - 对话框》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

go 程序使用参数运行外部 soft.exe:

cmd := exec.Command("soft.exe", "-text")
out, _ := cmd.CombinedOutput()

fmt.Printf("%s", out)

soft.exe文件有一些输出并等待输入值,例如:

请选择代码: 1, 2, 3, 4

按照通常的方式,在 shell 窗口中,我只需输入“1”并按 enter 键,soft.exe 就会给出结果。

谢谢,您的代码是[某个数字]

如何在运行后填充“1”并使用 golang 获取输出?在我的示例中,运行 soft.exe 后,它立即完成“请选择代码:1、2、3、4”。


解决方案


您需要将 os.stdin 重定向到 cmd.stdin,将 os.stdout 重定向到 cmd.stdout

参见 godoc:https://golang.org/pkg/os/exec/#Cmd

// stdin specifies the process's standard input.
   //
   // if stdin is nil, the process reads from the null device (os.devnull).
   //
   // if stdin is an *os.file, the process's standard input is connected
   // directly to that file.
   //
   // otherwise, during the execution of the command a separate
   // goroutine reads from stdin and delivers that data to the command
   // over a pipe. in this case, wait does not complete until the goroutine
   // stops copying, either because it has reached the end of stdin
   // (eof or a read error) or because writing to the pipe returned an error.
   stdin io.reader

此示例在 windows 上进行了测试。

package main

import (
    "fmt"
    "os"
    "os/exec"
)

func main() {
    cmd := exec.Command("yo")
    cmd.Stderr = os.Stderr
    cmd.Stdout = os.Stdout
    cmd.Stdin = os.Stdin
    if err := cmd.Run(); err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }

}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>