ameerkat
6/10/2011 - 8:05 AM

Python html linker

Python html linker

# Python HTML Linker
# Ameer Ayoub <ameer.ayoub@gmail.com>
from sys import argv
import re

def print_usage(script_name):
	print "usage:", script_name, "target_file template_file source_file0 (source_file1, source_file2, ...)"

if __name__ == "__main__":
	script_name = argv[0]
	target_file = ""
	template_file = ""
	source_files = []
	if(len(argv) >= 4):
		target_file = argv[1]
		template_file = argv[2]
		source_files = argv[3:]
		tin = open(template_file)
		tin_str = tin.read()
		out_str = tin_str
		trre = re.compile("\\$\\(\\d+\\)")
		trred = re.compile("\\d+")
		s = re.findall(trre, tin_str)
		for d in s:
			m = re.search(trred, d)
			if int(m.group(0)) < len(source_files):
				sin = open(source_files[int(m.group(0))])
				sin_str = sin.read()
				out_str = out_str.replace(d, sin_str)
				sin.close()
			else:
				print "Token", m.group(1), "out of range. Remove token or supply more source files."
		tout = open(target_file, "w")
		tout.write(out_str)
		tin.close()
		tout.close()
		print "Operation completed."
	else:
		print_usage(script_name)