dongtaidai0492 2014-11-10 18:25
浏览 56
已采纳

通过exec.Command在控制台中工作

Please help. I have to pass the console commando with a certain number of parameters. There are many.

That is, ideally, should be as follows: test.go --distr For example: test.go --distr mc curl cron

i create function

 func chroot_create() {
        cmd := exec.Command("urpmi",
                "--urpmi-root",
                *fldir,
                "--no-verify-rpm",
                "--nolock",
                "--auto",
                "--ignoresize",
                "--no-suggests",
                "basesystem-minimal",
                "rpm-build",
                "sudo",
                "urpmi",
                "curl")
        if err := cmd.Run(); err != nil {
                log.Println(err)
        }
}

And catch parameter distr through flag.Parse ()

How do I get rid of "rpm-build", "sudo", "urpmi", "curl") That would not be tied to count packets. Please forgive me for stupidity, I'm just starting to learn golang. Especially when there was a problem.

Full code http://pastebin.com/yeuKy8Cc

  • 写回答

1条回答 默认 最新

  • 普通网友 2014-11-11 02:14
    关注

    You are looking for the ... operator.

    func lsElements(elems ...string) {
            cmd := exec.Command("ls", append([]string{"-l", "-h", "/root"}, elems...)...)
            if err := cmd.Run(); err != nil {
                    log.Println(err)
            }
    }
    

    You receive as function parameter ...string which is in really a []string, except that when you call the function, you pass the strings separately.

    In order to use it, (and it works with any slices), you can "transform" your slice into list of element with ... suffix.

    In the case of exec, you could use elem... directly if you had only this. However, has you have fixed parameters as well, you need to build your slice with append and extend it back with ...

    Example: http://play.golang.org/p/180roQGL4a

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于博途V17进行仿真时无法建立连接问题
  • ¥15 请问下这个红框里面是什么文档或者记事本编辑器
  • ¥15 机器学习教材中的例题询问
  • ¥15 求.net core 几款免费的pdf编辑器
  • ¥15 为什么安装HCL 和virtualbox之后没有找到VirtualBoxHost-OnlyNetWork?
  • ¥15 C# P/Invoke的效率问题
  • ¥20 thinkphp适配人大金仓问题
  • ¥20 Oracle替换.dbf文件后无法连接,如何解决?(相关搜索:数据库|死循环)
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)