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) Output15 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 ContentUsing eval()Using compile() Using subprocess moduleUsing 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) Output15 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) Output15 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 moduleIf 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]) Output15 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. Comment More infoAdvertise with us Next Article Execute a String of Code in Python C Chinmoy Lenka Improve Article Tags : Misc Python python-utility Python string-programs Practice Tags : Miscpython Similar Reads 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 s 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: Python3 # Python program to demonstrate # string # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World' 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 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.Pythonn = 42 s = str(n) p 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 StringIO Module in Python StringIO is a module in Python that allows you to treat strings as file-like objects. It provides an in-memory stream for text I/O (input/output), which means you can read from and write to a string just like you would with a file, but without disk I/O. To use StringIO, you need to import it from th 4 min read Multiline String in Python A sequence of characters is called a string. In Python, a string is a derived immutable data typeâonce defined, it cannot be altered. To change the strings, we can utilize Python functions like split, join, and replace.Python has multiple methods for defining strings. Single quotations (''), double 4 min read Executing Shell Commands with Python This article starts with a basic introduction to Python shell commands and why one should use them. It also describes the three primary ways to run Python shell commands.os.system()subprocess.run()subprocess.Popen() What is a shell in the os?In programming, the shell is a software interface for acce 4 min read Call a function by a String name - Python In this article, we will see how to call a function of a module by using its name (a string) in Python. Basically, we use a function of any module as a string, let's say, we want to use randint() function of a random module, which takes 2 parameters [Start, End] and generates a random value between 3 min read Like