【发布时间】:2019-04-02 13:06:01
【问题描述】:
我的应用程序适用于从控制台提供的所有类型的 shell 命令(curl、date、ping,等等)。现在我想使用os/exec 使用交互式 shell 命令(如 mongo shell)来介绍这个案例。
例如第一步,连接到 mongodb:
mongo --quiet --host=localhost blog然后执行任意数量的命令,每一步都得到结果
db.getCollection('posts').find({status:'INACTIVE'})然后
exit
我尝试了以下方法,但它允许我每个 mongo 连接只执行一个命令:
func main() {
cmd := exec.Command("sh", "-c", "mongo --quiet --host=localhost blog")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
stdin, _ := cmd.StdinPipe()
go func() {
defer stdin.Close()
io.WriteString(stdin, "db.getCollection('posts').find({status:'INACTIVE'}).itcount()")
// fails, if I'll do one more here
}()
cmd.Run()
cmd.Wait()
}
有没有办法运行多个命令,得到每个执行命令的标准输出结果?
【问题讨论】:
-
您不应该为此使用 os/exec。您应该使用 mongo 驱动程序,直接与 mongodb 对话。
-
@Flimzy 我不能使用任何驱动程序,我的应用程序不应该知道提供的命令。它可以是 mongo、mysql、postgres 等等。
-
那么你应该为每一个使用驱动程序。如果您的应用程序知道将哪些命令发送到 os.exec 调用,那么它就必须知道它们。
标签: go interactive-shell