#!/usr/local/bin/python """ Convert C programs to Python programs automatically """ import sys, os, string def main(): for file in sys.argv[1:]: convert_to_python(file) def convert_to_python(filename): if filename[-2:] == ".c": convert_c_to_python(filename) def convert_c_to_python(filename): new_filename = filename[:-2] + ".py" try: f = open(filename, "r") lines = f.readlines() f.close() except IOError: print "File", filename, "is unreadable. Skipping." return try: f = open(new_filename, "r") f.close() print "File", new_filename, "already exists. Skipping." return except IOError: pass f = open(new_filename, "w") f.write("#!/usr/local/bin/python\n") for line in lines: converted_line = c_line_to_python(line) f.write(converted_line) f.write("\nmain()\n\n") f.close() os.system("chmod +x " + new_filename) print new_filename line_starts = [ ["/*", "##" ], [" */", "##" ], ["*/", "##" ], [" *", "# " ], ["*", "#" ], ["//", "##" ], ["#include ", "import os" ], ["#include ", "import sys" ], ["#include ", "import string" ], ["#include ", "import string" ], ["#include ", "import math" ], ["#include ", "import time" ], ["#include ", "from graphapp import *"], ["#include <", "import " ], ['#include "', "import " ], ["main()", "def main():" ], ["void main()", "def main():" ], ["main(void)", "def main():" ], ["void main(void)", "def main():" ], ["int main()", "def main():" ], ["main(int argc, char **argv)", "def main():" ], ["main(int argc, char *argv[])", "def main():" ], ["void main(int argc, char **argv)", "def main():" ], ["void main(int argc, char *argv[])", "def main():" ], ["int main(int argc, char **argv)", "def main():" ], ["int main(int argc, char *argv[])", "def main():" ], ["void ", "def ", ":"], ["int ", "def ", ":"], ["char *", "def ", ":"], ["else", "else", ":"], ] line_ends = [ ["{", "" ], ["}", "" ], [";", "" ], ] whole_lines = [ ["{", "" ], ["}", "" ], ] def c_line_to_python(line): if (line == "") or (line == "\n"): return line words = string.join(string.split(line)) for pattern in whole_lines: if words == pattern[0]: line = pattern[1] has_newline = (line[-1:] == '\n') if has_newline: line = line[:-1] for pattern in line_ends: length = len(pattern[0]) if line[-length:] == pattern[0]: line = line[:-length] + pattern[1] for pattern in line_starts: length = len(pattern[0]) if line[:length] == pattern[0]: line = pattern[1] + line[length:] if len(pattern) == 3: line = line + pattern[2] if has_newline: line = line + "\n" return line if __name__ == "__main__": main()