Skip to content

Instantly share code, notes, and snippets.

@m-manu
Created March 4, 2014 05:57
Show Gist options
  • Save m-manu/9341025 to your computer and use it in GitHub Desktop.
Save m-manu/9341025 to your computer and use it in GitHub Desktop.
To use this script, just place this in "/bin" directory (and grant it 755 perms). Then run your source files like "run helloworld.c" or "run HelloWorld.java" or "run helloworld.c"
#!/usr/bin/python
'''
Quickly compile and execute a source file in one-go. Does cleanup of executable file, if any.
Handles C, C++, Java, PHP, Shell and Python
'''
import argparse
from os import path, system, remove
def sourcefile(x):
if not path.isfile(x):
raise argparse.ArgumentError("{0} does not exist".format(x))
return x
def execute_commands(compiling, executing=None, cleaning=None):
try:
ret = system(compiling)
if ret==0:
if executing:
system(executing)
if cleaning:
remove(cleaning)
except OSError:
print "run: Error executing or running"
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Compiles a small console program and writes output to stdout')
parser.add_argument('sourcefile', type=sourcefile, help='path to program')
parser.add_argument('arguments', nargs='*', help='arguments to the program')
args = parser.parse_args()
args_c_str = ('"'+'" "'.join(args.arguments)+'"', '')[int(len(args.arguments)==0)]
sourcefile = path.basename(args.sourcefile)
filename_noext, extension = path.splitext(sourcefile)
if(extension==".c" or extension==".cpp" or extension==".h"):
compiler = "echo"
if(extension==".c"):
compiler="cc"
elif(extension==".cpp"):
compiler = "c++"
elif(extension==".h"):
args.sourcefile = args.sourcefile.replace('.h', '.cpp')
compiler = "c++"
execute_commands("%s \"%s\" -o %s.out" % (compiler, args.sourcefile, filename_noext),
executing = "./%s.out %s" % (filename_noext, args_c_str),
cleaning = filename_noext + ".out")
elif extension==".php":
execute_commands("php \"%s\" %s" % (args.sourcefile, args_c_str))
elif extension==".py":
execute_commands("python \"%s\" %s" % (args.sourcefile, args_c_str))
elif extension==".sh":
execute_commands("source \"%s\" %s" % (args.sourcefile, args_c_str))
elif extension==".java":
execute_commands("javac \"%s\"" % (args.sourcefile),
executing="java \"%s\" %s" % (filename_noext, args_c_str),
cleaning= filename_noext + ".class")
else:
print "Don't know how to run source file '%s'" % (sourcefile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment