7

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.

3
  • One-liner alternative: echo "something" > x.go && go run x.go Commented Oct 26, 2013 at 1:57
  • Don't have a computer handy to try it, but I suspect this would work? echo "code code code" | go run /dev/stdin Commented Oct 26, 2013 at 3:53
  • go run /dev/stdin doesn't work. Go checks that the file name is *.go . So I tried ln -s /dev/stdin stdin.go. But this happened: pastebin.com/YF1rv1bG My Hypothesis is that go tries to seek. Which breaks if the input file is stdin. Commented Oct 26, 2013 at 6:01

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

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'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.

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

Comments

1

This works

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

package main
import "fmt"

func main() {
  fmt.Println("Hello, World!")
}
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.

1 Comment

Thanks, but still this is writing the source code to disk /tmp/blah.go. Anyway without writing a file?
0

It has been proposed and declined here. There’s no built-in way to do this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.