Good Place. Good Things. Good Time.

exec Python

exec Python

Introduction to exec Python

exec() is an inbuilt function or a method in python that enables dynamic execution of the raw code or open file object or code object given within the exec statement. The raw code is parsed, interpreted for errors as python code, and gets executed instantly, the file is also parsed till its last line and executed and the code object is executed as it is. The exec has two optional arguments in its format that allow global variables and local variables to control its execution. Though the effect of execution will be seen instantly, this method does not pass on any value to the other parts of the program.

Syntax of exec Python

Given below is the syntax mentioned:

Exec(object, Dictionary : global variables, Dictionary : local variables)

1. Object

It can be a string, file, or code object.

  • String: It is the code text provided in the exec statement. If this code is correct syntactically then it is converted as a temporary executable and gets executed instantly.
  • File: All the lines from the file are parsed and executed similar to the code explained above.
  • Code object: It is executed as provided.

2. Global Variables

These are the global parameters that has presence / control over the entire program. These global parameters restrict the execution of the code within the boundary values defined in Exec statement. These global variables are independent of any functions and are used globally anywhere in the program. It is only optional and default action will result in full access to all methods. Python enables users to pass on only the select methods the program need to access to and these lists of method can be passed as dictionary elements.

3. Local Variables

Local parameters have a presence within the function and it controls the operation of that function only. These local variables are defined within a function and the scope is restricted within the function. Developers can mention the list of methods the function can have access to and the list is given in the form of a dictionary. It is only optional and the default action will provide full access to all the methods in the called module.

How exec Works in Python with Examples

Given below shows how exec works in python with examples:

a. Exec independent of global and local parameters

Here there are no global or local parameters defined to restrict the access for the program or functions. The program works within the scope available.

Code 1: Simple code

# Sample code is run in the exec method
exec("print(' . ')")
exec("print('Welcome to First Exec program')")

Output:

exec Python 1

Code 2: To compute cube of 6

# Sample code is run in the exec method
exec("print(' . ')")
exec("print('Cube of 6 is ')")
exec("print(6**3)")

Output:

To compute cube of 6

Code 3: To call a function within exec

import math # importing Mathematics module
def square_root(l): # Function beginning
return math.sqrt(l) # Returning results
n = input("number ")
n=int(n)
print (" ")
exec("print ('square root of ',n, ' is ', square_root(n))")

Output:

To call a function within exec

b. The exec with global parameters

Code 1: Simple program without global parameters

from math import * # importing Mathematics module
exec ("print('Square Root of a number')")
exec("print (sqrt(64))")

Output:

The exec with global parameters

Code 2: No permission

The same program gets into error with no permission to execute any of the global module. The null ‘{}’ option in the global option stops permission to all excepting built-in functions.

from math import * # importing Mathematics module
exec ("print('Square Root of a number')")
exec("print (sqrt(64))",{})

Output:

No permission

Code 3: With permission given for sqrt this program runs successfully

from math import * # importing Mathematics module
exec ("print('Square Root of a number')")
exec("print (sqrt(64))",{"sqrt":sqrt})

Output:

exec Python 6

Code 4: With global permission given for factorial only, this program that calls sqrt fails

from math import * # importing Mathematics module
exec ("print('Square Root of a number')")
exec("print (sqrt(64))",{"factorial":factorial})

Output:

exec Python 7

Code 5: Dictionary listings without global parameters

The entire directory access is listed.

from numpy import * # importing numpy module
exec ("print (dir())")

Output:

Dictionary listings without global parameters

And ………….. so on…

Code 6: Dictionary listings with global parameters

from numpy import * # importing Mathematics module
exec ("print (dir())",{})

Output:

Access to builtins dictionary is only allowed.

exec Python 10

Within builtin function also specific controls can be applied like {“__builtins__” : None}

c. Exec with local parameters

If local parameters are not provided in the Exec statement, by default, all builtin parameters will be used as local parameters, but its scope will be limited within the function.

Code 1: Without global and local parameters works fine

import math # importing Mathematics module
def square_root(l): # Function beginning
return math.sqrt(l) # Returning results
exec("print ('square root of 64 is ', square_root(64))")

Output:

exec Python 11

Code 2: With nil permission to global and local parameters it fails

import math # importing Mathematics module
def square_root(l): # Function beginning
return math.sqrt(l) # Returning results
exec("print ('square root of 64 is ', square_root(64))",{},{})

Output:

nil permission to global and local parameters it fails

Code 3: With nil permission for global and limited permission for local it works fine

import math # importing Mathematics module
def square_root(l): # Function beginning
return math.sqrt(l) # Returning results
exec("print ('square root of 64 is ', square_root(64))",{__builtins__:None}, {"square_root":square_root})

Output:

exec Python 13

Permissions can be granted for local parameters and the scope can be restricted accordingly. Global and local parameters can be adjusted as per the requirements and exec function can be used to a great extent.

Conclusion

The exec is slightly risky if the program allows free option to user to choose their own code and execute. User may use them indiscreetly and eat away all the resources and cause performance glitch. Sometime it may lead to a system crash. Hence developers will have to be judicious in throwing this exec option to users to execute whatever they opt for.

Recommended Articles

This is a guide to exec Python. Here we discuss the introduction and how exec works in python with examples respectively. You may also have a look at the following articles to learn more –

  1.  BFS Algorithm Python
  2. Tree Traversal Python
  3. DFS Algorithm in Python
  4. Linked List in Python

The post exec Python appeared first on EDUCBA.

Read original article here: exec Python

Read original article here: exec Python



Disclaimers and Denial of responsibility..!

Denial of responsibility! TheTopMag.com is an automatic aggregator of all media around the world. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – jamesonline999@gmail.com . The content will be deleted within 72 hours.
You might also like
Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.