【发布时间】:2019-09-21 13:38:27
【问题描述】:
我正在尝试对控制台 go 应用程序使用不同的 shell 命令,但由于某种原因,以下交互式 shell 的行为有所不同。
此代码打印 mongoDB 查询的结果:
cmd := exec.Command("sh", "-c", "mongo --quiet --host=localhost blog")
stdout, _ := cmd.StdoutPipe()
stdin, _ := cmd.StdinPipe()
stdoutScanner := bufio.NewScanner(stdout)
go func() {
for stdoutScanner.Scan() {
println(stdoutScanner.Text())
}
}()
cmd.Start()
io.WriteString(stdin, "db.getCollection('posts').find({status:'ACTIVE'}).itcount()\n")
//can't finish command, need to reuse it for other queries
//stdin.Close()
//cmd.Wait()
time.Sleep(2 * time.Second)
但 Neo4J shell 的相同代码不会打印任何内容:
cmd := exec.Command("sh", "-c", "cypher-shell -u neo4j -p 121314 --format plain")
stdout, _ := cmd.StdoutPipe()
stdin, _ := cmd.StdinPipe()
stdoutScanner := bufio.NewScanner(stdout)
go func() {
for stdoutScanner.Scan() {
println(stdoutScanner.Text())
}
}()
cmd.Start()
io.WriteString(stdin, "match (n) return count(n);\n")
//can't finish the command, need to reuse it for other queries
//stdin.Close()
//cmd.Wait()
time.Sleep(2 * time.Second)
有什么区别?我怎样才能使第二个工作? (不关闭命令)
附言
当我直接打印到os.Stdout 时,Neo4J 工作正常:
cmd := exec.Command("sh", "-c", "cypher-shell -u neo4j -p 121314 --format plain")
cmd.Stdout = os.Stdout
stdin, _ := cmd.StdinPipe()
cmd.Start()
io.WriteString(stdin, "match (n) return count(n);\n")
//stdin.Close()
//cmd.Wait()
time.Sleep(2 * time.Second)
【问题讨论】:
-
如果它适用于第二个变体,那么 cypher-shell 会打印到 stderr,而不是 stdout。 cmd.Stdout 分配通过调用 StdinPipe 被撤销。
-
@Peter 我试图删除
cmd.Stderr = os.Stderr,但它仍然以第二个变体打印结果。 -
我把 StdinPipe 误认为是 StdoutPipe。没关系我之前的评论。
标签: go cmd interactive-shell