Python Library has very powerful functions in actual operations

Source: Internet
Author: User

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.

 
 
  1. >>> code = """  
  2. def test(s):  
  3. print "test:", s  
  4. a = 123 
  5. """  
  6. >>> exec code  
  7. >>> a  
  8. 123  
  9. >>> test("abc")  
  10. 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.

 
 
  1. >>> a = 10 
  2. >>> x = eval("a + 3")  
  3. >>> x  
  4. 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.

 
 
  1. >>> x = eval("a + b", {}, {}) 

Pass a null value so that it cannot obtain local information

 
 
  1. Traceback (most recent call last):  
  2. File "<pyshell#21>", line 1, in <module> 
  3. x = eval("a + b", {}, {})  
  4. File "<string>", line 1, in <module> 
  5. NameError: name 'a' is not defined  
  6. >>> x = eval("a + b", {}, { "a":123, "b":2})   

Explicitly transfer environment information

 
 
  1. >>> x  
  2. 125  

The content of the above article is an introduction to the operations in the Python Library's actual application operations.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.