Python Execute String as Code

Document 对象参考手册Python3 Examples

Given a string of code, then use exec() to execute the string code.

Example 1: Using the built-in exec() method

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) exec_code()

Executing the above code produces the following output:

120

Document 对象参考手册Python3 Examples

Other Extensions