gpt4 book ai didi

go - 在 Go 中实时打印来自 exec 命令的标准输出

转载 作者:IT王子 更新时间:2023-10-29 01:41:10 27 4
gpt4 key购买 nike

<分区>

我有一个小的 Go 工具,基本上允许用户定义一个命令,然后使用 os/exec 运行。

我的问题是我想向用户显示命令的输出 (stdout/stderr)。

一个例子可能是这样的:用户定义一个命令,最后是sh test.shtest.sh 的内容:

echo "Start"
sleep 7s
echo "Done"

在我当前的实现中,用户只能在完整命令完成后才能看到输出。在上面的示例中,在 sleep 命令和第二个 echo 完成之前,用户不会看到输出 Start

我目前像这样检索命令的输出:

cmd := exec.Command(command, args...)
cmd.Dir = dir
// Attach to the standard out to read what the command might print
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Panic(err)
}
// Execute the command
if err := cmd.Start(); err != nil {
log.Panic(err)
}

buf := new(bytes.Buffer)
buf.ReadFrom(stdout)
log.Print(buf.String())

是否有可能以某种方式实时读取标准输出/标准错误。意思是一旦用户定义的命令创建并输出它就会被打印出来?

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