将一个.go文件作为额外参数传递给`go run`命令。

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

Passing a .go-file as additional argument to `go run`

问题

为了快速进行编程,我更喜欢使用go run prog.go ...而不是先构建可执行文件。然而,我正在处理的程序需要将另一个go文件作为参数。因此,go run和编译后的二进制文件的行为是不同的:

go run prog.go foo.go

会尝试执行两个go文件,而

go build prog.go && ./prog foo.go

会正确地将我的文件作为输入(预期的行为)。现在我可以通过go run ... -- foo.go这样的方式传递额外的参数,但是由于--的存在,os.Args中文件的位置在go run prog.go -- foo.go./prog foo.go之间是不同的。有没有简单的解决方案?我不想进行完整的标志处理。我应该放弃并坚持使用编译版本吗?

英文:

For quick hacking, I prefer to use go run prog.go ... instead of building the executable first. However, the program I am working on should take another go-file as an argument. As a consequence, go run and the compiled binary behave differently:

go run prog.go foo.go

will try to execute both go-files, whereas

go build prog.go && ./prog foo.go

will correctly take my file as input (the intended behaviour). Now I can pass additional args like this go run ... -- foo.go, but then because of the -- the position of the file differs in os.Args between the go run prog.go -- foo.go and the ./prog foo.go. Any easy solution? I'd like to avoid having full flag-processing. Should I just give up and stick to the compiled version?

答案1

得分: 6

这是命令的源代码,不可能的。:

for i < len(args) && strings.HasSuffix(args[i], ".go") {
    i++
}
files, cmdArgs := args[:i], args[i:]

你可以使用go install代替go build。这将把可执行文件放在$GOPATH/bin文件夹中(我不喜欢将二进制文件放在同一个文件夹中,因为有时我会不小心将其添加到git中)。但实际上并没有太大的区别。

另一个你可能想考虑的选项是rerun。它会在你更改文件时自动重新编译和运行代码:

rerun path/to/your/project foo.go
英文:

It's not possible. Here's the source for the command:

for i &lt; len(args) &amp;&amp; strings.HasSuffix(args[i], &quot;.go&quot;) {
    i++
}
files, cmdArgs := args[:i], args[i:]

You can use go install instead of go build. That will put your executable in your $GOPATH/bin folder (I don't like having the binary in the same folder because sometimes I accidentally add it to git). But it's really not much different.

Another option you might want to consider is rerun. It will automatically recompile and run your code whenever you change a file:

rerun path/to/your/project foo.go

答案2

得分: 0

再次看着我的问题,我必须弄清楚是否我将来会需要多个输入文件。如果不需要,我可以通过从Stdin读取而不是打开文件来解决。

英文:

Looking at my problem again, I have to find out if I'm ever going to need several input files. If not, I might get away with just reading from Stdin instead of opening a file.

huangapple
  • 本文由 发表于 2015年5月7日 21:39:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/30102822.html
匿名

发表评论

匿名网友

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

确定