Python built-in functions (20) -- exec, python built-in function exec
English document:
-
exec(
Object[,
Globals[,
Locals])
-
This function supports dynamic execution of Python code.
ObjectMust be either a string or a code object. if it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs ). [1] If it is a code object, it is simply executed. in all cases, the code that's executed is expected to be valid as file input (see the section "File input" in the Reference Manual ). be aware that
returnAnd
yieldStatements may not be used outside of function definitions even within the context of code passed to
exec()Function. The return value is
None.
-
In all cases, if the optional parts are omitted, the code is executed in the current scope. If only
GlobalsIs provided, it must be a dictionary, which will be used for both the global and the local variables. If
GlobalsAnd
LocalsAre given, they are used for the global and local variables, respectively. If provided,
LocalsCan be any mapping object. Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects
GlobalsAnd
Locals, The code will be executed as if it were embedded in a class definition.
-
If
GlobalsDictionary does not contain a value for the key
__builtins__, A reference to the dictionary of the built-in module
builtinsIs inserted under that key. That way you can control what builtins are available to the executed code by inserting your own
__builtins__Dictionary
GlobalsBefore passing it
exec().
-
Note
-
The built-in functions
globals()And
locals()Return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument
exec().
-
Note
-
The default
LocalsAct as described for function
locals()Below: modifications to the default
LocalsDictionary shocould not be attempted. Pass an explicit
LocalsDictionary if you need to see effects of the code on
LocalsAfter function
exec()Returns.
-
Note:
-
-
1. the exec function is similar to the eval function and also executes dynamic statements, except that the eval function is only used to evaluate the execution expression, while the exec function is mainly used to execute statement blocks.
>>> Eval ('a = 1 + 2') # Traceback (most recent call last): File "<pyshell #0>", line 1, in <module> eval ('a = 1 + 2') File "<string>", line 1 a = 1 + 2 ^ SyntaxError: invalid syntax >>> exec ('a = 1 + 2') # execute the statement >>> a3
2. The first parameter is the statement string. The globals parameter and locals parameter are optional parameters. If provided, the globals parameter must be a dictionary and the locals parameter is a mapping object.
3. The globals parameter is used to specify global variables that can be used during code execution and to collect global variables after code execution.
>>> G = {'num': 2 }>>> type (g) <class 'dict '>>> exec ('num2 = num + 2 ', g) >>> g ['num'] 2 >>> g ['num2'] # collects the num2 global variable 4 defined in exec.
4. The locals parameter is used to specify the local variables that can be used during code execution and to collect the local variables after code execution.
>>> G = {'num': 2 }>>> type (g) <class 'dict '>>>> l = {'num2 ': 3 }>>> type (l) <class 'dict '>>>> exec (''' num2 = 13num3 = num + num2', g, l) >>> l ['num2'] # The num2 value in l has changed 13
5. To ensure successful code running, the globals parameter dictionary does not contain_ Builtins __Python automatically adds a key_ Builtins __Value is the reference of the builtins module. If you want to restrict the code from using the builtins module, you must add a key in global_ Builtins __, the value is {} (few do this ).
>>> G ={}>> exec ('a = abs (-1) ', g) >>>>> g = {'_ builtins _': {}}>>> exec ('a = abs (-1) ', g) # You cannot use the built-in function Traceback (most recent call last): File "<pyshell #30>", line 1, in <module> exec ('a = abs (-1) ', g) File "<string>", line 1, in <module> NameError: name 'abs' is not defined
6. If the globals parameter is not provided, Python uses the dictionary returned by the globals () function by default. If the locals parameter is not provided, the globals parameter is used by default.
>>> Num = 1 >>> exec ('num2 = num + 1') >>> globals () {'_ package _': None, '_ loader _': <class '_ frozen_importlib.BuiltinImporter'>, '_ name _': '_ main _', '_ spec __': none, '_ builtins _': <module 'builtins '(built-in)>,' _ doc _ ': None, 'num2': 2, 'num': 1 }>>>>>>>> exec ('num2 = num + 1', {}) # specify the globals parameter, traceback (most recent call last): File "<pyshell #5>", line 1, in <module> exec ('num2 = num + 1', {}) File "<string>", line 1, in <module> NameError: name 'num' is not defined >>> l = locals () >>> l {'_ package _': None, '_ loader __': <class '_ frozen_importlib.BuiltinImporter'>, '_ name _': '_ main _', '_ spec _': None, '_ builtins _': <module 'builtins '(built-in)>,' _ doc _ ': None, 'L ':{...}, 'num2': 2, 'num': 1 }>>>>>>> exec ('num3 = num + 1', {}, l) # The globals parameter is specified, there is no num variable in globals, and the locals variable is specified. The locals variable contains the num variable, which is successfully executed >>> l {'_ package _': None, '_ loader _': <class '_ frozen_importlib.BuiltinImporter'>, '_ name _': '_ main _', '_ spec __': none, 'num3': 2, '_ builtins _': <module 'builtins '(built-in)>,' _ doc _ ': None, 'L ':{...}, 'num2': 2, 'num': 1} >>>