首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Golang exec.Command -对话框

Golang exec.Command -对话框
EN

Stack Overflow用户
提问于 2019-01-22 22:33:33
回答 1查看 1.2K关注 0票数 0

Go程序运行带有参数的外部soft.exe:

代码语言:javascript
复制
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”。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-23 04:52:27

您需要将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

这个样品在窗户上进行了测试。

代码语言:javascript
复制
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)
    }

}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54317432

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档