Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from os import sys
- from re import sub
- if len(sys.argv) == 1:
- print("[PREPROCESSOR ERR] Filename not specified.")
- exit()
- elif len(sys.argv) == 2:
- print("[PREPROCESSOR ERR] Output location not specified.")
- exit()
- args = sys.argv[1:]
- filename = args[0]
- output_path = args[1]
- sym_table = {}
- with open(filename) as file:
- lines = file.read().split("\n")
- for i in range(len(lines)):
- if lines[i].find("DEF_SYMS") >= 0:
- line = lines[i][(lines[i].find("DEF_SYMS ") + len("DEF_SYMS ")):]
- curr_line = line.split(" ")
- curr_line = [e.split("=") for e in curr_line]
- try:
- for e in curr_line:
- sym_table[e[0]] = e[1]
- except:
- print("[PREPROCESSOR ERR] DEF_SYMS directive must be formatted exactly like the following (_ = space) 'DEF_SYMS_<sym1>=<v1>_<sym2>=<v2>...'")
- break
- elif lines[i].find("END_SYMS") >= 0:
- line = lines[i][(lines[i].find("END_SYMS ") + len("END_SYMS ")):]
- curr_line = line.split(" ")
- try:
- for e in curr_line:
- if e in sym_table.keys():
- sym_table.pop(e)
- else:
- print("[PREPROCESSOR ERR] Cannot delete symbol: '" + e + "'")
- break
- except:
- print("[PREPROCESSOR ERR] END_SYMS directive must be formatted exactly like the following (_ = space) 'END_SYMS_<sym1>_<sym2>..'")
- break
- elif lines[i].find("END_ALL_SYMS") >= 0:
- sym_table = {}
- else:
- for key, value in sorted(sym_table.items(), key=lambda x: len(x)):
- lines[i] = sub(r"\b" + key + r"\b", value, lines[i])
- output = "\n".join(lines)
- try:
- with open(output_path, "r") as out: # When you use 'with', Python closes the file handle automatically when finished
- if out.read() != "":
- if input(output_path + " is not empty. Are you sure you want to overwrite it? (y/n): ") != "y":
- print("Cancelling preprocessing")
- else:
- with open(output_path, "w+") as out:
- out.write(output)
- print("Successfully preprocessed", filename)
- except:
- with open(output_path, "w") as out:
- out.write(output)
- print("Successfully preprocessed", filename)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement