**What's the use of this function? One of the simplest examples is our code, which will be read by the interpreter. The interpreter reads it as a string, and then it is compiled by compile and converted into python-recognizable code. .So python can be executed. **
**Here is an example, which is to compile a string of str into python code through compile. The details are as follows: **
Reference from http://www.cnblogs.com/wupeiqi/p/4592637.html
The content of this article can be seen from the title, which is to prepare for the subsequent analysis of the tornado template. It is also due to the clever use of this knowledge point, so I will use a separate article to introduce it. Not much nonsense, just go to the code:
#! usr/bin/env python
# coding:utf-8
namespace ={'name':'wupeiqi','data':[18,73,84]}
code ='''def hellocute():return "name %s ,age %d" %(name,data[0],) '''
func =compile(code,'<string>',"exec")
exec func in namespace
result = namespace['hellocute']()
print result
The execution result of this code is: name wupeiqi, age 18
Analysis of the above code:
In line 6, code is a string, and the content of the string is a function body.
Line 8, compile the code string into the function hello
In line 10, the function hello is added to the namespace dictionary (key is hello), and all built-in functions of python are added to the namespace field (key is builtins). In this way, the contents of the namespace are like one by one Global variables, namely
name = wupeiqi data = [18,73,84] def hellocute(): return "name %s ,age %d" %(name,data[0],)
Line 12, execute the Hello function and copy the return value to result
Line 14, enter result
This code is used very cleverly and blindly. It turns the string into a function and also provides global variables for the function. For this function, it is the most important part of the template language part of the python web framework, because in the template processing process, the html file is first read, then the html file is divided, and then the divided files form a string representation The function, and then the function that uses the above method to perform the string representation.
Recommended Posts