Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Replacing Python Code with the Results of Executing That Code

Credit: Joel Gould

Problem

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.

Solution

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata