Passing indented code to compile()

John Wilson tug at wilson.co.uk
Wed May 7 07:53:31 EDT 2003


I hit a problem when trying to compile some Python code embedded in an XML
document.

For example:

        <execute globals="globals" locals="locals">
            print "hello"
        </execute>

If I just pass the string I construct from the SAX callbacks the compile
function complains of a syntax error.

There seem to be two problems here:

1/ The line '            print "hello"' is preceded by a blank line and
followed by some whitespace.

2/  The line '            print "hello"' starts with whitespace.

I can fix point 1/ trivially by can remove leading and trailing blank lines.

Point 2/ is harder to fix. It isn't simple to shift an arbitrary block of
Python code to the left (comments and triple-quoted strings spring to mind
as sources of complexity).

What I do is to remove the leading and trailing blank lines, check to see if
the first character of the remaining lines (if any) is whitespace. If it is
then I prepend the statement "if 1:". I then append a blank line to the
resulting code block.

Questions:

1/ Will this always work?

2/ Is there a better way of doing this?

John Wilson
The Wilson Partnership
http://www.wilson.co.uk






More information about the Python-list mailing list