饭叔的知识整理

python exec

exec code in module.__dict__ means execute the commands in the file or string called 'code', taking global and local variables referred to in 'code' from module.dict and storing local and global variables created in 'code' into the dictionary module.dict

See http://docs.python.org/reference/simple_stmts.html#exec

Eg:

In [51]: mydict={}

In [52]: exec "val1=100" in mydict

In [53]: mydict['val1']
Out[53]: 100

Eg2:

In [54]: mydict={}

In [55]: mydict['val2']=200

In [56]: exec "val1=val2" in mydict

In [57]: mydict.keys()
Out[57]: ['__builtins__', 'val2', 'val1']

In [58]: mydict['val2']
Out[58]: 200

In [59]: mydict['val1']
Out[59]: 200

参考

http://stackoverflow.com/questions/12521675/given-module-m-and-code-object-c-what-does-exec-c-in-m-dict-do
http://stackoverflow.com/questions/2315044/how-to-generate-a-module-object-from-a-code-object-in-python