The following article describes how to operate Python Library in practice through the introduction of Python Library: Exec & Compile's actual operation code. The following is a detailed introduction to the article, I hope you will gain some benefits after reading the following articles.
Running code strings directly is also an important feature of dynamic languages. Although similar functions can be implemented through CodeDom in. NET/C #, it is far less convenient and free than Python.
- >>> code = """
- def test(s):
- print "test:", s
- a = 123
- """
- >>> exec code
- >>> a
- 123
- >>> test("abc")
- test: abc
Built-in functions, eval () and execfile (), are used to do similar things. The exec keyword executes multi-line code snippets. The eval () function is usually used to execute an expression containing the returned value, while the execfile is used to execute the source code file.
- >>> a = 10
- >>> x = eval("a + 3")
- >>> x
- 13
Both eval () and execfile () have the "globals, locals" parameter, which is used to pass environment variables. globals () and locals () are directly used by default or explicitly set to None () obtain the data of the current scope.
- >>> x = eval("a + b", {}, {})
Pass a null value so that it cannot obtain local information
- Traceback (most recent call last):
- File "<pyshell#21>", line 1, in <module>
- x = eval("a + b", {}, {})
- File "<string>", line 1, in <module>
- NameError: name 'a' is not defined
- >>> x = eval("a + b", {}, { "a":123, "b":2})
Explicitly transfer environment information
- >>> x
- 125
The content of the above article is an introduction to the operations in the Python Library's actual application operations.