compile() source code from a string

Costas Menico costas at meezon.com
Fri Mar 2 08:03:15 EST 2001


"Chris Gonnerman" <chris.gonnerman at usa.net> wrote:

>This is a multi-part message in MIME format.
>
>------=_NextPart_000_0085_01C0A29E.B3939520
>Content-Type: text/plain;
>	charset="Windows-1252"
>Content-Transfer-Encoding: 7bit
>
>There IS a syntax error in your code.  To wit:
>
Sorry, I should test my examples before posting (duh). The problem I
have been having is with this code below.This code will not work
unless the """ are on their own line.  It seems Python needs an extra
CR at the end of the code. I guess it kind of makes sense. 

Thanks for your help, 
costas

#!/usr/bin/env python
# This code does not work unless you put
# the """ on their own line
codestr = """
if x == 1:
  print "1"
  print "2"
  print "3"
elif x == 2:
  print 'A'
  print 'B'
  print 'C'"""
codeobj = compile(codestr, "codestr", "exec")
x = 2
exec(codeobj)


#!/usr/bin/env python
# This code works
codestr = """
if x == 1:
  print "1"
  print "2"
  print "3"
elif x == 2:
  print 'A'
  print 'B'
  print 'C'
"""
codeobj = compile(codestr, "codestr", "exec")
x = 2
exec(codeobj)




More information about the Python-list mailing list