python 讀檔範例
import os
import re
import sys
def parse(include_pattern, file, fout):
fin = open(file, 'r')
if not fin:
sys.stderr.write("File %s is not found.\n" % file)
raise SystemExit(1)
while True:
ch = fin.read(1)
if len(ch) == 0:
break
elif ch == '{':
ch = fin.read(1)
if ch == '%':
cmd = ''
while True:
ch = fin.read(1)
if len(ch) == 0:
break
elif ch == '%':
ch = fin.read(1)
if ch == '}':
break
else:
cmd += '%' + ch
else:
cmd += ch
print "Command is : %s" % cmd
for subfile in include_pattern.finditer(cmd):
parse(include_pattern, subfile.group(1), fout)
else:
fout.write('{' + ch)
else:
fout.write(ch)
fin.close()
if len(sys.argv) != 4:
sys.stderr.write("Usage: python %s inputfile outputfile host\n" % sys.argv[0])
raise SystemExit(1)
include_pattern = re.compile('include_file\s"([^"]+)"')
fout = open(sys.argv[2], 'w')
parse(include_pattern, sys.argv[1], fout)
fout.close()
fin = open(sys.argv[2], 'r')
code = fin.read()
fin.close()
#code = code.replace("{{host}}", sys.argv[3])
fout = open(sys.argv[2], 'w')
fout.write(code)
fout.close()
留言
張貼留言