登录
首页 >  Golang >  Go问答

在命令行界面中如何同时执行多个命令

来源:stackoverflow

时间:2024-03-19 22:24:30 128浏览 收藏

在命令行界面中同时执行多个命令可以通过交互式 shell 来实现。例如,连接到 MongoDB 后,可以通过写入进程的标准输入来执行任意数量的命令,并获取每一步的结果。不过,为了与 MongoDB 交互,建议使用 MongoDB 驱动程序,而不是尝试通过 shell exec 与其交互。

问题内容

我的应用程序可以使用控制台提供的所有类型的 shell 命令(curldateping 等)。现在我想使用 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()
}

有没有办法运行多个命令,为每个执行的命令获取标准输出结果?


解决方案


正如 flimzy 所指出的,您绝对应该使用 mongo 驱动程序来使用 mongo,而不是尝试通过 shell exec 与其交互。

但是,要回答根本问题,您当然可以执行多个命令 - 没有理由不能。每次写入进程的标准输入时,就像在终端上输入一样。除了专门检测它们是否连接到 tty 的进程之外,对此没有任何秘密限制。

不过,您的代码有几个问题 - 您绝对应该查看 os/exec package documentation。您正在调用 cmd.run,其中:

启动指定的命令并等待其完成。

然后调用 cmd.wait,这...也等待命令完成。你正在一个 goroutine 中写入 stdin 管道,即使这是一个非常序列化的过程:你想要写入管道来执行一个命令,获取结果,写入另一个命令,获取另一个结果......并发只会混乱很重要,不应该在这里使用。并且您不会发送换行符来告诉 mongo 您已经完成了命令的编写(就像您在 shell 中所做的那样 - mongo 不会在您输入结束括号后立即开始执行,您必须按 enter 键) .

您希望通过 stdin/stdout 与进程交互(再次注意,这绝对不是与数据库交互的方式,但是可以 对其他外部命令有效):

cmd := exec.Command("sh", "-c", "mongo --quiet --host=localhost blog")

cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr

stdin, _ := cmd.StdinPipe()

// Start command but don't wait for it to exit (yet) so we can interact with it
cmd.Start()

// Newlines, like hitting enter in a terminal, tell Mongo you're done writing a command
io.WriteString(stdin, "db.getCollection('posts').find({status:'INACTIVE'}).itcount()\n")
io.WriteString(stdin, "db.getCollection('posts').find({status:'ACTIVE'}).itcount()\n")

// Quit tells it you're done interacting with it, otherwise it won't exit
io.WriteString(stdin, "quit()\n")

stdin.Close()

// Lastly, wait for the process to exit
cmd.Wait()

本篇关于《在命令行界面中如何同时执行多个命令》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

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