[英]When we open an interactive python3 interpreter and run some commands, do we run the commands in some module?
When we open an interactive python3 interpreter and run some commands, do we run the commands in some module? 当我们打开一个交互式python3解释器并运行一些命令时,是否在某个模块中运行这些命令? What is that module?
那是什么模块?
I ask this because __name__
is __main__
in such cases, and I think __name__
is an attribute of some module which I don't know and am asking for. 我之所以
__name__
问,是因为在这种情况下__name__
是__main__
,我认为__name__
是某些模块的属性,我不知道该模块是否在请求。 But __dict__
and __file__
as attributes of a module don't exist. 但是作为模块属性的
__dict__
和__file__
不存在。 The attributes which exist are: 存在的属性是:
>>> globals()
{'__package__': None, '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__spec__': None}
Yes, the interpreter session is the __main__
module: 是的,解释器会话是
__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
The globals()
object is the module __dict__
namespace. globals()
对象是模块__dict__
命名空间。 Don't confuse the contents of the namespace with the namespace itself (when you ask for the attributes of an instance, __dict__
is not inside the instance __dict__
attribute either ). 不要混淆的名称空间本身(如果你问一个实例的属性,命名空间中的内容
__dict__
是不是里面的实例__dict__
任一属性)。
The __file__
attribute is optional ; __file__
属性是可选的 ; since you are not running from a file here, the attribute is not set: 由于您不是从此处的文件运行的,因此未设置该属性:
>>> sys.modules['__main__'].__file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module '__main__' has no attribute '__file__'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.