gpt4 book ai didi

Golang exec.Command - 对话框

转载 作者:IT王子 更新时间:2023-10-29 02:35:44 25 4
gpt4 key购买 nike

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

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

fmt.Printf("%s", out)

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

Please choose code: 1, 2, 3, 4

通常在 shell 窗口中,我只需键入“1”并按 Enter,soft.exe 就会给我结果。

Thank you, your code is [some number]

如何在运行后填充“1”并使用 Go 语言获取输出?在我的示例中,运行 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 exec.Command - 对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54317432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com