查看python的模块和函数

1、在cmd模式下
help(),进入帮助页面

>>> help()

Welcome to Python 2.7!  This is the online help utility.

modules查看所有模块

help> modules

Please wait a moment while I gather a list of all available modules...

BaseHTTPServer      antigravity         ihooks              sgmllib
Bastion             anydbm              imageop             sha
CGIHTTPServer       argparse            imaplib             shelve
Canvas              array               imghdr              shlex
ConfigParser        ast                 imp                 shutil
Cookie              asynchat            importlib           signal
Dialog              asyncore            imputil             site
DocXMLRPCServer     atexit              inspect             smtpd
FileDialog          audiodev

q或enter退出帮助页面

help> q

You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)".  Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.

dir(模块名)列出所查询内容的内置属性和方法

>>> dir(urllib)
['ContentTooShortError', 'FancyURLopener', 'MAXFTPCACHE', 'URLopener', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__version__', '_ftperrors', '_have_ssl', '_hexdig', '_hextochr', '_hostprog', '_is_unicode', '_localhost', '_noheaders', '_nportprog', '_passwdprog', '_portprog', '_queryprog', '_safe_map', '_safe_quoters', '_tagprog', '_thishost', '_typeprog', '_urlopener', '_userprog', '_valueprog', 'addbase', 'addclosehook', 'addinfo', 'addinfourl', 'always_safe', 'basejoin', 'c', 'ftpcache', 'ftperrors', 'ftpwrapper', 'getproxies', 'getproxies_enviro

dir()也可以查询python的内置方法, dir(builtins)

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError',

print(模块名.doc)查看使用帮助,一般为创建该类时候的备注

>>> print(urllib.__doc__)
Open an arbitrary URL.

See the following document for more info on URLs:
"Names and Addresses, URIs, URLs, URNs, URCs", at
http://www.w3.org/pub/WWW/Addressing/Overview.html

See also the HTTP spec (from which the error codes are derived):
"HTTP - Hypertext Transfer Protocol", at
http://www.w3.org/pub/WWW/Protocols/

print(urllib.dict)查看对象所拥有的属性

>>> print(urllib.__dict__)
{'splitnport': <function splitnport at 0x0000000003556BA8>, '_hostprog': None, 'getproxies': <function getproxies at 0x000000000355A198>, 'URLopener': <class urllib.URLopener at 0x0000000003545828>, '_typeprog': None, 'proxy_bypass_environment': <function proxy_bypass_environment at 0x000000000355A0B8>, 'urlencode': <function urlencode at 0x0000000003556F98>, 'basejoin': <function urljoin at 0x0000000003548588>, '_nportprog': None,

2、在解释器模式下
help(模块名)查看用法

import urllib
help(urllib)
Help on package urllib:

NAME
    urllib

PACKAGE CONTENTS
    error
    parse
    request
    response
    robotparser

FILE
    c:\users\dell\appdata\local\programs\python\python37\lib\urllib\__init__.py

import urllib.request
help(urllib.request)
Help on module urllib.request in urllib:

NAME
    urllib.request - An extensible library for opening URLs using a variety of protocols

DESCRIPTION
    The simplest way to use this module is to call the urlopen function,
    which accepts a string containing a URL or a Request object (described
    below).  It opens the URL and returns the results as file-like
    object; the returned object has some extra methods described below.
    
    The OpenerDirector manages a collection of Handler objects that do
    all the actual work.  Each Handler implements a particular protocol or
    option.  The OpenerDirector is a composite object that invokes the
    Handlers needed to open the requested URL.  For example, the
    HTTPHandler performs HTTP GET and POST requests and deals with
    non-error returns.  The HTTPRedirectHandler automatically deals with
    HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
    deals with digest authentication.
    
    urlopen(url, data=None) -- Basic usage is the same as original
    urllib.  pass the url and optionally data to post to an HTTP URL, and
    get a file-like object back.  One difference is that you can also pass
    a Request instance instead of URL.  Raises a URLError (subclass of
    OSError); for HTTP errors, raises an HTTPError, which can also be
    treated as a valid response.
    
    build_opener -- Function that creates a new OpenerDirector instance.
    Will install the default handlers.  Accepts one or more Handlers as
    arguments, either instances or Handler classes that it will
    instantiate.  If one of the argument is a subclass of the default
    handler, the argument will be installed instead of the default.
    
    install_opener -- Installs a new opener as the default opener.
    
    objects of interest:
    
    OpenerDirector -- Sets up the User Agent as the Python-urllib client and manages
    the Handler classes, while dealing with requests and responses.
    
    Request -- An object that encapsulates the state of a request.  The
    state can be as simple as the URL.  It can also include extra HTTP
    headers, e.g. a User-Agent.
    
    BaseHandler --
    
    internals:
    BaseHandler and parent
    _call_chain conventions
    
    Example usage:
    
    import urllib.request
    
    # set up authentication info
    authinfo = urllib.request.HTTPBasicAuthHandler()
    authinfo.add_password(realm='PDQ Application',
                          uri='https://mahler:8092/site-updates.py',
                          user='klem',
                          passwd='geheim$parole')
    
    proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"})
    
    # build a new opener that adds authentication and caching FTP handlers
    opener = urllib.request.build_opener(proxy_support, authinfo,
                                         urllib.request.CacheFTPHandler)
    
    # install it
    urllib.request.install_opener(opener)
    
    f = urllib.request.urlopen('http://www.python.org/')

CLASSES
    builtins.object
        AbstractBasicAuthHandler
            HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler)
            ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler)
        AbstractDigestAuthHandler
        BaseHandler
            DataHandler
            FTPHandler
                CacheFTPHandler
            FileHandler
            HTTPCookieProcessor
            HTTPDefaultErrorHandler
            HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler)
            HTTPErrorProcessor
            HTTPRedirectHandler
            ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler)
            ProxyHandler
            UnknownHandler
        HTTPPasswordMgr
            HTTPPasswordMgrWithDefaultRealm
                HTTPPasswordMgrWithPriorAuth
        OpenerDirector
        Request
        URLopener
            FancyURLopener
    AbstractHTTPHandler(BaseHandler)
        HTTPHandler
        HTTPSHandler
    
    class AbstractBasicAuthHandler(builtins.object)
     |  AbstractBasicAuthHandler(password_mgr=None)
     |  
     |  Methods defined here:
     |  
     |  __init__(self, password_mgr=None)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  http_error_auth_reqed(self, authreq, host, req, headers)
     |  
     |  http_request(self, req)
     |  

