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

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

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了