6

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

echo "some awesome go code here" | go run

但不起作用。谢谢。

4

3 回答 3

3

因为我认为这将是一个有用的东西,所以我编写了一个相对较小的 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.

来源(也可作为 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)
于 2013-10-26T11:09:41.827 回答
3

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

您可以尝试使用gccgo,因为GCC 支持从 stdin 读取

于 2013-10-26T01:47:33.493 回答
1

这有效

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

package main
import "fmt"

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

如果您不想先打开文件并对其进行编辑。虽然我不会发现这种超级实用的日常使用。

于 2017-06-19T21:09:13.257 回答