命令行与IDLE中的dir()函数

dop*_*man 5 python

我试过在IDLE中运行以下代码:

import sys
dir(sys)
Run Code Online (Sandbox Code Playgroud)

没有结果:

>>>
Run Code Online (Sandbox Code Playgroud)

但是当我在命令行中运行它时,我得到了这个:

>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']
Run Code Online (Sandbox Code Playgroud)

有人能解释我所做的不同吗?

kin*_*all 4

问题的根源在于对作用的误解dir()。如果您在交互式 Python 提示符下使用它>>>,很容易认为它的意思是“打印给定对象中可用的名称”。然而,它实际上所做的是返回给定对象中可用的名称。

为了方便起见,交互式 Python shell 会打印最后一条语句的结果(如果有的话)(None假定该语句没有产生结果)。因此,当您dir()按照提示执行操作时,会打印>>>结果。然而,执行打印的并不是 Python shell dir()dir()

因此,在 IDLE 会话中,您正在执行dir(),但没有对结果执行任何操作。由于您不是以交互方式执行该语句,而是作为脚本执行,因此 Python 不会自动为您打印它,因为它不知道您想要这样做(事实上,大多数时候您并不需要)。您可以将其存储在变量中以供以后使用:

sysdir = dir(sys)
Run Code Online (Sandbox Code Playgroud)

由于它是一个列表,因此您可以迭代它:

for n in dir(sys):
    # do something
Run Code Online (Sandbox Code Playgroud)

或者你可以打印它:

print dir(sys)    # Python 3 requires print(dir(sys))
Run Code Online (Sandbox Code Playgroud)