1 描述

把一个字符串当成语句执行

exec()  执行储存在字符串或文件中的 Python 语句,相比于  eval() , exec() 可以执行更复杂的 Python 代码。

exec函数和eval函数类似,也是执行动态语句

只不过eval函数只用于执行表达式求值,

        而exec函数主要用于执行语句块。

>>> eval("a=1+2")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    a=1+2
     ^
SyntaxError: invalid syntax  #无效语法,字符串无法执行

>>> exec("a=1+2")
>>> a
3

2 语法

exec(object[, globals[, locals]])

object:必选参数,表示需要被指定的Python代码。它必须是字符串或code对象。如果object是一个字符串,该字符串会先被解析为一组Python语句,然后在执行(除非发生语法错误)。如果object是一个code对象,那么它只是被简单的执行。

   = 字符串是Python的合法语句

globals:可选参数,表示全局命名空间(存放全局变量),如果被提供,则必须是一个字典对象。

   = 表达式使用的全局变量 字典    globals()

locals:可选参数,表示当前局部命名空间(存放局部变量),如果被提供,可以是任何映射对象。如果该参数被忽略,那么它将会取与globals相同的值。

   = 表达式使用的局部变量 字典  等同globals(第二个参数值)

    有locals参数时,优先执行该参数

globals()

功能:收集全局变量
参数:无
返回值:得到一个收集全局变量的字典(会包含系统的内置变量)

locals()

功能:收集局部变量
参数:无
返回值:得到一个收集局部变量的字典

3 返回值

None

但是执行后,local或globals 的self 采用字典形式输出

4 练习

x = 100
y = 200

s = '''
a = x + y
print(a)
    '''
exec(s)

运行

300

x = 100
y = 200

ls = {'x':1,'y':2}
gs = {'x':3,'y':4}
exec('a = x + y',ls,gs)
print("ls =",ls)     #ls = {'x': 1, 'y': 2,}
print("----------------------")
print("gs =",gs)    #gs = {'x': 3, 'y': 4, 'a': 7}
print("======================")

ls = {'x':1,'y':2}
gs = {'x':3,'y':4}
exec('a = x + y',None,gs)
print("ls =",ls)    #ls = {'x': 1, 'y': 2}
print("----------------------")
print("gs =",gs)    #gs = {'x': 3, 'y': 4, 'a': 7}
print("======================")

ls = {'x':1,'y':2}
gs = {'x':3,'y':4}
exec('a = x + y',ls)
print("ls =",ls)    #ls = {'x': 1, 'y': 2, 'a': 3,}
print("----------------------")
print("gs =",gs)    #gs = {'x': 3, 'y': 4}
print("======================")

ls = {'x':1,'y':2}
gs = {'x':3,'y':4}
exec('a = x + y',ls,None)
print("ls =",ls)     #ls = {'x': 1, 'y': 2, 'a': 3, }
print("----------------------")
print("gs =",gs)    #gs = {'x': 3, 'y': 4}
print("======================")

实际上,在上述代码输出过程中,全局变量中包含了很多内置全局变量。上面的代码实际输出为:

