语句与语法笔记:学会python中_doc_和pydoc——python学习手册笔记之3

学习笔记 专栏收录该内容
104 篇文章 0 订阅

标题## 语句与语法:学会python中的_doc_和pydoc——python学习手册笔记之3

光看书不练习很难学好python,光看书不做点学习笔记,恐怕连书本的东西也是半知半解,不知所云。这手册的第三部分草草看完,好像还没有出现多少练的东西,这个笔记3,算是对于这个第三部分的读后复习吧。
阅读中感觉那个导入的函数import很重要,先简略理解一下import,因为它的确有点复杂,也就先做粗略了解,在实践中继续理解。这import之后的sys也是这样,要非常了解它们,你还得有一些非常的经验不可,也是略知再说。

标题一、两个函数:import和sys

函数import是用来导入模块的指令,你要导入math模块,那在python解释器中就使用import math,而你要导入sys模块,你在解释器中照葫芦画瓢,那就打上import sys。
本篇笔记关注sys中的文档字符串资源,所以我们导入的就是sys。
何谓sys呢?这个稍微多一点文字,它大概来自system一词,取其前三个字母sys。我录下python文本中对它的描述:

这个模块提供入口给某些对象,这些对象在解释器中被使用或者维护,同时,它也提供函数以便于解释器深度地交互使用(英文原文:This module provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the interpret)。

于是我们就开始在解释器中导入sys,以便进一步理解如何在python中编写文档,以及使用它现成的文档(document)资源,所以本笔记主要复习的是第15章的内容,它的主题就是文档(p444-469),如教材所言,我们接触的只是冰山一角。

标题二、一个有趣的指令:doc

于是我们导入sys:使用import sys
代码

略去有关目录查找对象属性的那一部分,把焦点集中在文档字符串(docstrings)的指令__doc__上面.我们先做导入文本的练习。
第一步:做一个docstrings.py的代码,其中包含用三引号围住的文本符号。
第二步:在python解释器中运行这个代码,使用导入import,把刚才的文件名置入其后。
第三步:使用打印函数。
请看代码

>>> import docstrings
25

    that interact strongly to the
    Module documentation Words Go Here

>>> print(docstrings.__doc__)

This module provides access to
some objects used or maintained
by the interpreter and to functions
that interact strongly with the interpret
Module documentation Words Go Here

只要是代码中的文本文件都可以用这个_doc_导入进来。第一段是代码中部的文本。后面一段是代码头部的文本,都是用print函数来打印那些想调用的文本。这是自制代码文本的调用,打印,使用的是双下划线的_doc_函数。
这个函数不仅可以用来打印自制文本,还可以用来打印内置文档字符串。这样的字符串用sys文本作为实例,这就用上我们在开头说明的那个sys模块。
请看第二个代码

>>> import sys
>>> print(sys.__doc__)
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.

Dynamic objects:

argv -- command line arguments; argv[0] is the script pathname if known
path -- module search path; path[0] is the script directory, else ''
modules -- dictionary of loaded modules

displayhook -- called to show results in an interactive session
excepthook -- called to handle any uncaught exception other than SystemExit
  To customize printing in an interactive session or to install a custom
  top-level exception handler, assign other functions to replace these.

stdin -- standard input file object; used by input()
stdout -- standard output file object; used by print()
stderr -- standard error object; used for error messages
  By assigning other file objects (or objects that behave like files)
  to these, it is possible to redirect all of the interpreter's I/O.

last_type -- type of last uncaught exception
last_value -- value of last uncaught exception
last_traceback -- traceback of last uncaught exception
  These three are only available in an interactive session after a
  traceback has been printed.

Static objects:

builtin_module_names -- tuple of module names built into this interpreter
copyright -- copyright notice pertaining to this interpreter
exec_prefix -- prefix used to find the machine-specific Python library
executable -- absolute path of the executable binary of the Python interpreter
float_info -- a named tuple with information about the float implementation.
float_repr_style -- string indicating the style of repr() output for floats
hash_info -- a named tuple with information about the hash algorithm.
hexversion -- version information encoded as a single integer
implementation -- Python implementation information.
int_info -- a named tuple with information about the int implementation.
maxsize -- the largest supported length of containers.
maxunicode -- the value of the largest Unicode code point
platform -- platform identifier
prefix -- prefix used to find the Python library
thread_info -- a named tuple with information about the thread implementation.
version -- the version of this interpreter as a string
version_info -- version information as a named tuple
dllhandle -- [Windows only] integer handle of the Python DLL
winver -- [Windows only] version number of the Python DLL
_enablelegacywindowsfsencoding -- [Windows only]
__stdin__ -- the original stdin; don't touch!
__stdout__ -- the original stdout; don't touch!
__stderr__ -- the original stderr; don't touch!
__displayhook__ -- the original displayhook; don't touch!
__excepthook__ -- the original excepthook; don't touch!

