系统工具-获取模块文档

获取模块文档

学习用Python来编写系统代码在很大程度上就是学习Python的系统模块。目前有多种方式可获取这些模块的属性说明和参考手册。

获取模块的属性列表:

[root@localhost ~]# python3
Python 3.6.1 (default, Jul 12 2017, 09:58:07) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> dir(sys) 
['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe', '_git', '_home', '_xoptions', 'abiflags', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'set_asyncgen_hooks', 'set_coroutine_wrapper', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions']

dir函数会简单地返回一个列表,其中包含了带属性对象的所有属性的字符串名称。这是一种在交互提示符下唤醒对模块的记忆的便捷方式。

>>> sys.version
'3.6.1 (default, Jul 12 2017, 09:58:07) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)]'
>>> 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;
## 此处省略多行

分页显示文档字符串

使用print函数可以将换行符 进行换行显示出来:

>>> 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.

### 省略多行

由于print 本身并不完成页面滚动或分页显示,因此还可以使用help函数:

>>> help(sys)
Help on built-in module sys:

NAME
    sys

MODULE REFERENCE
    https://docs.python.org/3.6/library/sys
    
    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.

### 省略多行

help函数是PyDoc系统提供的接口之一。PyDoc系统是Python自带的标准库代码,可将对象相关的文档(文档字符串和结构信息等)呈现为格式化后的形式。

字符串方法基础知识

find 函数返回子字符串第一个匹配所在的偏移位置,replace 函数则完成全局搜索与替换。和所有字符串操作一样,replace 函数返回的是新字符串,而不是改变既有字符串。

>>> mystr = 'xxxSPAMxxx'
>>> mystr.find('SPAM')           # 返回首个匹配的位置偏移
3
>>> mystr = 'xxaaxxaa'
>>> mystr.replace('aa', 'SPAM')  # 全局替换
'xxSPAMxxSPAM'
>>> mystr = 'xxxSPAMxxx'
>>> 'SPAM' in mystr       # 子字符串搜索/测试
True
>>> 'Ni' in mystr         # 没找到时
False
>>> mystr.find('Ni')
-1
>>> mystr = '	 Ni
'
>>> mystr.find('Ni')
2
>>> mystr.strip()   # 取出空白分隔符
'Ni'
>>> mystr.rstrip()  # 同上,只不过在右侧进行
'	 Ni'

字符串方法:

>>> mystr = 'SHRUBBERY'
>>> mystr.lower()     # 大小写转换
'shrubbery'
>>> mystr.isdigit()   # 内容测试
False
>>> mystr.isalpha()
True

>>> import string        # 环境预设: 可在 ‘in’ 等语句中使用
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.whitespace    # 空白分隔符
' 	

x0bx0c'

用字符串作为分隔符来分割原始字符串,也可以用子字符串将它们连接起来:

>>> mystr = 'aaa,bbb,ccc'
>>> mystr.split(',')  # 分割为子字符串组成的列表
['aaa', 'bbb', 'ccc']

>>> mystr = 'a b
c
d'
>>> mystr.split()     # 默认分隔符: 空格
['a', 'b', 'c', 'd']

>>> delim = 'NI'
>>> delim.join(['aaa', 'bbb', 'ccc'])  # 连接子字符串列表
'aaaNIbbbNIccc'

>>> ' '.join(['A', 'dead', 'parrot'])  # 在期间添加空格符
'A dead parrot'
>>> '-'.join(['A', 'dead', 'parrot'])  # 在期间添加 -
'A-dead-parrot'

>>> chars = list('Lorreta')  # 转换为字符组成的列表
>>> chars
['L', 'o', 'r', 'r', 'e', 't', 'a']
>>> chars.append('!')
>>> ''.join(chars)           # 生成为字符串: 分隔符为空
'Lorreta!'

实际上,我们可以组合split 和join 来模拟前面介绍的replace 函数:

>>> mystr = 'xxaaxxaa'
>>> 'SPAM'.join(mystr.split('aa'))
'xxSPAMxxSPAM'
>>> mystr.split('aa')
['xx', 'xx', '']

另外 Python 不会自动将字符串转换为数字:

>>> int("42"), eval("42")   # 字符串转换为整型
(42, 42)
>>> str(42), repr(42)       # 整型转换为字符串
('42', '42')
>>> ("%d" % 42), '{:d}'.format(42)  # 分别借助格式化表达式和方法
('42', '42')
>>> "42" + str(1), int("42") + 1    # 分别为连接和加法
('421', 43)

文件操作基础知识

open函数,打开命令行中给出的外部文件,并借助文件对象的read 方法将文件的文本一次性读入内存。

文件内容加载为字符串;

固定大小的字节集合加载为字符串;

文件的内容加载为单行字符串组成的列表;

文件的下一行加载为字符串。

open('file').read()       # 将整个文件读取为字符串
open('file').read(N)      # 将后面N个字节读取为字符串
open('file').readlines()  # 将整个文件读取为单行字符串组成的列表
open('file').readline()   # 跨过 '
' 读取下一行

简单文件读写:

>>> file = open('spam.txt','w')      # 创建文件 spam.txt
>>> file.write(('spam' * 5) + '
')  # 写入文本:返回所写入的#个字符
21
>>> file.close()
>>> file = open('spam.txt')       # 或者用open('spam.txt').read()
>>> text = file.read()            # 读取为字符串
>>> text
'spamspamspamspamspam
'

回忆一下,Python每个模块都有一个内置的__name__变量,当且仅当文件作为程序运行时,而不是作为库导入时,Python会将这个变量设为__mian__字符串。因此,当这个脚本代码作为顶层程序运行时,下面的if 判断将为真,但在其他地方被导入时则为假:

if __name__ == '__main__':
    # ...代码执行入口...
原文地址:https://www.cnblogs.com/chengtai/p/7356414.html