1 >>> code = """
2 ... def test():
3 ... print "this is a test by abeen"
4 ... """
5 >>> test() # 'test'is not defined
6 Traceback (most recent call last):
7 File "", line 1, in
8 NameError: name 'test' is not defined
9 >>> exec code
10 >>> test() # test()成功执行
11 this is a test by abeen Eval
eval() 和 execfile() 都有 "globals, locals" 参数,用于传递环境变量,默认或显式设置为 None 时都直接使用 globals() 和 locals() 获取当前作用域的数据。
1 >>> a =10
2 >>> eval("a+3") #默认传递环境变量
3 13
4 >>> evla("a+3")
5 Traceback (most recent call last):
6 File "", line 1, in
7 NameError: name 'evla' is not defined
8 >>> eval("a+3")
9 13
10 >>> eval("a+3",{},{"a":100}) #显示传递环境变量
11 103 execfile
main.py
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
s = "main.s"
execfile("test.py")
test.py
1 #!/usr/bin/env python
2 # _*_ coding:utf-8 _*_
3
4 def test():
5 print "this is a test by abeen", s
6
7 test()
输出结果:
1 abeen@localhost:~/learn_test/exec_compile$ python main.py
2 this is a test by abeen main.s