ls = {'x': 1, 'y': 2, '__builtins__': {'id': <built-in function id>, 'min': <built-in function min>, 'license': Type license() to see the full license text, 'all': <built-in function all>, 'SyntaxError': <class 'SyntaxError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'delattr': <built-in function delattr>, 'OverflowError': <class 'OverflowError'>, 'RecursionError': <class 'RecursionError'>, 'BaseException': <class 'BaseException'>, 'FileExistsError': <class 'FileExistsError'>, 'help': Type help() for interactive help, or help(object) for help about object., 'dict': <class 'dict'>, 'FutureWarning': <class 'FutureWarning'>, 'IOError': <class 'OSError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'complex': <class 'complex'>, 'ord': <built-in function ord>, 'print': <built-in function print>, 'property': <class 'property'>, 'callable': <built-in function callable>, 'memoryview': <class 'memoryview'>, 'set': <class 'set'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'ReferenceError': <class 'ReferenceError'>, 'BufferError': <class 'BufferError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'chr': <built-in function chr>, 'range': <class 'range'>, 'pow': <built-in function pow>, 'IndentationError': <class 'IndentationError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'TimeoutError': <class 'TimeoutError'>, 'InterruptedError': <class 'InterruptedError'>, 'int': <class 'int'>, 'ConnectionError': <class 'ConnectionError'>, 'input': <built-in function input>, 'FloatingPointError': <class 'FloatingPointError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'bytes': <class 'bytes'>, 'staticmethod': <class 'staticmethod'>, 'isinstance': <built-in function isinstance>, 'False': False, 'AttributeError': <class 'AttributeError'>, 'ImportWarning': <class 'ImportWarning'>, 'SystemExit': <class 'SystemExit'>, '__import__': <built-in function __import__>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", 'abs': <built-in function abs>, 'filter': <class 'filter'>, 'slice': <class 'slice'>, 'tuple': <class 'tuple'>, 'iter': <built-in function iter>, 'object': <class 'object'>, 'eval': <built-in function eval>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'StopIteration': <class 'StopIteration'>, 'issubclass': <built-in function issubclass>, 'sum': <built-in function sum>, 'max': <built-in function max>, 'enumerate': <class 'enumerate'>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'UserWarning': <class 'UserWarning'>, 'NameError': <class 'NameError'>, 'Exception': <class 'Exception'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), 'bin': <built-in function bin>, 'ResourceWarning': <class 'ResourceWarning'>, 'any': <built-in function any>, 'LookupError': <class 'LookupError'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'list': <class 'list'>, 'ChildProcessError': <class 'ChildProcessError'>, 'next': <built-in function next>, 'Warning': <class 'Warning'>, 'ImportError': <class 'ImportError'>, '__build_class__': <built-in function __build_class__>, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'str': <class 'str'>, 'classmethod': <class 'classmethod'>, 'globals': <built-in function globals>, 'BlockingIOError': <class 'BlockingIOError'>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'UnicodeError': <class 'UnicodeError'>, 'oct': <built-in function oct>, 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    for supporting Python development.  See www.python.org for more information., 'setattr': <built-in function setattr>, 'ascii': <built-in function ascii>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'exec': <built-in function exec>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'EnvironmentError': <class 'OSError'>, 'round': <built-in function round>, 'super': <class 'super'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'TypeError': <class 'TypeError'>, 'TabError': <class 'TabError'>, 'reversed': <class 'reversed'>, 'SystemError': <class 'SystemError'>, 'float': <class 'float'>, 'hasattr': <built-in function hasattr>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'IndexError': <class 'IndexError'>, 'None': None, 'repr': <built-in function repr>, 'True': True, 'ValueError': <class 'ValueError'>, 'sorted': <built-in function sorted>, 'format': <built-in function format>, 'frozenset': <class 'frozenset'>, 'KeyError': <class 'KeyError'>, 'GeneratorExit': <class 'GeneratorExit'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'map': <class 'map'>, 'bool': <class 'bool'>, 'OSError': <class 'OSError'>, 'hex': <built-in function hex>, 'PermissionError': <class 'PermissionError'>, 'bytearray': <class 'bytearray'>, 'RuntimeError': <class 'RuntimeError'>, 'open': <built-in function open>, 'vars': <built-in function vars>, 'hash': <built-in function hash>, 'compile': <built-in function compile>, 'getattr': <built-in function getattr>, 'type': <class 'type'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'AssertionError': <class 'AssertionError'>, 'BytesWarning': <class 'BytesWarning'>, 'zip': <class 'zip'>, 'divmod': <built-in function divmod>, 'MemoryError': <class 'MemoryError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, '__debug__': True, 'dir': <built-in function dir>, '__name__': 'builtins', 'BrokenPipeError': <class 'BrokenPipeError'>, 'copyright': Copyright (c) 2001-2016 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved., 'ArithmeticError': <class 'ArithmeticError'>, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'Ellipsis': Ellipsis, '__package__': '', 'UnboundLocalError': <class 'UnboundLocalError'>, 'EOFError': <class 'EOFError'>, 'NotImplemented': NotImplemented}}
----------------------
gs = {'x': 3, 'y': 4, 'a': 7}
======================
ls = {'x': 1, 'y': 2}
----------------------
gs = {'x': 3, 'y': 4, 'a': 7}
======================
ls = {'x': 1, 'y': 2, 'a': 3, '__builtins__': {'id': <built-in function id>, 'min': <built-in function min>, 'license': Type license() to see the full license text, 'all': <built-in function all>, 'SyntaxError': <class 'SyntaxError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'delattr': <built-in function delattr>, 'OverflowError': <class 'OverflowError'>, 'RecursionError': <class 'RecursionError'>, 'BaseException': <class 'BaseException'>, 'FileExistsError': <class 'FileExistsError'>, 'help': Type help() for interactive help, or help(object) for help about object., 'dict': <class 'dict'>, 'FutureWarning': <class 'FutureWarning'>, 'IOError': <class 'OSError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'complex': <class 'complex'>, 'ord': <built-in function ord>, 'print': <built-in function print>, 'property': <class 'property'>, 'callable': <built-in function callable>, 'memoryview': <class 'memoryview'>, 'set': <class 'set'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'ReferenceError': <class 'ReferenceError'>, 'BufferError': <class 'BufferError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'chr': <built-in function chr>, 'range': <class 'range'>, 'pow': <built-in function pow>, 'IndentationError': <class 'IndentationError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'TimeoutError': <class 'TimeoutError'>, 'InterruptedError': <class 'InterruptedError'>, 'int': <class 'int'>, 'ConnectionError': <class 'ConnectionError'>, 'input': <built-in function input>, 'FloatingPointError': <class 'FloatingPointError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'bytes': <class 'bytes'>, 'staticmethod': <class 'staticmethod'>, 'isinstance': <built-in function isinstance>, 'False': False, 'AttributeError': <class 'AttributeError'>, 'ImportWarning': <class 'ImportWarning'>, 'SystemExit': <class 'SystemExit'>, '__import__': <built-in function __import__>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", 'abs': <built-in function abs>, 'filter': <class 'filter'>, 'slice': <class 'slice'>, 'tuple': <class 'tuple'>, 'iter': <built-in function iter>, 'object': <class 'object'>, 'eval': <built-in function eval>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'StopIteration': <class 'StopIteration'>, 'issubclass': <built-in function issubclass>, 'sum': <built-in function sum>, 'max': <built-in function max>, 'enumerate': <class 'enumerate'>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'UserWarning': <class 'UserWarning'>, 'NameError': <class 'NameError'>, 'Exception': <class 'Exception'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), 'bin': <built-in function bin>, 'ResourceWarning': <class 'ResourceWarning'>, 'any': <built-in function any>, 'LookupError': <class 'LookupError'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'list': <class 'list'>, 'ChildProcessError': <class 'ChildProcessError'>, 'next': <built-in function next>, 'Warning': <class 'Warning'>, 'ImportError': <class 'ImportError'>, '__build_class__': <built-in function __build_class__>, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'str': <class 'str'>, 'classmethod': <class 'classmethod'>, 'globals': <built-in function globals>, 'BlockingIOError': <class 'BlockingIOError'>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'UnicodeError': <class 'UnicodeError'>, 'oct': <built-in function oct>, 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    for supporting Python development.  See www.python.org for more information., 'setattr': <built-in function setattr>, 'ascii': <built-in function ascii>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'exec': <built-in function exec>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'EnvironmentError': <class 'OSError'>, 'round': <built-in function round>, 'super': <class 'super'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'TypeError': <class 'TypeError'>, 'TabError': <class 'TabError'>, 'reversed': <class 'reversed'>, 'SystemError': <class 'SystemError'>, 'float': <class 'float'>, 'hasattr': <built-in function hasattr>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'IndexError': <class 'IndexError'>, 'None': None, 'repr': <built-in function repr>, 'True': True, 'ValueError': <class 'ValueError'>, 'sorted': <built-in function sorted>, 'format': <built-in function format>, 'frozenset': <class 'frozenset'>, 'KeyError': <class 'KeyError'>, 'GeneratorExit': <class 'GeneratorExit'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'map': <class 'map'>, 'bool': <class 'bool'>, 'OSError': <class 'OSError'>, 'hex': <built-in function hex>, 'PermissionError': <class 'PermissionError'>, 'bytearray': <class 'bytearray'>, 'RuntimeError': <class 'RuntimeError'>, 'open': <built-in function open>, 'vars': <built-in function vars>, 'hash': <built-in function hash>, 'compile': <built-in function compile>, 'getattr': <built-in function getattr>, 'type': <class 'type'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'AssertionError': <class 'AssertionError'>, 'BytesWarning': <class 'BytesWarning'>, 'zip': <class 'zip'>, 'divmod': <built-in function divmod>, 'MemoryError': <class 'MemoryError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, '__debug__': True, 'dir': <built-in function dir>, '__name__': 'builtins', 'BrokenPipeError': <class 'BrokenPipeError'>, 'copyright': Copyright (c) 2001-2016 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved., 'ArithmeticError': <class 'ArithmeticError'>, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'Ellipsis': Ellipsis, '__package__': '', 'UnboundLocalError': <class 'UnboundLocalError'>, 'EOFError': <class 'EOFError'>, 'NotImplemented': NotImplemented}}
----------------------
gs = {'x': 3, 'y': 4}
======================
ls = {'x': 1, 'y': 2, 'a': 3, '__builtins__': {'id': <built-in function id>, 'min': <built-in function min>, 'license': Type license() to see the full license text, 'all': <built-in function all>, 'SyntaxError': <class 'SyntaxError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'delattr': <built-in function delattr>, 'OverflowError': <class 'OverflowError'>, 'RecursionError': <class 'RecursionError'>, 'BaseException': <class 'BaseException'>, 'FileExistsError': <class 'FileExistsError'>, 'help': Type help() for interactive help, or help(object) for help about object., 'dict': <class 'dict'>, 'FutureWarning': <class 'FutureWarning'>, 'IOError': <class 'OSError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'complex': <class 'complex'>, 'ord': <built-in function ord>, 'print': <built-in function print>, 'property': <class 'property'>, 'callable': <built-in function callable>, 'memoryview': <class 'memoryview'>, 'set': <class 'set'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'ReferenceError': <class 'ReferenceError'>, 'BufferError': <class 'BufferError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'chr': <built-in function chr>, 'range': <class 'range'>, 'pow': <built-in function pow>, 'IndentationError': <class 'IndentationError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'TimeoutError': <class 'TimeoutError'>, 'InterruptedError': <class 'InterruptedError'>, 'int': <class 'int'>, 'ConnectionError': <class 'ConnectionError'>, 'input': <built-in function input>, 'FloatingPointError': <class 'FloatingPointError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'bytes': <class 'bytes'>, 'staticmethod': <class 'staticmethod'>, 'isinstance': <built-in function isinstance>, 'False': False, 'AttributeError': <class 'AttributeError'>, 'ImportWarning': <class 'ImportWarning'>, 'SystemExit': <class 'SystemExit'>, '__import__': <built-in function __import__>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", 'abs': <built-in function abs>, 'filter': <class 'filter'>, 'slice': <class 'slice'>, 'tuple': <class 'tuple'>, 'iter': <built-in function iter>, 'object': <class 'object'>, 'eval': <built-in function eval>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'StopIteration': <class 'StopIteration'>, 'issubclass': <built-in function issubclass>, 'sum': <built-in function sum>, 'max': <built-in function max>, 'enumerate': <class 'enumerate'>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'UserWarning': <class 'UserWarning'>, 'NameError': <class 'NameError'>, 'Exception': <class 'Exception'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), 'bin': <built-in function bin>, 'ResourceWarning': <class 'ResourceWarning'>, 'any': <built-in function any>, 'LookupError': <class 'LookupError'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'list': <class 'list'>, 'ChildProcessError': <class 'ChildProcessError'>, 'next': <built-in function next>, 'Warning': <class 'Warning'>, 'ImportError': <class 'ImportError'>, '__build_class__': <built-in function __build_class__>, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'str': <class 'str'>, 'classmethod': <class 'classmethod'>, 'globals': <built-in function globals>, 'BlockingIOError': <class 'BlockingIOError'>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'UnicodeError': <class 'UnicodeError'>, 'oct': <built-in function oct>, 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    for supporting Python development.  See www.python.org for more information., 'setattr': <built-in function setattr>, 'ascii': <built-in function ascii>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'exec': <built-in function exec>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'EnvironmentError': <class 'OSError'>, 'round': <built-in function round>, 'super': <class 'super'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'TypeError': <class 'TypeError'>, 'TabError': <class 'TabError'>, 'reversed': <class 'reversed'>, 'SystemError': <class 'SystemError'>, 'float': <class 'float'>, 'hasattr': <built-in function hasattr>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'IndexError': <class 'IndexError'>, 'None': None, 'repr': <built-in function repr>, 'True': True, 'ValueError': <class 'ValueError'>, 'sorted': <built-in function sorted>, 'format': <built-in function format>, 'frozenset': <class 'frozenset'>, 'KeyError': <class 'KeyError'>, 'GeneratorExit': <class 'GeneratorExit'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'map': <class 'map'>, 'bool': <class 'bool'>, 'OSError': <class 'OSError'>, 'hex': <built-in function hex>, 'PermissionError': <class 'PermissionError'>, 'bytearray': <class 'bytearray'>, 'RuntimeError': <class 'RuntimeError'>, 'open': <built-in function open>, 'vars': <built-in function vars>, 'hash': <built-in function hash>, 'compile': <built-in function compile>, 'getattr': <built-in function getattr>, 'type': <class 'type'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'AssertionError': <class 'AssertionError'>, 'BytesWarning': <class 'BytesWarning'>, 'zip': <class 'zip'>, 'divmod': <built-in function divmod>, 'MemoryError': <class 'MemoryError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, '__debug__': True, 'dir': <built-in function dir>, '__name__': 'builtins', 'BrokenPipeError': <class 'BrokenPipeError'>, 'copyright': Copyright (c) 2001-2016 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved., 'ArithmeticError': <class 'ArithmeticError'>, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'Ellipsis': Ellipsis, '__package__': '', 'UnboundLocalError': <class 'UnboundLocalError'>, 'EOFError': <class 'EOFError'>, 'NotImplemented': NotImplemented}}
----------------------
gs = {'x': 3, 'y': 4}
======================

