python
exec <Code to execute> [Dictionary of reference variables[,Dictionary of variable allocation destination]]
exec.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##Basic example. There are side effects in the global environment
exec "x=1"
print "x in global env is", x
##Run in your own environment.
ref1=dict(x=100)
exec """print 'x in temporary env is', x
y=x+1""" in ref1
print "y is in global()? ->", "y" in globals()
print "y in ref1 is", ref1["y"]
##Run in your own environment. Variable assignment to another environment
ref2=dict(x=1000)
dest=dict()
exec "z=1+x" in ref2, dest
print "z is in global()? ->", "z" in globals()
print "z is in ref2? ->", "z" in ref2
print "z in dest is", dest["z"]
Execution result
python
bash-3.2$ ./exec.py
x in global env is 1
x in temporary env is 100
y is in global()? -> False
y in ref1 is 101
z is in global()? -> False
z is in ref2? -> False
z in dest is 1001
Recommended Posts