Home > Backend Development > Python Tutorial > How Can I Execute Python Code from a String?

How Can I Execute Python Code from a String?

Susan Sarandon
Release: 2024-12-16 05:05:10
Original
993 people have browsed it

How Can I Execute Python Code from a String?

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)
Copy after login

After execution, the code in the string will be performed, resulting in output such as:

Hello world
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template