将代码直接传递到没有文件的go run

时间:2013-10-26 00:16:08

标签: go

是否可以将一串go代码传递到go run而不是go run /some/path/script.go?我试过了:

echo "some awesome go code here" | go run

但是不起作用。感谢。

3 个答案:

答案 0 :(得分:3)

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

您可以尝试将gccgo用作GCC supports reading from stdin

答案 1 :(得分:2)

由于我认为这是一个有用的东西,我写了一个相对较小的Python脚本,实现了我想你想要的。我称之为go-script,这里有一些用法示例:

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

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

帮助:

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't specify 'package main' (enabled by default)
  -m, --main            Wrap input in a func main() {} block
  -d, --debug           Print the generated Go code instead of running it.

来源(也可用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("-i", "--import", dest="imports", action="append", default=[],
                  help="Import package of given name", metavar="PACKAGE")

parser.add_option("-p", "--no-package", dest="package", action="store_false", default=True,
                  help="Don't specify 'package main' (enabled by default)")

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

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

(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)

答案 2 :(得分:1)

这有效

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

package main
import "fmt"

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

如果您不想打开文件并先编辑它。虽然我不会发现这对每天使用都非常实用。