1. 程式人生 > >compile a string of python code

compile a string of python code

str = '''
flag = True
for i in range(0,3): 
    print i
if flag:
    print "ok"
'''
c = compile(str,'','exec')
exec c

得到如下結果

0
1
2
ok