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
Susan SarandonOriginal
2024-12-16 05:05:101049browse

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)

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!

Statement:
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