compile() source code from a string

Costas Menico costas at meezon.com
Thu Mar 1 19:24:02 EST 2001


I would like to use the compile() function to compile source code from
a string variable.

The commands I use is as follows:

code='for i in range(3): print i'
comp=compile(code,'','exec')
exec(comp)

This works well.

However I would like to execute the following example from string
variable:

if x == 1:
  print "1"
  print "2"
  print "3"
elif x = 2:
  print 'A'
  print 'B'
  print 'C'  

print 1+2


How can I put this into a string variable that the compile() function
would accept? I tried putting chr(13)+chr(10) between each line but it
gives a syntax error. Also putting a \n or \r does not help either.

The only option that I see is to write it to a file and use
compile_file() but that would be time consuming.

Does anyone have any ideas how to do this?

Thanks

Costas






More information about the Python-list mailing list