查看函数的方法,默认参数

import urllib.request
help(urllib.request.urlopen)
Help on function urlopen in module urllib.request:

urlopen(url, data=None, timeout=<object object at 0x00000159B10BE230>, *, cafile=None, capath=None, cadefault=False, context=None)
    Open the URL url, which can be either a string or a Request object.
    
    *data* must be an object specifying additional data to be sent to
    the server, or None if no such data is needed.  See Request for
    details.
    
    urllib.request module uses HTTP/1.1 and includes a "Connection:close"
    header in its HTTP requests.
    
    The optional *timeout* parameter specifies a timeout in seconds for
    blocking operations like the connection attempt (if not specified, the
    global default timeout setting will be used). This only works for HTTP,
    HTTPS and FTP connections.
    
    If *context* is specified, it must be a ssl.SSLContext instance describing
    the various SSL options. See HTTPSConnection for more details.
    
    The optional *cafile* and *capath* parameters specify a set of trusted CA
    certificates for HTTPS requests. cafile should point to a single file
    containing a bundle of CA certificates, whereas capath should point to a
    directory of hashed certificate files. More information can be found in
    ssl.SSLContext.load_verify_locations().
    
    The *cadefault* parameter is ignored.
    
    This function always returns an object which can work as a context
    manager and has methods such as
    
    * geturl() - return the URL of the resource retrieved, commonly used to
      determine if a redirect was followed
    
    * info() - return the meta-information of the page, such as headers, in the
      form of an email.message_from_string() instance (see Quick Reference to
      HTTP Headers)
    
    * getcode() - return the HTTP status code of the response.  Raises URLError
      on errors.
    
    For HTTP and HTTPS URLs, this function returns a http.client.HTTPResponse
    object slightly modified. In addition to the three new methods above, the
    msg attribute contains the same information as the reason attribute ---
    the reason phrase returned by the server --- instead of the response
    headers as it is specified in the documentation for HTTPResponse.
    
    For FTP, file, and data URLs and requests explicitly handled by legacy
    URLopener and FancyURLopener classes, this function returns a
    urllib.response.addinfourl object.
    
    Note that None may be returned if no handler handles the request (though
    the default installed global OpenerDirector uses UnknownHandler to ensure
    this never happens).
    
    In addition, if proxy settings are detected (for example, when a *_proxy
    environment variable like http_proxy is set), ProxyHandler is default
    installed and makes sure the requests are handled through the proxy.

查看函数的属性

import urllib.request
print(dir(urllib.request.urlopen))
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

查看内建函数的属性

import sys
print(sys.builtin_module_names)
('_abc', '_ast', '_bisect', '_blake2', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', '_codecs_tw', '_collections', '_csv', '_datetime', '_functools', '_heapq', '_imp', '_io', '_json', '_locale', '_lsprof', '_md5', '_multibytecodec', '_opcode', '_operator', '_pickle', '_random', '_sha1', '_sha256', '_sha3', '_sha512', '_signal', '_sre', '_stat', '_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', '_winapi', 'array', 'atexit', 'audioop', 'binascii', 'builtins', 'cmath', 'errno', 'faulthandler', 'gc', 'itertools', 'marshal', 'math', 'mmap', 'msvcrt', 'nt', 'parser', 'sys', 'time', 'winreg', 'xxsubtype', 'zipimport', 'zlib')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值