Python in two Artifact & exec () & eval ()

An artifact 1-- built-in function eval

eval function is built in the python, its role is changed corresponding to the character string expression, also corresponds to a function code string becomes double quotation marks, the eval function corresponding to the string to turn it there in the course of absolute advantage, but there is also the risk of use, so use the right in the program, I suggest not to use

eval The syntax is as follows:

eval(expression[, globals[, locals]])
expression: String
globals: variable scope, global namespace, if provided, must be a dictionary object.
locals: variable scope, the local name space, if provided, may be any map object.

Combined with globals and locals look at a few examples

Globals transmitted parameter value { "age": 1822},
b = eval("{'name':'linux','age':age}",{"age":1822})
print(b)

结果:{‘name’: ‘linux’, ‘age’: 1822}
Coupled with the locals variables
age=18
b = eval("{'name':'linux','age':age}",{"age":1822},locals())
print(b)

结果:{'name': 'linux', 'age': 18}

It can be seen from the above examples:

When only global variables globals, do not use local variables locals, to find whether there is a global variable, if there is a global variable
If you use both global and local, local locals first search of the variables, followed by looking in globals global variables, local variables of the same name parameter overrides the value of the global variables in, follow the value of the order (Local -> Global -> Built-in )

The power of place 1.eval

Change the value of a variable

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

eval function to achieve conversion between the list, dict, tuple with str

String into a list b = eval ( "[[1,2], [3,4], [5,6], [7,8], [9,0]]")
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]]
String into a dictionary b = eval ( "{1: 'a', 2: 'b'}")
a = "{1: 'a', 2: 'b'}"
print(type(a))
b = eval(a)
print(type(b))
print(b)

结果:<class 'str'>
     <class 'dict'>
     {1: 'a', 2: 'b'}
String into a tuple b = eval ( "([1,2], [3,4], [5,6], [7,8], (9,0))")
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))

As can be seen from the above example, a string to eval, eval expression that returns to a value, which is its advantage

2.eval dangerous place

eval is convenient, but be aware that security can be converted into a string expression and execution, you can use to perform system commands to delete files and other operations.
When the user of the danger of it is not clear, enter the following:
eval("__import__('os').system('ls /Users/chunming.liu/Downloads/')")
It is actually executed is as follows
os.system('ls /Users/chunming.liu/Downloads/')
Then continue typing:
eval("__import__('os').system('cat /Users/chunming.liu/Downloads/tls_asimov_cert.pem')")
Again a delete command, the file will disappear. such as
eval("__import__('os').system('rm /Users/chunming.liu/Downloads/车辆转发测试.png')")
So use eval, on the one hand to enjoy his flexibility, we must also pay attention to safety.

Second, artifact 2 - built-in function exec ()

deleting the python3 the execfile () method, using the Exec (), it can perform complex code:

with open('test1.py','r') as f:
    exec(f.read())

exec format syntax is as follows:

exec(object[, globals[, locals]]]
object: Required parameter indicates python code needs to be specified, it must be a string or code objects. If the object is a string, the string will be parsed into a first set of python statement, and then execute. If the object is a code object, it is just a simple execution
globals: optional parameter, with the eval function
locals: optional parameter, with the eval function
return value:
The return value of the function is always None exec
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

Corresponds to the above-described example exec () is executed

globals = {'x': 7, 'y': 10, 'lis': ['aa', 'bb', 'cc']}

for i in lis:    
    print(i)

I am here with you to talk about the difference between function and exec () function eval ():

eval () function only Calcd a single expression, but () function can be dynamically run code segment exec

eval () function can return a value, and the exec () function returns the value is always None

Guess you like

Origin www.cnblogs.com/shenhongbo/p/11566596.html