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”。
发布于 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
这个样品在窗户上进行了测试。
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)
}
}https://stackoverflow.com/questions/54317432
复制相似问题