Execute Python Code from a String
Executing code stored in a string is useful in various scenarios. Python provides two approaches for this purpose.
Using exec() for Statements
For statements, use the exec() function or the exec statement (for Python 2). These evaluate a string containing Python code and execute it.
my_code = 'print("Hello world")' exec(my_code)
After execution, the code in the string will be performed, resulting in output such as:
Hello world
Using eval() for Expressions
When you need to obtain the value of an expression, use the eval() function. This evaluates a string containing an expression and returns the result.
x = eval("2+2") print(x) # Output: 4
Cautionary Note:
However, blindly executing code from a string is generally discouraged due to potential security risks and bad programming practice. Carefully consider whether there are alternative approaches that are more efficient and secure.
The above is the detailed content of How Can I Execute Python Code from a String?. For more information, please follow other related articles on the PHP Chinese website!