Functions:

displayhook() -- print an object to the screen, and save it in builtins._
excepthook() -- print an exception and its traceback to sys.stderr
exc_info() -- return thread-safe information about the current exception
exit() -- exit the interpreter by raising SystemExit
getdlopenflags() -- returns flags to be used for dlopen() calls
getprofile() -- get the global profiling function
getrefcount() -- return the reference count for an object (plus one :-)
getrecursionlimit() -- return the max recursion depth for the interpreter
getsizeof() -- return the size of an object in bytes
gettrace() -- get the global debug tracing function
setdlopenflags() -- set the flags to be used for dlopen() calls
setprofile() -- set the global profiling function
setrecursionlimit() -- set the max recursion depth for the interpreter
settrace() -- set the global debug tracing function

许多内置函数的文本说明,都可以通过这种导入获得。
再看第三个代码:

>>> print(map.__doc__)
map(func, *iterables) --> map object

Make an iterator that computes the function using arguments from
each of the iterables.  Stops when the shortest iterable is exhausted.

标题三、__doc__的延申:两种方式的Pydoc工具

pydoc是提取文档字符串及相关结构的工具,其实就是那个__doc__的延申。这个工具有两个提取方式,一种方式就是使用内置的help函数,通过解释器来启用pydoc。依然是使用导入import,把那个sys给导入进来。所以,这里依然用得着开头说明过的import和sys函数。
(一)使用help的Pydoc工具
第四个代码:

>>> import sys
>>> help(sys.gettrace)
Help on built-in function gettrace in module sys:

gettrace()
    Return the global debug tracing function set with sys.settrace.

    See the debugger chapter in the library manual.

省掉sys也是可能的,例如以下文本调用:
第五个代码:

>>> help('re')
Help on module re:

NAME
    re - Support for regular expressions (RE).

MODULE REFERENCE
    https://docs.python.org/3.9/library/re

    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module provides regular expression matching operations similar to
    those found in Perl.  It supports both 8-bit and Unicode strings; both
    the pattern and the strings being processed can contain null bytes and
    characters outside the US ASCII range.

    Regular expressions can contain both special and ordinary characters.
    Most ordinary characters, like "A", "a", or "0", are the simplest
    regular expressions; they simply match themselves.  You can
    concatenate ordinary characters, so last matches the string 'last'.

    The special characters are:
        "."      Matches any character except a newline.
        "^"      Matches the start of the string.
        "$"      Matches the end of the string or just before the newline at
                 the end of the string.
        "*"      Matches 0 or more (greedy) repetitions of the preceding RE.
                 Greedy means that it will match as many repetitions as possible.
        "+"      Matches 1 or more (greedy) repetitions of the preceding RE.
        "?"      Matches 0 or 1 (greedy) of the preceding RE.
        *?,+?,?? Non-greedy versions of the previous three special characters.
        {m,n}    Matches from m to n repetitions of the preceding RE.
        {m,n}?   Non-greedy version of the above.
        "\\"     Either escapes special characters or signals a special sequence.
        []       Indicates a set of characters.
                 A "^" as the first character indicates a complementing set.
        "|"      A|B, creates an RE that will match either A or B.
        (...)    Matches the RE inside the parentheses.
                 The contents can be retrieved or matched later in the string.
        (?aiLmsux) The letters set the corresponding flags defined below.
        (?:...)  Non-grouping version of regular parentheses.
        (?P<name>...) The substring matched by the group is accessible by name.
        (?P=name)     Matches the text matched earlier by the group named name.
        (?#...)  A comment; ignored.
        (?=...)  Matches if ... matches next, but doesn't consume the string.
-- More  --

这里的more表示还可以继续提供,但篇幅太长,截取一段表示就行。
最有趣的是全浏览器模式,值得在这里复习理解,欣赏这python语言的奇妙。
(二)Pydoc的全浏览器:启用win10启动器的Pycoc模式
解释器需回到文件索引状态,用quit()回到这个状态。

>>> quit()
PS C:\Users\Lenovo\py文件夹> py -3 -m pydoc -b
Server ready at http://localhost:59597/
Server commands: [b]rowser, [q]uit
server>
Server commands: [b]rowser, [q]uit
server> q
Server stopped
PS C:\Users\Lenovo\py文件夹> cd..
PS C:\Users\Lenovo> py -3 -m pydoc -b
Server ready at http://localhost:59692/
Server commands: [b]rowser, [q]uit
server>

使用py -3 -m pydoc -b,启动Windows启动器,则出现上述页面,接着闪现彩色浏览器页面
在这里插入图片描述
可以在这个页面分别调用模块,主题和关键字查询,为寻找文档字符串提供了彩色图,这个颜色还可以自调,这留给以后再去把握吧。
很有趣的这个手册第三部分,特别是这个文档字符串的使用。可惜所要求的for循环练习还没有做,也是留给以后再做吧。

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值