Python basis: dynamic run python code

Paper come Zhongjue know this practice is essential. ------ Lu Song "winter reading shows sub Yu"

I. Introduction

In practice, we do not know the actual needs of the implementation of a program that, in order to ensure flexibility, we need to dynamically generate code and then execute, so today simply summarize using python execute python code.

Second, prior knowledge points

Trying to dynamically execute Python scripts, you need to know how to string or file content into python and identify the instructions. Implementation code dynamically loaded and executed, can use the eval () and exec () function.

2.1.eval () function

eval () function is used to perform a string expression, and returns the value of the expression. The syntax is as follows:

eval(expression, globals=None, locals=None)
  • expression - expression.
  • globals - variable scope, global namespace, if provided, it must be a dictionary object.
  • locals - variable scope, the local name space, if provided, may be any map object.

Note: Python code that it performs only a single arithmetic expression ( note eval does not support any form of assignment ), not a complex code logic, and it is quite similar to lambda expressions.

2.2.exec () function

exec () execute Python statements which are stored in a file or string compared to eval, exec can perform more complex Python code.

exec(object[, globals[, locals]])
  • object: Required parameter indicates Python code needs to be specified. It must be a string or code objects. If the object is a string that will first be resolved to a set of Python statement, and then execute (unless a syntax error occurs). If the object is a code object, it is just a simple execution.
  • globals: optional parameter represents the global name space (to store global variables), if provided, must be a dictionary object.
  • locals: an optional parameter that indicates the current local namespace (store local variables), if provided, may be any map object. If this parameter is ignored, then it will take the globals the same value.

exec return value is always None.

2.3.eval use and differences with exec

  • eval () function only Calcd single expression, whereas exec () function can be dynamically run code segments.
  • eval () function can return a value, and exec () function returns the value is always None.

Third, the implementation of dynamic Detailed python

There are several ways to perform dynamic python simple list what are the following categories:

  1. The implementation of a single line of python statement string
  2. Python execute statement blocks of multiple lines of code
  3. Perform functions
  4. Dynamic Execution python file

Now we explain the use of it one by one.

3.1. Perform his string expression

If his string expression is performed, it may be used eval () and exec () function, but the exec () method does not return a result. Examples used here only demonstrate eval () methods:

def print_str():
    eval("print('hello world')")

def add(x, y):
    return eval("x+y")

if __name__ == "__main__":
	print_str()
    print(add(12, 56))

Execution results are as follows:
Here Insert Picture Description

3.2. Block of code

If you are performing multi-line string expression, eval () is not a lot of use, eval does not support any form of assignment. So to use the exec () method.

expr = """
count = 10
for index in range(count):
    print(index)
"""

def eval_code():
    eval(expr)

def exec_for():
    exec(expr)

if __name__ == "__main__":
    exec_for()
    # eval_for()  # 这样写会报错

Presentation as follows:
Here Insert Picture Description

3.3. Execution function

In fact, there is no difference and perform other functions, eval () and exec () function can be used

def print_str():
    eval("print('hello world')")

def eval_fun():
    eval("print_str()")

def exec_fun():
    exec("print_str()")

if __name__ == "__main__":
    eval_fun()
    exec_fun()

Results are as follows:
Here Insert Picture Description

3.4. Execution .py file

Sometimes we need to perform a py file, then use the exec () function can be used, in fact, there is a execfile () built-in functions can be achieved in the implementation of python file in Python2, but in the python3 has been removed method. You can only use the exec () execute python file.

def exec_file(file_name, func_name):
    with open(file_name, "rb") as f:
        source_code = f.read()
    exec_code = compile(source_code, file_name, "exec")
    scope = {}
    exec(exec_code, scope)
    f = scope.get(func_name, None)
    f()

if __name__ == "__main__":
    exec_file(文件名, 方法名)

Fourth, real

# -*- coding: utf-8 -*-
# 动态执行python
expr = """
count = 10
for index in range(count):
    print(index)
"""
def print_str():
    eval("print('hello world')")

def add(x, y):
    return eval("x+y")


def eval_for():
    eval(expr)


def exec_code():
    exec("print('hello world')")


def exec_for():
    exec(expr)


def eval_fun():
    eval("print_str()")


def exec_fun():
    exec("print_str()")


def exec_file(file_name, func_name):
    with open(file_name, "rb") as f:
        source_code = f.read()
    exec_code = compile(source_code, file_name, "exec")
    scope = {}
    exec(exec_code, scope)
    f = scope.get(func_name, None)
    f()


if __name__ == "__main__":
    # print_str()
    # print(add(12, 56))
    # exec_fun()
    # sum = add(12, 45)
    # print("sum=", sum)
    # exec_for()
    # eval_for()
    eval_fun()
    exec_fun()
    # 我测试的使用使用的我的博客的文件名,大家可以去我的博客里面取
    # https://blog.csdn.net/m1090760001/article/details/103329077
    # exec_file("seleniumblog.py", "open_blog")
Published 19 original articles · won praise 67 · views 20000 +

Guess you like

Origin blog.csdn.net/m1090760001/article/details/103336519