Created
October 26, 2013 11:09
-
-
Save x3ro/7168195 to your computer and use it in GitHub Desktop.
Python script to run Go code supplied from stdin, based on http://stackoverflow.com/questions/19601338/passing-go-code-directly-into-go-run-without-a-file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment