将go代码直接传递给go run而不使用文件

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

Passing go code directly into go run without a file

问题

可以将Go代码作为字符串传递给go run命令吗?而不是使用go run /some/path/script.go的方式?我尝试了以下命令:

echo "some awesome go code here" | go run

但是没有成功。谢谢。

英文:

Is it possible to pass a string of go code into go run instead of go run /some/path/script.go? I tried:

echo "some awesome go code here" | go run

But does not work. Thanks.

答案1

得分: 3

我不认为有这样的选项。至少标准的*g编译器或go run没有这个选项。

你可以尝试使用gccgo,因为GCC支持从标准输入读取

英文:

I don't think that there is such an option. At least not with the standard *g compilers or
go run.

You can try using gccgo as GCC supports reading from stdin.

答案2

得分: 3

由于代码部分是英文的,我将为您提供代码的中文翻译:

由于我认为这是一个有用的工具,所以我编写了一个相对简短的Python脚本,可以实现您想要的功能。我将其称为go-script,以下是一些用法示例:

假设test.go是一个有效的Go文件,包括包和导入:

$ go-script --no-package < test.go

从标准输入运行代码,导入fmt并将其包装在func main(){}中:

$ echo 'fmt.Println("test")' | go-script --import fmt --main
$ echo 'fmt.Println("test")' | go-script -ifmt -m

帮助信息:

用法:go-script [选项]

选项:
  -h, --help            显示此帮助消息并退出
  -i PACKAGE, --import=PACKAGE
                        导入给定名称的包
  -p, --no-package      不指定'package main'(默认启用)
  -m, --main            将输入包装在func main() {}块中
  -d, --debug           打印生成的Go代码而不是运行它。

源代码(也可在gist上找到):

#!/usr/bin/env python

from __future__ import print_function
from optparse import OptionParser
import os
import sys

parser = OptionParser()

parser.add_option("-i", "--import", dest="imports", action="append", default=[],
                  help="导入给定名称的包", metavar="PACKAGE")

parser.add_option("-p", "--no-package", dest="package", action="store_false", default=True,
                  help="不指定'package main'(默认启用)")

parser.add_option("-m", "--main", dest="main", action="store_true", default=False,
                  help="将输入包装在func main() {}块中")

parser.add_option("-d", "--debug", dest="debug", action="store_true", default=False,
                  help="打印生成的Go代码而不是运行它。")

(options, args) = parser.parse_args()

stdin = ""
for line in sys.stdin.readlines():
    stdin += "%s\n" % line

out = ""
if options.package:
    out += "package main\n\n"

for package in options.imports:
    out += "import \"%s\"\n" % package

out += "\n"
if options.main:
    out += "func main() {\n%s\n}\n" % stdin
else:
    out += stdin

if options.debug:
    print(out)
else:
    tmpfile = "%s%s" % (os.environ["TMPDIR"], "script.go")
    f = open(tmpfile, 'w')
    print(out, file=f)
    f.close()
    os.execlp("go", "", "run", tmpfile)

以上是代码的中文翻译。

英文:

Since I thought that this would be a useful thing to have, I wrote a relatively small Python script that achieves what I think you want. I called it go-script, and here are some usage examples:

# Assuming that test.go is a valid go file including package and imports
$ go-script --no-package &lt; test.go

# Runs code from stdin, importing &#39;fmt&#39; and wrapping it in a func main(){}
$ echo &#39;fmt.Println(&quot;test&quot;)&#39; | go-script --import fmt --main
$ echo &#39;fmt.Println(&quot;test&quot;)&#39; | go-script -ifmt -m

Help:

Usage: go-script [options]

Options:
  -h, --help            show this help message and exit
  -i PACKAGE, --import=PACKAGE
                        Import package of given name
  -p, --no-package      Don&#39;t specify &#39;package main&#39; (enabled by default)
  -m, --main            Wrap input in a func main() {} block
  -d, --debug           Print the generated Go code instead of running it.

The source (also available as a gist):

#!/usr/bin/env python

from __future__ import print_function
from optparse import OptionParser
import os
import sys

parser = OptionParser()

parser.add_option(&quot;-i&quot;, &quot;--import&quot;, dest=&quot;imports&quot;, action=&quot;append&quot;, default=[],
                  help=&quot;Import package of given name&quot;, metavar=&quot;PACKAGE&quot;)

parser.add_option(&quot;-p&quot;, &quot;--no-package&quot;, dest=&quot;package&quot;, action=&quot;store_false&quot;, default=True,
                  help=&quot;Don&#39;t specify &#39;package main&#39; (enabled by default)&quot;)

parser.add_option(&quot;-m&quot;, &quot;--main&quot;, dest=&quot;main&quot;, action=&quot;store_true&quot;, default=False,
                  help=&quot;Wrap input in a func main() {} block&quot;)

parser.add_option(&quot;-d&quot;, &quot;--debug&quot;, dest=&quot;debug&quot;, action=&quot;store_true&quot;, default=False,
                  help=&quot;Print the generated Go code instead of running it.&quot;)

(options, args) = parser.parse_args()

stdin = &quot;&quot;
for line in sys.stdin.readlines():
    stdin += &quot;%s\n&quot; % line

out = &quot;&quot;
if options.package:
    out += &quot;package main\n\n&quot;

for package in options.imports:
    out += &quot;import \&quot;%s\&quot;\n&quot; % package

out += &quot;\n&quot;
if options.main:
    out += &quot;func main() {\n%s\n}\n&quot; % stdin
else:
    out += stdin

if options.debug:
    print(out)
else:
    tmpfile = &quot;%s%s&quot; % (os.environ[&quot;TMPDIR&quot;], &quot;script.go&quot;)
    f = open(tmpfile, &#39;w&#39;)
    print(out, file=f)
    f.close()
    os.execlp(&quot;go&quot;, &quot;&quot;, &quot;run&quot;, tmpfile)

答案3

得分: 1

这段代码可以实现以下功能:

cat <<EOF | tee /tmp/blah.go | go run /tmp/blah.go

package main
import "fmt"

func main() {
  fmt.Println("Hello, World!")
}
EOF

如果你不想先打开文件并编辑它,可以使用这种方式。尽管我认为这种方法在日常使用中并不是非常实用。

英文:

This works

cat &lt;&lt;EOF | tee /tmp/blah.go | go run /tmp/blah.go

package main
import &quot;fmt&quot;

func main() {
  fmt.Println(&quot;Hello, World!&quot;)
}
EOF

If you want to not have to open a file and edit it first. Although I wouldn't find this super practical for every day use.

huangapple
  • 本文由 发表于 2013年10月26日 08:16:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/19601338.html
匿名

发表评论

匿名网友

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

确定