📜  在Python中执行一串代码

📅  最后修改于: 2022-05-13 01:55:39.709000             🧑  作者: Mango

在Python中执行一串代码

给定字符串变量内的几行代码并执行字符串内的代码。
例子:

Input:
code = """ a = 6+5
           print(a)"""
Output:
11
Explanation:
Mind it that "code" is a variable and
not python code. It contains another code, 
which we need to execute.

Input:
code = """ def factorial(num):
               for i in range(1,num+1):
                   fact = fact*i
               return fact
           print(factorial(5))"""
Output:
120
Explanation:
On executing the program containing the 
variable in Python we must get the result 
after executing the content of the variable.

这里我们使用exec()函数来解决包含在变量中的代码。 exec()函数用于Python代码的动态执行。它可以采用包含Python语句的代码块,例如循环、类、函数/方法定义,甚至是 try/except 块。此函数不返回任何内容。下面的代码解决了这个问题并解释了 exec()函数。

Python3
# Python program to illustrate use of exec to
# execute a given code as string.
 
# function illustrating how exec() functions.
def exec_code():
    LOC = """
def factorial(num):
    fact=1
    for i in range(1,num+1):
        fact = fact*i
    return fact
print(factorial(5))
"""
    exec(LOC)
     
# Driver Code
exec_code()


输出:

120