当我们打开一个交互式 python3 解释器和 运行 一些命令时,我们是否 运行 某些模块中的命令?
When we open an interactive python3 interpreter and run some commands, do we run the commands in some module?
当我们打开交互式 python3 解释器和 运行 一些命令时,我们是否 运行 某些模块中的命令?那个模块是什么?
我问这个是因为在这种情况下 __name__
是 __main__
,而且我认为 __name__
是某个我不知道并要求的模块的属性。但是 __dict__
和 __file__
作为模块的属性不存在。存在的属性是:
>>> globals()
{'__package__': None, '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__spec__': None}
是的,解释器会话是 __main__
模块:
$ python3.6
Python 3.6.1 (default, Apr 5 2017, 20:56:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.modules['__main__']
<module '__main__' (built-in)>
>>> sys.modules['__main__'].__dict__ is globals()
True
globals()
对象 是 模块 __dict__
命名空间。不要将命名空间的内容与命名空间本身混淆(当您询问实例的属性时,__dict__
不在实例内部 __dict__
属性 either).
__file__
属性是可选的;由于您不是来自此处文件的 运行,因此未设置属性:
>>> sys.modules['__main__'].__file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module '__main__' has no attribute '__file__'
当我们打开交互式 python3 解释器和 运行 一些命令时,我们是否 运行 某些模块中的命令?那个模块是什么?
我问这个是因为在这种情况下 __name__
是 __main__
,而且我认为 __name__
是某个我不知道并要求的模块的属性。但是 __dict__
和 __file__
作为模块的属性不存在。存在的属性是:
>>> globals()
{'__package__': None, '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__spec__': None}
是的,解释器会话是 __main__
模块:
$ python3.6
Python 3.6.1 (default, Apr 5 2017, 20:56:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.modules['__main__']
<module '__main__' (built-in)>
>>> sys.modules['__main__'].__dict__ is globals()
True
globals()
对象 是 模块 __dict__
命名空间。不要将命名空间的内容与命名空间本身混淆(当您询问实例的属性时,__dict__
不在实例内部 __dict__
属性 either).
__file__
属性是可选的;由于您不是来自此处文件的 运行,因此未设置属性:
>>> sys.modules['__main__'].__file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module '__main__' has no attribute '__file__'