命令需要换行才能完成
Command requires line break to finish
我正在尝试 运行 sqlite3 作为 Go 的进程。我想将 cmd.Stdin
与 bytes.Buffer
和 os.Stdin
结合起来。然而,当我在 stdin 字节缓冲区上写入 .quit
命令时,程序并没有直接退出,而是在等待来自 os.stdin
的换行符。当它收到来自 os.stdin
的换行符时,它就会退出。
我尝试调用 os.Stdin.Write([]byte("\n"))
但没有成功。如何在 .quit
命令后直接退出而不与 os.Stdin
进行任何交互?
func main() {
cmd := exec.Command("/usr/bin/sqlite3")
bufOut, bufErr, bufIn := &bytes.Buffer{}, &bytes.Buffer{}, &bytes.Buffer{}
cmd.Stdout = io.MultiWriter(bufOut, os.Stdout)
cmd.Stderr = io.MultiWriter(bufErr, os.Stderr)
cmd.Stdin = io.MultiReader(bufIn, os.Stdin)
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
// Execute .help command on sqlite3
if _, err := bufIn.Write([]byte(".help\n")); err != nil {
log.Fatal(err)
}
// Execute .quit command on sqlite3 (should exit here)
if _, err := bufIn.Write([]byte(".quit\n")); err != nil {
log.Fatal(err)
}
// Nevertheless, it requires a '\n' from os.Stdin before exiting
if err := cmd.Wait(); err != nil {
log.Fatal(err)
}
fmt.Println("out:", bufOut.String(), "err:", bufErr.String())
}
一个问题是您在此处使用 MultiReader:
cmd.Stdin = io.MultiReader(bufIn, os.Stdin)
来自docs for MultiReader(强调已添加):
MultiReader returns a Reader that's the logical concatenation of the provided input readers. They're read sequentially.
其他相关信息来自the documentation for Cmd.Stdin
。它表示如果 Stdin
不是 nil
或 *os.File
,则
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.
所以您的程序中发生的事情是这样的:cmd
的 Stdin
-reading goroutine 从 MultiReader bufIn
读取数据。首先,它会读取您写入 bufIn
的数据,但随后会尝试读取更多数据。 MultiReader 看到 bufIn
已耗尽并移动到 Read
它的下一个参数 os.Stdin
。当您调用 cmd.Wait
时,它会阻止等待 MultiReader 发送 EOF,但 MultiReader 本身会阻止尝试从 os.Stdin
读取。在您发送 EOF(例如,按 ctrl-D)或按 Enter 之前,什么都不会发生。 (我不太确定为什么按回车键有效,因为这通常不会导致 EOF,但如果我弄清楚细节,我会更新。)
另一个问题是竞争条件,因为 - goroutine 完全有可能在你写入之前从你的 bufIn
读取它,在这种情况下你随后写的任何东西至 bufIn
将被忽略。
与其使用缓冲区与进程通信,不如使用 cmd.StdoutPipe
和 cmd.StdinPipe
。但是,这并不能解决整个问题——您不能使用阻塞 IO 以交互方式与子进程通信,因为您最终会等待从等待您编写命令的进程中读取数据。可能你最好的选择是使用 goroutine 从命令中读取并使用 select 和超时来读取输出,直到它合理地确定没有更多的到来。
这是一种实现方式。它至少需要一些充实,错误处理,但它确实有效。 startScanner
设置 goroutine 以从命令的输出中读取行并将它们写入通道。 readLinesFromChannelWithTimeout
从给定的通道读取数据,直到给定的超时时间过去但没有数据。请注意,您 必须 在调用 cmd.Wait()
之前调用 cmdIn.Close()
否则后者将无限期挂起。
package main
import (
"bufio"
"fmt"
"io"
"log"
"os/exec"
"time"
)
func readLinesFromChannelWithTimeout(ch chan string, timeout time.Duration) []string {
var lines []string
for {
select {
case line, ok := <-ch:
if !ok {
return lines
} else {
lines = append(lines, line)
}
case <-time.After(timeout):
return lines
}
}
}
func startScanner(cmdOut io.ReadCloser) chan string {
ch := make(chan string)
go func(ch chan string) {
defer close(ch)
scanner := bufio.NewScanner(cmdOut)
for scanner.Scan() {
ch <- scanner.Text()
}
}(ch)
return ch
}
func main() {
cmd := exec.Command("/usr/bin/sqlite3")
cmdIn, _ := cmd.StdinPipe()
cmdOut, _ := cmd.StdoutPipe()
cmd.Start()
ch := startScanner(cmdOut)
var lines []string
io.WriteString(cmdIn, ".help\n")
lines = readLinesFromChannelWithTimeout(ch, time.Millisecond*100)
fmt.Printf("Got %d lines from .help\n", len(lines))
io.WriteString(cmdIn, ".show\n")
lines = readLinesFromChannelWithTimeout(ch, time.Millisecond*100)
fmt.Printf("Got %d lines from .show\n", len(lines))
cmdIn.Close() // vital! Wait() will hang otherwise
if err := cmd.Wait(); err != nil {
log.Fatal(err)
}
}
我正在尝试 运行 sqlite3 作为 Go 的进程。我想将 cmd.Stdin
与 bytes.Buffer
和 os.Stdin
结合起来。然而,当我在 stdin 字节缓冲区上写入 .quit
命令时,程序并没有直接退出,而是在等待来自 os.stdin
的换行符。当它收到来自 os.stdin
的换行符时,它就会退出。
我尝试调用 os.Stdin.Write([]byte("\n"))
但没有成功。如何在 .quit
命令后直接退出而不与 os.Stdin
进行任何交互?
func main() {
cmd := exec.Command("/usr/bin/sqlite3")
bufOut, bufErr, bufIn := &bytes.Buffer{}, &bytes.Buffer{}, &bytes.Buffer{}
cmd.Stdout = io.MultiWriter(bufOut, os.Stdout)
cmd.Stderr = io.MultiWriter(bufErr, os.Stderr)
cmd.Stdin = io.MultiReader(bufIn, os.Stdin)
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
// Execute .help command on sqlite3
if _, err := bufIn.Write([]byte(".help\n")); err != nil {
log.Fatal(err)
}
// Execute .quit command on sqlite3 (should exit here)
if _, err := bufIn.Write([]byte(".quit\n")); err != nil {
log.Fatal(err)
}
// Nevertheless, it requires a '\n' from os.Stdin before exiting
if err := cmd.Wait(); err != nil {
log.Fatal(err)
}
fmt.Println("out:", bufOut.String(), "err:", bufErr.String())
}
一个问题是您在此处使用 MultiReader:
cmd.Stdin = io.MultiReader(bufIn, os.Stdin)
来自docs for MultiReader(强调已添加):
MultiReader returns a Reader that's the logical concatenation of the provided input readers. They're read sequentially.
其他相关信息来自the documentation for Cmd.Stdin
。它表示如果 Stdin
不是 nil
或 *os.File
,则
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.
所以您的程序中发生的事情是这样的:cmd
的 Stdin
-reading goroutine 从 MultiReader bufIn
读取数据。首先,它会读取您写入 bufIn
的数据,但随后会尝试读取更多数据。 MultiReader 看到 bufIn
已耗尽并移动到 Read
它的下一个参数 os.Stdin
。当您调用 cmd.Wait
时,它会阻止等待 MultiReader 发送 EOF,但 MultiReader 本身会阻止尝试从 os.Stdin
读取。在您发送 EOF(例如,按 ctrl-D)或按 Enter 之前,什么都不会发生。 (我不太确定为什么按回车键有效,因为这通常不会导致 EOF,但如果我弄清楚细节,我会更新。)
另一个问题是竞争条件,因为 bufIn
读取它,在这种情况下你随后写的任何东西至 bufIn
将被忽略。
与其使用缓冲区与进程通信,不如使用 cmd.StdoutPipe
和 cmd.StdinPipe
。但是,这并不能解决整个问题——您不能使用阻塞 IO 以交互方式与子进程通信,因为您最终会等待从等待您编写命令的进程中读取数据。可能你最好的选择是使用 goroutine 从命令中读取并使用 select 和超时来读取输出,直到它合理地确定没有更多的到来。
这是一种实现方式。它至少需要一些充实,错误处理,但它确实有效。 startScanner
设置 goroutine 以从命令的输出中读取行并将它们写入通道。 readLinesFromChannelWithTimeout
从给定的通道读取数据,直到给定的超时时间过去但没有数据。请注意,您 必须 在调用 cmd.Wait()
之前调用 cmdIn.Close()
否则后者将无限期挂起。
package main
import (
"bufio"
"fmt"
"io"
"log"
"os/exec"
"time"
)
func readLinesFromChannelWithTimeout(ch chan string, timeout time.Duration) []string {
var lines []string
for {
select {
case line, ok := <-ch:
if !ok {
return lines
} else {
lines = append(lines, line)
}
case <-time.After(timeout):
return lines
}
}
}
func startScanner(cmdOut io.ReadCloser) chan string {
ch := make(chan string)
go func(ch chan string) {
defer close(ch)
scanner := bufio.NewScanner(cmdOut)
for scanner.Scan() {
ch <- scanner.Text()
}
}(ch)
return ch
}
func main() {
cmd := exec.Command("/usr/bin/sqlite3")
cmdIn, _ := cmd.StdinPipe()
cmdOut, _ := cmd.StdoutPipe()
cmd.Start()
ch := startScanner(cmdOut)
var lines []string
io.WriteString(cmdIn, ".help\n")
lines = readLinesFromChannelWithTimeout(ch, time.Millisecond*100)
fmt.Printf("Got %d lines from .help\n", len(lines))
io.WriteString(cmdIn, ".show\n")
lines = readLinesFromChannelWithTimeout(ch, time.Millisecond*100)
fmt.Printf("Got %d lines from .show\n", len(lines))
cmdIn.Close() // vital! Wait() will hang otherwise
if err := cmd.Wait(); err != nil {
log.Fatal(err)
}
}