Passing go code directly into go run without a file
Asked Answered
go
T

4

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.

Terranceterrane answered 26/10, 2013 at 0:16 Comment(3)
One-liner alternative: echo "something" > x.go && go run x.goKelley
Don't have a computer handy to try it, but I suspect this would work? echo "code code code" | go run /dev/stdinSpec
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.Relativity
F
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.

Freefloating answered 26/10, 2013 at 1:47 Comment(0)
T
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)
Turmel answered 26/10, 2013 at 11:9 Comment(0)
C
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.

Catchfly answered 19/6, 2017 at 21:9 Comment(1)
Thanks, but still this is writing the source code to disk /tmp/blah.go. Anyway without writing a file?Terranceterrane
D
0

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

Doreendorelia answered 1/8, 2024 at 22:44 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.