繁体   English   中英

Golang执行命令-对话框

[英]Golang exec.Command - Dialog

去程序运行带有参数的外部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 

该样品在窗户上测试。

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)
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM