Python built-in function——exec

黄舟
Release: 2017-01-19 16:37:23
Original
1732 people have browsed it

Python built-in function - exec

xecexec(object[, globals[, locals]])
Copy after login

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
Copy after login

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)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!