参考 https://www.cnblogs.com/sesshoumaru/p/5998523.html

Python学习笔记011——内置函数exec()的更多相关文章

  1. python学习笔记011——内置函数pow()

    1 语法 pow(x, y[, z]) x -- 数值表达式. y -- 数值表达式. z -- 数值表达式. 函数是计算 x 的 y 次方,如果 z 在存在,则再对结果进行取模,其结果等效于pow( ...

  2. python学习笔记011——内置函数dir()

    1 描述 dir()函数可以查看(打印)对象的属性和方法.不管时那种对象(python中一切皆对象)类型(数据,模块)都有自己的属性和方法. dir() 函数不带参数时,返回当前范围内的变量.方法和定 ...

  3. Python学习笔记011——内置函数eval()

    1 描述 eval()  函数用来执行一个字符串表达式,并返回表达式的值 2 语法 原文 eval(expression[, globals=None[, locals=None]]) express ...

  4. python学习笔记011——内置函数__module__、__name__

    1 __module__描述 __module__ : 如果当前模块为顶层模块执行 则打印__main__ 如果当前模块为被调用模块的时候 打印当前模块的名称 2 __module__示例 def f ...

  5. python学习笔记011——内置函数sorted()

    1 描述 sorted() 函数对所有可迭代的对象进行排序操作. sorted() 与sort()函数之间的区别 1 排序对象 sorted:所有可迭代对象的排序 sort:list列表的排序 2 返 ...

  6. python学习笔记011——内置函数filter()

    1 描述 filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表. 2 语法 filter(function, iterable) function -- 函数,过 ...

  7. python学习笔记011——内置函数sum()

    1 描述 sum() 方法对系列进行求和计算. 2 语法 sum(iterable[, start]) iterable:可迭代对象,如列表. start:指定相加的参数,如果没有设置这个值,默认为0 ...

  8. python学习笔记011——内置函数__sizeof__()

    1 描述 __sizeof__() : 打印系统分配空间的大小 2 示例 def fun(): pass print(fun.__sizeof__()) 运行 112

  9. Python学习笔记-Day3-python内置函数

    python内置函数 1.abs    求绝对值 2.all 判断迭代器中的所有数据是否都为true 如果可迭代的数据的所有数据都为true或可迭代的数据为空,返回True.否则返回False 3.a ...

随机推荐

  1. C/C++字符串查找函数

    C/C++ string库(string.h)提供了几个字符串查找函数,如下: memchr 在指定内存里定位给定字符 strchr 在指定字符串里定位给定字符 strcspn 返回在字符串str1里 ...

  2. jQuery用面向对象的思想来编写验证表单的插件

    本人的重点是怎么构建一个简单有效可扩展的jQuery表单验证插件,这篇文章没有教你怎么用 validate plugin.我们的重点在学习一些jQuery,Javascript面向对象编程的知识. 下 ...

  3. 本地主机DNS劫持演示及防范

    劫持演示                                                                                      如果要进行DNS劫持 ...

  4. [置顶] Android异步加载数据库和多线程编程

    Android是一种基于Linux的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由Google公司和开放手机联盟领导及开发.尚未有统一中文名称,中国大陆地区较多人使用“安卓” ...

  5. Ofstream的endl不好用怎么回事?

    用endl,std::endl, "\n"都不好用,不输出换行,怎么回事? [解决方法] If you're writing a text file, you shouldn't ...

  6. 在Fedora8上安装MySQL5.0.45的过程

    本来想安装最新的5.6.13-1版本,下载下来后,依赖的包rpmlib无处下载,无法只得作罢.从Foreda8的安装光盘中找到了以下文件: mysql-5.0.45-4.fc8.i386.rpm my ...

  7. wepy - Cannot read property 'Promise' of undefined

    正当我们准备试探示例时,突然.... 造成这个错误有两个原因 (wepy以前的版本默认启动了Promise,自1.4.x以后需要手动开启) 1.未下载Promise 详情见启用文档:Promise   ...

  8. Linux高性能server编程——多线程编程(下)

    多线程编程 条件变量 假设说相互排斥锁是用于同步线程对共享数据的訪问的话.那么条件变量则是用于线程之间同步共享数据的值. 条件变量提供了一种线程间的通信机制:当某个共享数据达到某个值得时候,唤醒等待这 ...

  9. sql面试-查询选修课程的学生

    首先: 1 .  EXISTS 子查询找到的提交 NOT EXISTS 子查询中 找不到的提交 说明:不要去翻译为存在和不存在,把脑袋搞晕. 2 . 建立程序循环的概念,这是一个动态的查询过程.如 F ...

  10. java面试第十四天

    包名.类名和属性可以被序列化,方法和构造器不会被序列化的. 静态属性不会被序列化的. 属性会被递归序列化的,也就是一个类中有引用类型的属性,如果这个属性对应的类实现了Serializable接口,在对 ...