Exec and eval instances in Python, pythoneval

Source: Internet
Author: User

Exec and eval instances in Python, pythoneval

Through exec, You can execute dynamic Python code, similar to the eval function of Javascript. The eval function in Python can calculate the Python expression and return the result (exec does not return the result, print (eval ("... ") Print None );
Copy codeThe Code is as follows:
>>> Exec ("print (\" hello, world \")")
Hello, world

>>> A = 1
>>> Exec ("a = 2 ")
>>>
2

There is a scope (namespace, scope) concept here. In order not to break the current scope, you can create a scope (a dictionary) to execute exec (Javascript does not have this function ):

Copy codeThe Code is as follows:
>>> Scope = {}
>>> Exec ("a = 4", scope)
>>>
2
>>> Scope ['a']
4

>>> Scope. keys ()
Dict_keys (['A', '_ builtins _'])

_ Builtins _ contains all built-in functions and values;

The common {} does not contain _ builtins __
Copy codeThe Code is as follows:
>>> A = {}
>>> A. keys ()
Dict_keys ([])

Like exec, eval can also use the namespace:

Copy codeThe Code is as follows:
>>> Result = eval ('2 + 3 ')
>>> Result
5
>>> Scope = {}
>>> Scope ['a'] = 3
>>> Scope ['B'] = 4
>>> Result = eval ('a + B ', scope)
>>> Result
7


How to obtain the python exec eval running result

Hfile = file ("f:/1.txt"," r ") # f:/1.txt: 1 + 1 string = hfile. readline () retStr = eval (string) print retStr

In python, how does one convert an int to the name of an existing object?

A = 2

Print eval ("a % s" %)

A is the number entered by the user.

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.