亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang exec.Command - 對話框

Golang exec.Command - 對話框

Go
qq_笑_17 2023-06-01 18:03:11
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 就會給我結果。謝謝,您的代碼是 [some number]如何在運行后填充“1”并使用 GoLang 獲取輸出?在我的示例中,運行 soft.exe 后它會立即完成“請選擇代碼:1、2、3、4”的工作。
查看完整描述

1 回答

?
阿晨1998

TA貢獻2037條經驗 獲得超6個贊

您需要將 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)

    }


}


查看完整回答
反對 回復 2023-06-01
  • 1 回答
  • 0 關注
  • 196 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號