Home > Article > Backend Development > Python built-in function——exec
Python built-in function - exec
xecexec(object[, globals[, locals]])
This function is to execute a statement or function.
The parameter object is a string statement or the object name of a compiled statement.
The parameter globals is the global namespace, used to specify the global namespace that can be accessed when executing the statement;
The parameter locals is the local namespace, used to specify the namespace of the local scope that can be accessed when executing the statement.
Please note that this function will not return any value, regardless of whether the function or statement has any return value statement, such as return or yield statement.
If the parameters globals and locals are ignored, the namespace in which the call is made will be used.
Both parameters are required to be in dictionary form to describe the namespace.
We have learned functions such as compile and eval before, so what are the differences between them?
You can simply think of their differences as follows:
compile函数是只编译字符串代码,而不作任何的执行,但它可以编译表达式或语句。 eval函数是**只执行表达式字符串代码,而不执行语句代码。** x = eval('%d + 6' % x) exec函数是**只执行语句代码,而不执行表达式代码**,因为它没有任何返回值。 exec('if True: print(6)') >>> exec('if True: print 100') 100 >>> exec(''' x = 200 if x>100: print x+200 ''') 400
The above is the content of Python’s built-in function-exec. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!