eval(expression[, globals[, locals]])
b = eval("{'name':'linux','age':age}",{"age":1822}) print(b) 結果:{‘name’: ‘linux’, ‘age’: 1822}
age=18 b = eval("{'name':'linux','age':age}",{"age":1822},locals()) print(b) 結果:{'name': 'linux', 'age': 18}
x = 10 def func(): y = 20 a = eval('x+y') print("a", a) b = eval('x+y', {'x': 1, 'y': 2}) print("b", b) c = eval('x+y', {'x': 1, 'y': 2}, {'y': 3, 'z': 4}) print("c", c) func() 結果:a 30 b 3 c 4
a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]" print(type(a)) b = eval(a) print(type(b)) print(b) 結果:<class 'str'> <class 'list'> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
a = "{1: 'a', 2: 'b'}" print(type(a)) b = eval(a) print(type(b)) print(b) 結果:<class 'str'> <class 'dict'> {1: 'a', 2: 'b'}
a = "([1,2], [3,4], [5,6], [7,8], (9,0))" print(type(a)) b = eval(a) print(type(b)) print(b) 結果:<class 'str'> <class 'tuple'> ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
eval("__import__('os').system('ls /Users/chunming.liu/Downloads/')")
os.system('ls /Users/chunming.liu/Downloads/')
eval("__import__('os').system('cat /Users/chunming.liu/Downloads/tls_asimov_cert.pem')")
eval("__import__('os').system('rm /Users/chunming.liu/Downloads/車輛轉發測試.png')")
with open('test1.py','r') as f: exec(f.read())
exec(object[, globals[, locals]]]
globals = {'x': 7, 'y': 10, 'lis': ['aa', 'bb', 'cc']} locals = {} a = eval("3*x+4*y", globals, locals) print(a) exec("for i in lis: print(i)", globals, locals) 結果:61 aa bb cc
上述示例中exec()中至關於執行了python
globals = {'x': 7, 'y': 10, 'lis': ['aa', 'bb', 'cc']} for i in lis: print(i)