Thursday, July 4, 2024
HomeLanguagesPythonExecute a String of Code in Python

Execute a String of Code in Python

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




# Python program to illustrate use of exec to
# execute a given code as string.
 
# function illustrating how exec() functions.
def exec_code():
    LOC = """
def factorial(num):
    fact=1
    for i in range(1,num+1):
        fact = fact*i
    return fact
print(factorial(5))
"""
    exec(LOC)
     
# Driver Code
exec_code()


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




code = '6+5'
result = eval(code)
print(result)  # Output: 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




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


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.

This article is contributed by Chinmoy Lenka. If you like Lazyroar and would like to contribute, you can also write an article using write.neveropen.co.za or mail your article to review-team@neveropen.co.za. See your article appearing on the Lazyroar main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

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.

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments