#templates.py import fileinput, re field_pat = re.compile(r'\[(.*?)\]') scope = {} def replacement(match): code = match.group(1) try: return str(eval(code, scope)) except SyntaxError: exec code in scope return '' lines = [] for line in fileinput.input(): lines.append(line) text = ''.join(lines) print field_pat.sub(replacement, text)現(xiàn)在編輯兩個文件,通過調(diào)用這個腳本來處理: cat > magnus.txt [name = 'Magnus Lie Hetland' ] [email = 'magnus@foo.bar' ] [language = 'python' ] cat > template.txt [import time] Dear [name]. I would like to learn how to program. I hear you use the [language] a lot. Please help me to learn Oscar 現(xiàn)在來調(diào)用: python templates.py magnus.txt template.txt 結(jié)果: Dear Magnus Lie Hetland. I would li? to learn how to program. I hear you use the python a lot. Please help me to learn Oscar templates.py腳本把template.txt中[]定義的變量替換成了magnus.txt中定義好的值。
一段很強(qiáng)大的python腳本求解釋
桃花長相依
2018-07-18 07:04:42