使用”go run”将命令行参数传递给可执行文件的方法是:

huangapple go评论89阅读模式
英文:

Passing CLI arguments to excutables with 'go run'

问题

我有一个程序readfile.go,我想将命令行参数os.Args[1]也设置为readfile.go

然而,'go run'认为这是它自己的附加参数,而不是输出可执行文件的参数。是否有一个标志可以告诉'go run'这是可执行文件的参数?

mvaidya@mvaidya-VirtualBox:~/junkeork$ go run readfile.go readfile.go
package main: case-insensitive file name collision: "readfile.go" and "readfile.go"
mvaidya@mvaidya-VirtualBox:~/junkeork$

错误信息:

package main: case-insensitive file name collision: "readfile.go" and "readfile.go"

英文:

I have a program readfile.go and I want to give the command line argument os.Args[1] also as readfile.go.

However 'go run' thinks that it is an additional argument to itself rather than to the output executable. Is there a flag which can tell 'go run' that this is an argument to executable?

<pre>
mvaidya@mvaidya-VirtualBox:~/junkeork$ go run readfile.go readfile.go
package main: case-insensitive file name collision: "readfile.go" and "readfile.go"
mvaidya@mvaidya-VirtualBox:~/junkeork$
</pre>

Error:
> package main: case-insensitive file name collision: "readfile.go" and
> "readfile.go"

答案1

得分: 29

你可以使用--来将go文件与参数分开:

go run readfile.go -- readfile.go
英文:

You can use -- to separate gofiles from arguments:

go run readfile.go -- readfile.go

答案2

得分: 8

为了避免获取两次readfile.go的歧义,我建议你使用命名的标志。这也会解决这个问题。

示例:

package main

import (
    "flag"
    "fmt"
)

func main() {
    cmd := flag.String("cmd", "", "")
    flag.Parse()
    fmt.Printf("my cmd: \"%v\"\n", string(*cmd))
}

不要忘记使用flag.Parse()来获取命令行参数

你可以通过以下方式将参数传递给go run命令:go run .\main.go -cmd main.go,然后你将得到输出:

my cmd: "main.go"

希望这能帮到其他人。

英文:

To avoid the ambiguity of getting twice readfile.go, I advise you to use named flags. This will solve the problem too.

Example:

package main

import (
    &quot;flag&quot;
    &quot;fmt&quot;
)

func main() {
    cmd := flag.String(&quot;cmd&quot;, &quot;&quot;, &quot;&quot;)
    flag.Parse()
    fmt.Printf(&quot;my cmd: \&quot;%v\&quot;\n&quot;, string(*cmd))
}

Don't forget using flag.Parse() to retrieve the command line arguments

You can pass args to the go run command this way: go run .\main.go -cmd main.go and you'll get as output:

my cmd: &quot;main.go&quot;

I hope this can help other.

答案3

得分: 1

janos的答案对于未命名的参数可以很好地工作,对于命名参数:

go run .go -arg1Name arg1Value -arg2Name arg2Value.....
例如,go run main.go -x 2 -y 5;x和y是参数名称。
英文:

The answer by janos can work well with unnamed args., for named args.:

go run .go -arg1Name arg1Value -arg2Name arg2Value.....
Eg, go run main.go -x 2 -y 5 ; x and y are arg. names

huangapple
  • 本文由 发表于 2017年7月15日 19:52:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/45117892.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定