登录
首页 >  Golang >  Go问答

如何在golang中使用os/exec处理用户输入?我无法停止输入阶段

来源:stackoverflow

时间:2024-04-08 19:36:37 421浏览 收藏

今天golang学习网给大家带来了《如何在golang中使用os/exec处理用户输入?我无法停止输入阶段》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~

问题内容

首先,我将命令构建为 exec.exe:

package main
import "fmt"
func main() {
    var input string
    fmt.println("input a value")
    fmt.scanln(&input)
    fmt.println(input)

    fmt.println("input another value")
    fmt.scanln(&input)
    fmt.println(input)
}

然后我想使用 os/exec 包来运行它:

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.command("g:\\go_workspace\\gopath\\src\\pjx\\modules\\exec\\exec")

    stdin, e := cmd.stdinpipe()
    if e != nil {
        panic(e)
    }
    stdout, e := cmd.stdoutpipe()
    if e != nil {
        panic(e)
    }
    if e:=cmd.start();e!=nil {
        panic(e)
    }
    stdin.write([]byte("hello"))
    var buf = make([]byte, 512)
    n, e := stdout.read(buf)
    if e != nil {
        panic(e)
    }
    fmt.println(string(buf[:n]))

    if e := cmd.wait(); e != nil {
        panic(e)
    }
}

最后我运行它,结果将在用户输入阶段暂停,例如:

(如果图片未加载,它们会在输入阶段暂停)

please input a value:

1
12
232

我是否以错误的方式使用cmd管道?


解决方案


程序正在阻塞,因为子进程中的 fmt.scanln 正在等待 \n 字符(eof 也会导致它返回)。为了避免阻塞,您的输入应该包含两个 \n,或者您可以只调用“stdin.close()”来指示输入流已完成。

由于子进程多次调用 scanlnprintln,因此对 stdout.read 的单次调用可能无法读取子进程的完整输出。您可以继续调用 stdout.read() 直到返回 io.eof 错误,或者仅使用 ioutil.readall

func main() {
    cmd := exec.command("g:\\go_workspace\\gopath\\src\\pjx\\modules\\exec\\exec")

    stdin, e := cmd.stdinpipe()
    if e != nil {
        panic(e)
    }

    stdout, e := cmd.stdoutpipe()
    if e != nil {
        panic(e)
    }
    if e := cmd.start(); e != nil {
        panic(e)
    }
    _, e = stdin.write([]byte("hello\nworld\n"))
    if e != nil {
        panic(e)
    }
    stdin.close()

    out, _ := ioutil.readall(stdout)
    // or you can use a loop
    //for {
    //  var buf = make([]byte, 512)
    //  n, e := stdout.read(buf)
    //  if e == io.eof {
    //      break
    //  }
    //  if e != nil {
    //      panic(e)
    //  }
    //  fmt.println(string(buf[:n]))
    //}

    fmt.println(string(out))

    if e := cmd.wait(); e != nil {
        panic(e)
    }
}

您需要监听正在执行的程序的输出。当您写“hello”时,程序可能仍在写入其标准输出。试试这个:

go func() {
        in := bufio.NewReader(stdout)
        for {
            s, err := in.ReadString('\n')
            if err != nil {
                return
            }
            fmt.Println(s)
        }
    }()

    if e := cmd.Start(); e != nil {
        panic(e)
    }

    stdin.Write([]byte("hello\n"))
    stdin.Write([]byte("hello2\n"))
    if e := cmd.Wait(); e != nil {
        panic(e)
    }

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何在golang中使用os/exec处理用户输入?我无法停止输入阶段》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>