Movatterモバイル変換


[0]ホーム

URL:


Open In App

Given a string containing Python code, the task is to execute it dynamically.For example:

Input: "x = 5\ny = 10\nprint(x + y)"
Output: 15

Below are multiple methods to execute a string of Python code efficiently.

Using exec()

exec() function allows us to execute dynamically generated Python code stored in a string.

Python
code="x = 5\ny = 10\nprint(x + y)"exec(code)

Output
15

Explanation:

  • exec(code) executes the string code as Python code.
  • Variables x and y are created, and their sum is printed.

Using eval()

eval()function can execute a single expression stored in a string and return its result. It is more limited compared to exec() but can be useful for evaluating expressions.

Python
code="5 + 10"res=eval(code)print(res)

Output
15

Using compile() with exec() or eval()

compile() converts a string into a code object, which can then be executed multiple times using exec() or eval(). Useful when the same code is run repeatedly.

Python
code="x = 5\ny = 10\nprint(x + y)"res=compile(code,'<string>','exec')exec(res)

Output
15

Explanation:

  • compile(code, '<string>', 'exec') compiles the string into a code object.
  • exec(compiled_code) executes the compiled code.

Using subprocess module

If we want to execute the code in a separate process, we can use thesubprocess module. This is more suitable for executing standalone scripts or commands.

Python
importsubprocesscode="print(5 + 10)"subprocess.run(["python3","-c",code])

Output
15

Explanation:

  • subprocess.run([...]) runs a separate Python process.
  • -c flag allows passing code directly as a string.

C

Chinmoy Lenka GfG
Improve

C

Chinmoy Lenka GfG
Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp