Passing indented code to compile()
Harvey Thomas
hst at empolis.co.uk
Wed May 7 08:49:49 EDT 2003
John Wilson wrote:
>
> 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
>
Assuming that you are parsing for well-formed XML, then all white space is considered significant; hence the blank line and leading white space before/after the print statement. If the XML document had contained
<execute globals="globals" locals="locals">print "hello"</execute>
then you wouldn't have had the problem. If the code to be compiled spans more than one line I can see further problems though as Python's indentation rules are going to get in the way unless the XML is very carefully formatted.
HTH
Harvey
_____________________________________________________________________
This message has been checked for all known viruses by the MessageLabs Virus Scanning Service.
More information about the Python-list
mailing list