Exec () function in Python

The exec () function used to execute Python programs dynamically can be string or object code. How does exec () function syntax, what parameters do it have, and how is it used? Invites you to read the track.

Exec () function in Python Picture 1

The exec () function syntax in Python

 exec(doituong, global, local) 

The parameters of exec ():

Exec () has three parameters:

  1. doituong: a string or object code
  2. global: a dictionary that specifies methods and global variables available. Global is an optional parameter.
  3. local: a map object. Local is an optional parameter.

Global and local use will be analyzed by Quantrimang 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

5 ★ | 1 Vote

May be interested

  • Open source Python projects for beginnersPhoto of Open source Python projects for beginners
    where are the best open source python projects that can be learned? this is probably one of the most frequently asked questions that the 'newbie' feet wet to step into the world of python questions and learn.
  • How to use List comprehension in PythonPhoto of How to use List comprehension in Python
    you may have heard about python's list comprehension and may have used it without really understanding them. therefore, this article will introduce and guide you how to use list comprehension in python.
  • How to create a command line program in Python with ClickPhoto of How to create a command line program in Python with Click
    click is a python package to write command line interfaces with as little code as possible. this article will show you how to use click to create the command line program.
  • Code Python on the browser with these free online Python interpretersPhoto of Code Python on the browser with these free online Python interpreters
    you should use an interactive interactive shell. these are sites that allow you to write, execute python code and immediately see the results, without installing anything.
  • Array in PythonPhoto of Array in Python
    arrays are a fundamental part of all programming languages, it is a collection of elements of a single data type, for example, integer arrays, string arrays. however, in pythong, there is no original array data structure. so we use python lists instead of arrays.
  • Callable () function in PythonPhoto of Callable () function in Python
    callable () in python checks whether objects can be called. if the object is allowed to call, the function returns true, otherwise it returns false. how does the callable () function have the syntax, what parameters do we have, we will learn in this section.