如何在 python 3 控制台中打印出导入库的成员函数?

How to print out member functions of a imported library in a python 3 console?

注意:示例输出是 ipython(增强的 python 编程控制台)功能,而不是 python 3 标准 (@DTing)。使用默认控制台时,可以通过dir(libname)命令获取成员函数列表(@Matthew Runchey)。

在 python 2.7 控制台中,可以使用命令 libname. 打印出导入库 libname 的成员函数。 预期的输出应该是这样的:

>>> import hashlib
>>> hashlib.
hashlib.algorithms  hashlib.new     hashlib.sha224   hashlib.sha384
hashlib.md5         hashlib.sha1    hashlib.sha256   hashlib.sha512

(示例取自本视频中的 0:13 左右:https://youtu.be/dG3tOsGEYP4

但是,我的 python 3.4 控制台 (Win7 x64) 出现语法错误。

>>> import hashlib
>>> hashlib.
  File "<stdin>", line 1
    hashlib.
           ^
SyntaxError: invalid syntax

那么在 python 3 中做同样事情的正确方法是什么?

这不是 python 的功能,而是 ipython 选项卡完成功能。

见下文:

$ python
Python 2.7.9 (default, Apr  7 2015, 07:58:25)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import hashlib
>>> hashlib.
  File "<stdin>", line 1
    hashlib.
           ^
SyntaxError: invalid syntax
>>>

点击 . 之后的标签:

$ ipython
Python 2.7.9 (default, Apr  7 2015, 07:58:25)
Type "copyright", "credits" or "license" for more information.

IPython 3.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import hashlib

In [2]: hashlib.
hashlib.algorithms             hashlib.md5                    hashlib.sha1                   hashlib.sha384
hashlib.algorithms_available   hashlib.new                    hashlib.sha224                 hashlib.sha512
hashlib.algorithms_guaranteed  hashlib.pbkdf2_hmac            hashlib.sha256

也适用于 python3:

$ ipython
Python 3.4.3 (default, Apr  7 2015, 08:05:21)
Type "copyright", "credits" or "license" for more information.

IPython 3.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import hashlib

In [2]: hashlib.
hashlib.algorithms_available   hashlib.new                    hashlib.sha224                 hashlib.sha512
hashlib.algorithms_guaranteed  hashlib.pbkdf2_hmac            hashlib.sha256
hashlib.md5                    hashlib.sha1                   hashlib.sha384

如果您使用的是 ipython,这可能是一个相关问题 IPython tab completion not working

dir(module_name)

这将打印您导入的任何函数的列表。

>>>import hashlib
>>>dir(hashlib)
['__all__', '__builtin_constructor_cache', '__builtins__', '__cached__', '__doc__', '__file__', '__get_builtin_constructor', '__loader__', '__name__', '__package__', '__spec__', '_hashlib', 'algorithms_available', 'algorithms_guaranteed', 'md5', 'new', 'pbkdf2_hmac', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']