Python exec() Built in Function
The exec() function in Python is used to execute a dynamically generated code, which is a code that is created or modified at runtime. The exec() function takes a string or an object that contains a valid Python code and executes it as if it was written in a file. You can also pass a dictionary of global and local variables to the exec() function to modify the execution environment. Here are some examples of using exec() in Python:
Execute a Python statement stored as a string:
code = 'print("Hello, world!")'
exec(code)
Output: Hello, world!
In this example, exec(code) executes the Python statement 'print("Hello, world!")', which prints the string "Hello, world!" to the console.
Use exec() to execute a Python script stored in a file:
with open('script.py', 'r') as file:
code = file.read()
exec(code)
In this example, we open the file 'script.py', read its contents into a string, and then use exec() to execute the code in that string. This allows you to run Python scripts stored in files from within another Python script.
Use exec() to execute arbitrary code entered by the user:
code = input("Enter some Python code: ")
exec(code)
In this example, we prompt the user to enter some Python code, and then use exec() to execute that code. This allows the user to enter arbitrary Python code and have it executed, which can be useful for interactive exploration and experimentation. However, as mentioned earlier, this is potentially dangerous if the input is not trusted.
Some more examples:
# Execute a simple expression
x = 10
y = 20
code = "z = x + y"
exec(code)
print(z) # Output: 30
# Execute a user input
code = input("Enter some Python code: ")
exec(code)
# For example, if you enter print("Hello World"), it will print Hello World
# Execute a code with global and local variables
global_var = {"x": 5}
local_var = {"y": 10}
code = "z = x * y"
exec(code, global_var, local_var)
print(global_var["z"]) # Output: 50
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment