英文:
Working in the console via exec.Command
问题
请帮忙。我必须通过一定数量的参数传递控制台命令。有很多参数。
理想情况下应该是这样的:
test.go --distr <这里是所需的程序,用逗号分隔>
例如:
test.go --distr mc curl cron
我创建了一个函数:
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)
}
}
并通过flag.Parse()获取参数distr。
我如何摆脱
"rpm-build",
"sudo",
"urpmi",
"curl"
这样就不会与包的数量有关。请原谅我的愚蠢,我刚开始学习golang。尤其是当出现问题时。
完整代码请参考:http://pastebin.com/yeuKy8Cc
英文:
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 <here comma desired program>
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
得分: 0
你正在寻找...
运算符。
func lsElements(elems ...string) {
cmd := exec.Command("ls", append([]string{"-l", "-h", "/root"}, elems...)...)
if err := cmd.Run(); err != nil {
log.Println(err)
}
}
你接收到的函数参数是...string
,实际上是一个[]string
,只是在调用函数时你将字符串分开传递。
为了使用它(它适用于任何切片),你可以使用...
后缀将切片"转换"为元素列表。
在exec的情况下,如果只有elem...
,你可以直接使用它。然而,由于你还有固定的参数,你需要使用append
构建切片,并使用...
扩展它。
示例:http://play.golang.org/p/180roQGL4a
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论