Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python String Module
Next article icon

Execute a String of Code in Python

Last Updated : 10 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, we encounter situations where a Python program needs to dynamically execute code stored as a string. We will explore different ways to execute these strings safely and efficiently.

Using the exec function

exec() function allows us to execute dynamically generated Python code stored in a string. It is the most straightforward and commonly used method for this purpose.

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

Output
15 

Explanation:

  • exec() function takes the string of code as an argument and executes it as Python code.
  • variables x and y are created and their sum is printed.
  • This method is simple and works well for executing multiple lines of code stored as a string.

Let’s explore some more methods and see how we can execute a string of code in Python.

Table of Content

  • Using eval()
  • Using compile()
  • Using subprocess module

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 

Explanation:

  • eva() function evaluates the string as a Python expression and returns the result.
  • This method is ideal for scenarios where we only need to execute and get the result of a single expression.

Using compile()

compile() function can be used to compile a string of code into a code object, which can then be executed using exec() or eval(). This is useful for advanced use cases where we need more control.

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

Output
15 

Explanation:

  • compile() function converts the string of code into a code object.
  • exec() function is then used to execute the compiled code object.
  • This method is useful for scenarios where we need to compile the code once and execute it multiple times.

Using subprocess module

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

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

Output
15 

Explanation:

  • The subprocess.run function is used to execute the string of code as a separate Python process.
  • The -c flag allows us to pass the code string directly to the Python interpreter.
  • This method is useful when we need isolation or want to execute the code in a separate environment.


Next Article
Python String Module
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Python
  • Python string-programs
  • python-utility
Practice Tags :
  • python

Similar Reads

  • Convert Hex to String in Python
    Hexadecimal (base-16) is a compact way of representing binary data using digits 0-9 and letters A-F. It's commonly used in encoding, networking, cryptography and low-level programming. In Python, converting hex to string is straightforward and useful for processing encoded data. Using List Comprehen
    2 min read
  • Python String Concatenation
    String concatenation in Python allows us to combine two or more strings into one. In this article, we will explore various methods for achieving this. The most simple way to concatenate strings in Python is by using the + operator. Using + OperatorUsing + operator allows us to concatenation or join
    3 min read
  • Convert String to Int in Python
    In Python, converting a string to an integer is important for performing mathematical operations, processing user input and efficiently handling data. This article will explore different ways to perform this conversion, including error handling and other method to validate input string during conver
    3 min read
  • Python String Module
    The string module is a part of Python's standard library and provides several helpful utilities for working with strings. From predefined sets of characters (such as ASCII letters, digits and punctuation) to useful functions for string formatting and manipulation, the string module streamlines vario
    4 min read
  • Collections.UserString in Python
    Strings are the arrays of bytes representing Unicode characters. However, Python does not support the character data type. A character is a string of length one. Example: C/C++ Code # Python program to demonstrate # string # Creating a String # with single Quotes String1 = 'Welcome to the Geeks Worl
    2 min read
  • Python String index() Method
    The index() method in Python is used to find the position of a specified substring within a given string. It is similar to the find() method but raises a ValueError if the substring is not found, while find() returns -1. This can be helpful when we want to ensure that the substring exists in the str
    2 min read
  • Python | Execute and parse Linux commands
    Prerequisite: Introduction to Linux Shell and Shell Scripting Linux is one of the most popular operating systems and is a common choice for developers. It is popular because it is open source, it's free and customizable, it is very robust and adaptable. An operating system mainly consists of two par
    6 min read
  • Python String center() Method
    center() method in Python is a simple and efficient way to center-align strings within a given width. By default, it uses spaces to fill the extra space but can also be customized to use any character we want. Example: [GFGTABS] Python s1 = "hello" s2 = s1.center(20) print(s2) [/GFGTABS]Ou
    2 min read
  • Convert integer to string in Python
    In this article, we’ll explore different methods for converting an integer to a string in Python. The most straightforward approach is using the str() function. Using str() Functionstr() function is the simplest and most commonly used method to convert an integer to a string. [GFGTABS] Python n = 42
    2 min read
  • f-strings in Python
    Python offers a powerful feature called f-strings (formatted string literals) to simplify string formatting and interpolation. f-strings is introduced in Python 3.6 it provides a concise and intuitive way to embed expressions and variables directly into strings. The idea behind f-strings is to make
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
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