July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Joel Gould
You have a template string that may include embedded Python code, and you need a copy of the template in which any embedded Python code is replaced by the results of executing that code.
This recipe exploits the ability of the standard function
re.sub to call
a user-supplied replacement function for each match and to substitute
the matched substring with the replacement
function’s result:
import re
import sys
import string
def runPythonCode(data, global_dict={}, local_dict=None, errorLogger=None):
""" Main entry point to the replcode module """
# Encapsulate evaluation state and error logging into an instance:
eval_state = EvalState(global_dict, local_dict, errorLogger)
# Execute statements enclosed in [!! .. !!]; statements may be nested by
# enclosing them in [1!! .. !!1], [2!! .. !!2], and so on:
data = re.sub(r'(?s)\[(?P<num>\d?)!!(?P<code>.+?)!!(?P=num)\]',
eval_state.exec_python, data)
# Evaluate expressions enclosed in [?? .. ??]:
data = re.sub(r'(?s)\[\?\?(?P<code>.+?)\?\?\]',
eval_state.eval_python, data) return data class EvalState: """ Encapsulate evaluation state, expose methods to execute/evaluate """ def _ _init_ _(self, global_dict, local_dict, errorLogger): self.global_dict = global_dict self.local_dict = local_dict if errorLogger: self.errorLogger = errorLogger else: # Default error "logging" writes error messages to sys.stdout self.errorLogger = sys.stdout.write # Prime ...