Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

Exec ()() Function in Python

Explore Exec ()() Function in Python with clear explanations, practical examples, and useful tips.

Table of Contents

This guide covers exec ()() function in python with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.

The Exec ()() Function Syntax in Python

exec(doituong, global, local)

The parameters of exec ():

Exec () Has three parameters:

  • Doituong: A string or object code
  • Global: A dictionary that specifies methods and global variables available. Global is an optional parameter.
  • Local: A map object. Local is an optional parameter.

Global And local use will be analyzed by TipsMake later in this article.

Example 1: How Does Exec ()() Function?

# ???c vi?t b?i TipsMake.com
program = 'a = 5nb=10nprint("T?ng =", a+b)'
exec(program)

Run the program, the result is:

T?ng = 15

In this example, the object string is passed into Exec (), The global and local parameters are ignored in this case.

Example 2: Allow Users to Enter Input

program = input('Enter a program:')
exec(program)

Run the program, the result is:

Enter a program: [print(item) for item in [1, 2, 3]]
1
2
3

If you want to get Python code from users, you can use the Compile () Function before using Exec ().

You should be careful when using exec!

You need to pay a little attention if you are using a Unix system like macOS, Linux. And perform the functions of the os module. The os module is built to provide methods to help you create, delete, and change folders.

If you then enter the value as Exec (input ()), The user may have problems changing the file even if it deletes the file with the Os. System ('rm -rf *') command.

So if you use Exec (input ()) In your code, it is reasonable to check which variables and methods you can use. You should do this with the function Dir ().

from math import *
exec('print(dir())' ) 

Running the code and the resulting result will look like this:

['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', 
 '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 
 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 
 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 
 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 
 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

The Case Does Not Pass Global and Local Parameters

When using Exec () Without passing these two parameters as the examples above, the expression will be executed in the current scope. You can check the variables and methods available with Dir () As mentioned above.

Where to Pass Global Parameters and Ignore Local

Global And Local (dictionary) parameters are used for global and local variables respectively. If dictionary local is omitted, this default parameter program is Global. That is, Global Will be used for both global and local variables.

You can check local and global dictionary with Global () And Local () Built-in functions ()

Example: Transfer an empty dictionary to the global parameter

from math import *
exec('print(dir())', {})

# Code d??i ?ây s? x?y ra exception
# print(exec('sqrt(25)', {}))

If you pass a blank dictionary into the global, only the __builtins__ Function is valid for doituong. You will not be able to access any function of the math module even though you have imported the math module into the program above.

Run the program, the result is:

['__builtins__']

In this example, the expression can use the Sqrt () And Pow () functions Together with __builtins__.

from math import *
exec('print(dir())', {'sqrt': sqrt, 'pow': pow})

exec('print(sqrt(9))', {'sqrt': sqrt, 'pow': pow})

Alternatively, you can change the name of the available method for your desired expression.

from math import *
exec('print(dir())', {'canbachai': sqrt, 'pow': pow})

# object can have canbachai() module
exec('print(canbachai(9))', {'canbachai': sqrt, 'pow': pow})

The Case Transmits Both Global and Local Parameters

from math import *

globalsParameter = {'__builtins__' : None}
localsParameter = {'print': print, 'dir': dir}
exec('print(dir())', globalsParameter, localsParameter)

Run the program, the result is returned

['dir', 'print']

Here, only the Print () And Dir () Built-in functions can be executed by the Exec () Function .

The important thing to note is that Exec () Executes but does not return any values (returns None). Therefore, you cannot use Return And Yield statements Outside of defined functions.

Last lesson: float () function in Python

Next lesson: Hex () function in Python

FAQ

What should I check before following these steps?

Confirm device and software compatibility, save important data, and make sure you have the required permissions, files, and account access.

Why might the process not work?

Common causes include outdated software, missing permissions, incompatible hardware, an unstable connection, or completing a step in the wrong order.

Can I undo the changes if necessary?

That depends on the tool or setting. Use built-in restore options when available, keep a backup, and record the original configuration first.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.