Open In App

Execute a String of Code in Python

Last Updated : 21 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given few lines of code inside a string variable and execute the code inside the string. 
Examples: 
 

Input:
code = """ a = 6+5
           print(a)"""
Output:
11
Explanation:
Mind it that "code" is a variable and
not python code. It contains another code, 
which we need to execute.

Input:
code = """ def factorial(num):
               for i in range(1,num+1):
                   fact = fact*i
               return fact
           print(factorial(5))"""
Output:
120
Explanation:
On executing the program containing the 
variable in Python we must get the result 
after executing the content of the variable.

Here we use the exec() function to solve the code contained inside a variable. exec() function is used for the dynamic execution of Python code. It can take a block of code containing Python statements like loops, class, function/method definitions and even try/except block. This function doesn’t return anything. The code below solves the problem and explains the exec() function. 
 

Python3




code = '"hello" + "world"'
result = eval(code)
print(result)  # Output: "hello world"
 
code = '["a", "b", "c"][1]'
result = eval(code)
print(result)  # Output: "b"


Output: 
 

120

Use eval()
 

Another approach to execute a string of code in Python is to use the eval() function. This function is similar to exec(), but it evaluates a string of code and returns the result.

Here is an example of using eval() to execute a string of code:

Python3




import types
 
code_string = "a = 6+5"
my_namespace = types.SimpleNamespace()
exec(code_string, my_namespace.__dict__)
print(my_namespace.a)  # 11


 Output:

11

Time Complexity: O(1)

Auxiliary space: O(1)

Like exec(), eval() can be used to evaluate any valid Python expression, not just simple arithmetic operations. For example:

Python3





Output:

helloworld
b

Note that eval() can be a security risk if you are evaluating code from an untrusted source, as it allows the execution of any Python expression. In such cases, it is recommended to use exec() instead, or to parse the code and evaluate it piece by piece in a controlled manner.

METHOD 3:Using a custom Namespace.

APPROACH:

This code executes the string “a = 6+5” using exec() and stores the resulting variable a in a SimpleNamespace object called my_namespace. It then prints the value of my_namespace.a, which is 11.

ALGORITHM:
1.Define the code string “a = 6+5”.
2.Create a SimpleNamespace object called my_namespace.
3.Execute the code string using exec() and store the resulting variable in my_namespace.
4.Print the value of my_namespace.a’.

Python3




import types
 
code_string = "a = 6+5"
my_namespace = types.SimpleNamespace()
exec(code_string, my_namespace.__dict__)
print(my_namespace.a)  # 11


Output

11

Time complexity: The time complexity of this code is O(1) as it involves a simple assignment and print statement. The time complexity of exec() function will depend on the complexity of the code string being executed.

Space complexity: The space complexity of this code is O(1) as it only uses a few variables (code_string, my_namespace, and the a variable created by executing the code string). The space complexity of exec() function will depend on the size and complexity of the code string being executed.



Similar Reads

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 parts: The kernel and the Shell. The kernel basically
6 min read
Python - Measure time taken by program to execute
This article aims to show how to measure the time taken by the program to execute. Calculating time helps to optimize your Python script to perform better. Approach #1 : A simple solution to it is to use time module to get the current time. The following steps calculate the running time of a program or section of a program. Store the starting time
2 min read
Menu driven Python program to execute Linux commands
Linux is one of the most popular operating systems and is a common choice for developers. However, it is difficult to remember the vast range of commands that Linux supports, and hence a Python program that can run these commands easily is demonstrated below. In this article, we will deal with a Python program that can be used to run complex Linux
3 min read
How to execute a 11-digit instruction using different addressing modes in Python?
Here, we have an 11 bit instruction which has first 2 bits for representing addressing mode, next 3 bits for the opcode and the last 6 bits are for the two operands, 3 bits each. We will execute this 11 bit Instruction using four different addressing modes:- Direct mode: In this mode, the addresses of two operands are specified in the instruction.
4 min read
How to Execute Shell Commands in a Remote Machine in Python?
Running shell commands on a Remote machine is nothing but executing shell commands on another machine and as another user across a computer network. There will be a master machine from which command can be sent and one or more slave machines that execute the received commands. Getting Started We will be using Websocket protocol to send shell comman
3 min read
How to Execute a Script in SQLite using Python?
In this article, we are going to see how to execute a script in SQLite using Python. Here we are executing create table and insert records into table scripts through Python. In Python, the sqlite3 module supports SQLite database for storing the data in the database. Approach Step 1: First we need to import the sqlite3 module in Python. import sqlit
2 min read
How to Execute many SQLite Statements in Python?
In SQLite using the executescript() method, we can execute multiple SQL statements/queries at once. The basic execute() method allows us to only accept one query at a time, so when you need to execute several queries we need to arrange them like a script and pass that script to the executescript() method. executescript() can be able to execute seri
3 min read
How to Execute Shell Commands in a Remote Machine using Python - Paramiko
Paramiko is a Python library that makes a connection with a remote device through SSh. Paramiko is using SSH2 as a replacement for SSL to make a secure connection between two devices. It also supports the SFTP client and server model. Authenticating SSH connection To authenticate an SSH connection, we need to set up a private RSA SSH key (not to be
4 min read
How to Execute a SQLite Statement in Python?
In this article, we are going to see how to execute SQLite statements using Python. We are going to execute how to create a table in a database, insert records and display data present in the table. In order to execute an SQLite script in python, we will use the execute() method with connect() object: connection_object.execute("sql statement") Appr
2 min read
Execute PostgreSQL Stored Procedure and Function in Python
A stored procedure is a sequence of structured procedural language queries stored in a relational database management system as a data dictionary, which can be shared and reused multiple times. All CRUD operations, querying operations can be performed by calling the stored procedure. The use of stored procedures reduces the repetition of code that
3 min read
Practice Tags :