Created
December 24, 2020 01:54
-
-
Save Lokno/237f72d40a56c4f18c324b78fea9c63d to your computer and use it in GitHub Desktop.
Python script for evaluating single line C/C++ code
This file contains hidden or 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
| import sys,os | |
| import subprocess | |
| types = { 'int' : '%d', | |
| 'long' : '%ld', | |
| 'long long' : '%lld', | |
| 'float' : '%.32f', | |
| 'double' : '%.56f', | |
| 'unsigned' : '%u', | |
| 'unsigned long' : '%lu', | |
| 'unsigned long long' : '%llu', | |
| 'str' : '%s' } | |
| compilers = { 'gcc' : 'c', 'g++' : 'cpp' } | |
| cpp_template = """ | |
| #include <iostream> | |
| #include <limits> | |
| #include <cmath> | |
| #include <iomanip> | |
| int main() | |
| { | |
| std::cout << std::setprecision(50) << (%s) << std::endl; | |
| return 0; | |
| } | |
| """ | |
| c_template = """ | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <math.h> | |
| #include <limits.h> | |
| int main() | |
| { | |
| printf("%s\\n",%s); | |
| return 0; | |
| } | |
| """ | |
| if 2 < len(sys.argv) < 5: | |
| compiler = sys.argv[1] | |
| out_type = None | |
| if len(sys.argv) == 4: | |
| out_type = sys.argv[2] | |
| code_line = sys.argv[3] | |
| else: | |
| code_line = sys.argv[2] | |
| if compiler not in compilers: | |
| print('compiler %s unsupported' % compiler) | |
| sys.exit(-1) | |
| lang = compilers[compiler] | |
| if lang != 'c': | |
| out_type = None | |
| if lang == 'c' and out_type is None: | |
| print('c compilation requires return type') | |
| sys.exit(-1) | |
| if lang == 'c' and out_type not in types: | |
| print('type %s unsupported for c compilation' % out_type) | |
| sys.exit(-1) | |
| if code_line[-1] == ';': | |
| code_line = code_line[:-1] | |
| filename = "tmp." + lang | |
| template = c_template if lang == "c" else cpp_template | |
| with open(filename,"w") as fout: | |
| args = (code_line) if out_type is None else (types[out_type],code_line) | |
| fout.write(template % args) | |
| os.system("%s -o tmp %s" % (compiler,filename)) | |
| process = subprocess.Popen(['./tmp'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
| out,err = process.communicate() | |
| if err.decode() == '': | |
| print(out.decode().rstrip()) | |
| else: | |
| print('ERROR: ' + err.decode().rstrip()) | |
| else: | |
| print(" usage %s <compiler> [<return type>] <code>" % sys.argv[0]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment