Python入门教程 | Python 常用标准库概览

Python3 标准库概览

Python 标准库非常庞大,所提供的组件涉及范围十分广泛,使用标准库我们可以让您轻松地完成各种任务。

以下是一些 Python3 标准库中的模块:

  • os 模块:os 模块提供了许多与操作系统交互的函数,例如创建、移动和删除文件和目录,以及访问环境变量等。

  • sys 模块:sys 模块提供了与 Python 解释器和系统相关的功能,例如解释器的版本和路径,以及与 stdin、stdout 和 stderr 相关的信息。

  • time 模块:time 模块提供了处理时间的函数,例如获取当前时间、格式化日期和时间、计时等。

  • datetime 模块:datetime 模块提供了更高级的日期和时间处理函数,例如处理时区、计算时间差、计算日期差等。

  • random 模块:random 模块提供了生成随机数的函数,例如生成随机整数、浮点数、序列等。

  • math 模块:math 模块提供了数学函数,例如三角函数、对数函数、指数函数、常数等。

  • re 模块:re 模块提供了正则表达式处理函数,可以用于文本搜索、替换、分割等。

  • json 模块:json 模块提供了 JSON 编码和解码函数,可以将 Python 对象转换为 JSON 格式,并从 JSON 格式中解析出 Python 对象。

  • urllib 模块:urllib 模块提供了访问网页和处理 URL 的功能,包括下载文件、发送 POST 请求、处理 cookies 等。

操作系统接口

os模块提供了不少与操作系统相关联的函数。

>>> import os
>>> os.getcwd()      # 返回当前的工作目录
'C:\\Users\\Lenovo'
>>> os.chdir(r'C:\Users\Lenovo\Desktop') # 修改当前的工作目录 使用r原始字符串(raw string),可以不需要双反斜杠
>>> os.system('mkdir today') # 执行windows shell系统命令 mkdir,生成名为today的文件夹
0

建议使用 “import os” 风格而非 “from os import *”。这样可以保证随操作系统不同而有所变化的 os.open() 不会覆盖内置函数 open()。

在使用 os 这样的大型模块时内置的 dir() 和 help() 函数非常有用:

>>> import os
>>> dir(os)
['DirEntry', 'EX_OK', 'F_OK', 'GenericAlias', 'Mapping', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_AddedDllDirectory', '_Environ', '__all__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_check_methods', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_walk', '_wrap_close', 'abc', 'abort', 'access', 'add_dll_directory', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'unsetenv', 'urandom', 'utime', 'waitpid', 'waitstatus_to_exitcode', 'walk', 'write']
>>> help(os)
Help on module os:

NAME
    os - OS routines for NT or Posix depending on what system we're on.

MODULE REFERENCE
    https://docs.python.org/3.11/library/os.html

    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 exports:
      - all functions from posix or nt, e.g. unlink, stat, etc.
      - os.path is either posixpath or ntpath
      - os.name is either 'posix' or 'nt'
      - os.curdir is a string representing the current directory (always '.')
      - os.pardir is a string representing the parent directory (always '..')
      - os.sep is the (or a most common) pathname separator ('/' or '\\')
      - os.extsep is the extension separator (always '.')
      - os.altsep is the alternate pathname separator (None or '/')
      - os.pathsep is the component separator used in $PATH etc
      - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
      - os.defpath is the default search path for executables
      - os.devnull is the file path of the null device ('/dev/null', etc.)

-- More  --

针对日常的文件和目录管理任务,shutil 模块提供了一个易于使用的高级接口:

C:\Users\Lenovo>cd Desktop #切换到桌面文件夹下
C:\Users\Lenovo\Desktop>python  # 进入python交互模式
Python 3.11.4 (tags/v3.11.4:d2340ef, Jun  7 2023, 05:45:37) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import shutil #导入shutil模块
>>> shutil.copyfile('test.txt', 'test1.txt') #复制桌面的test.txt文件并生成test1.txt
'test1.txt'
>>> shutil.move('sourceFolder', 'targetFolder') #sourceFolder文件夹移动到targetFolder文件夹下
'targetFolder\\sourceFolder'
>>>

文件通配符

glob模块提供了一个函数用于从目录通配符搜索中生成文件列表:

>>> import glob #导入模块 
>>> glob.glob('*.py') #匹配当前目录下的所有文件名为.py的文件
['dog.py', 'fibo.py', 'support.py', 'support1.py', 'test.py', 'using_name.py']

命令行参数

通用工具脚本经常调用命令行参数。这些命令行参数以链表形式存储于 sys 模块的 argv 变量。
在Python中,sys.argv是一个列表,它包含了当你运行一个Python脚本时所用的命令行参数。sys.argv[0]是脚本的名字(也就是正在执行的.py文件),sys.argv[1]是第一个命令行参数,sys.argv[2]是第二个命令行参数,依此类推。

这是一个简单的例子来展示如何使用sys.argv:

import sys  
  
def main(argv):  
    # argv[0] 是脚本的名字  
    print(f"脚本的名字是: {argv[0]}")  
  
    # 从 argv[1] 开始,是我们传入的命令行参数  
    for i in range(1, len(argv)):  
        print(f"参数 {i} 是: {argv[i]}")  
  
if __name__ == "__main__":  
    main(sys.argv)

如果你把这个脚本保存为script.py,然后在命令行中运行python script.py arg1 arg2 arg3,你将看到以下的输出:

C:\Users\Lenovo\Desktop>python script.py arg1 arg2 arg3
脚本的名字是: script.py
参数 1 是: arg1
参数 2 是: arg2
参数 3 是: arg3

错误输出重定向和程序终止

sys 还有 stdin,stdout 和 stderr 属性,即使在 stdout 被重定向时,后者也可以用于显示警告和错误信息。

>>> import sys
>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one
47
>>>

大多脚本的定向终止都使用 "sys.exit()"或者“exit()”。

字符串正则匹配

re模块为高级字符串处理提供了正则表达式工具。对于复杂的匹配和处理,正则表达式提供了简洁、优化的解决方案:

>>> import re #导入模块
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') #‘which foot or hand fell fastest’ 匹配字符串中的以空格和f开头的字符串
['foot', 'fell', 'fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'

如果只需要简单的功能,应该首先考虑字符串方法,因为它们非常简单,易于阅读和调试:

>>> import re #导入模块
>>> 'tea for too'.replace('too', 'two') # 将文本中的too替换为tweo
'tea for two'

数学

math模块为浮点运算提供了对底层C函数库的访问:

>>> import math #导入math模块
>>> math.cos(math.pi / 4) 
0.70710678118654757
>>> math.log(1024, 2) #求1024 计算以 2 为底数的对数
10.0

random提供了生成随机数的工具。

>>> import random #导入模块
>>> random.choice(['apple', 'pear', 'banana']) # 在集合中随机输出一个元素
'apple'
>>> random.sample(range(100), 10)   # 在0-100中随机抽取10个数字,不包含100
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random()    # 在0-1之间随机生成一个小数
0.17970987693706186
>>> random.randrange(6)    # 在0-6中随机返回一个证书 不包含6
4

访问互联网

有几个模块用于访问互联网以及处理网络通信协议。其中最简单的两个是用于处理从 urls 接收的数据的 urllib.request

>>> from urllib.request import urlopen
>>> for line in urlopen('https://www.baidu.com/'):
...     line = line.decode('utf-8')  # Decoding the binary data to text.
...     print(line)

#输出百度网页文本...

日期和时间

datetime 模块为日期和时间处理同时提供了简单和复杂的方法。

支持日期和时间算法的同时,实现的重点放在更有效的处理和格式化输出。

>>> import datetime #导入模块
>>> current_datetime = datetime.datetime.now() #获取当前日期和时间
>>> print(current_datetime)
2023-10-04 21:35:23.999185
>>> current_date = datetime.date.today() #获取当前日期
>>> print(current_date)
2023-10-04
>>> formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S") #格式化日期
>>> print(formatted_datetime)
2023-10-04 21:35:23
>>>

该模块还支持时间处理:

>>> from datetime import date   #导入了 datetime 模块中的 date 类
>>> now = date.today() #当前日期
>>> now
datetime.date(2023, 10, 4)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") #格式化输出时间
'10-04-23. 04 Oct 2023 is a Wednesday on the 04 day of October.'
>>> birthday = date(1991, 9, 20) #创建了一个表示生日的日期对象
>>> age = now - birthday  # 计算两个日期之间的时间差
>>> age.days  # 变量age的days属性,表示时间差的天数
11702

数据压缩

以下模块直接支持通用的数据打包和压缩格式:zlib,gzip,bz2,zipfile,以及 tarfile

>>> import zlib #导入模块
>>> s = b'witch which has which witches wrist watch'
>>> len(s) 输出长度
41
>>> zlib.crc32(s)  进行 CRC32 校验
226805979
>>> t = zlib.compress(s) #压缩文本
>>> len(t) 输出长度
37
>>> print(t)
b'x\x9c+\xcf,I\xceP(\xcf\xc8\x04\x92\x19\x89\xc5PV9H4\x15\xc8+\xca,.Q(O\x04\xf2\x00D?\x0f\x89'
>>> s=zlib.decompress(t) #解压
>>> print(s)
b'witch which has which witches wrist watch'
>>> zlib.crc32(s)  进行 CRC32 校验
226805979
>>>
  • CRC32 校验和也可以用于数据的完整性验证。例如,当一个文件被复制到另一个位置时,可以使用 CRC32 校验和来验证复制后的文件是否与原始文件相同。计算文件的 CRC32 校验和后,将校验和存储在另一个位置或与文件一起传输。然后,在需要验证文件完整性时,可以重新计算文件的 CRC32 校验和,并将其与原始校验和进行比较。

性能度量

有些用户对了解解决同一问题的不同方法之间的性能差异很感兴趣。Python 提供了一个度量工具,为这些问题提供了直接答案。

例如,使用元组封装和拆封来交换元素看起来要比使用传统的方法要诱人的多,timeit 证明了现代的方法更快一些。
交换a和b的值

>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() #计算执行代码耗时
0.03332749998662621
>>> Timer('a,b = b,a', 'a=1; b=2').timeit() #计算执行代码耗时
0.024641399970278144 

相对于 timeit 的细粒度,profilepstats 模块提供了针对更大代码块的时间度量工具。

测试模块

开发高质量软件的方法之一是为每一个函数开发测试代码,并且在开发过程中经常进行测试

doctest模块提供了一个工具,扫描模块并根据程序中内嵌的文档字符串执行测试。

测试构造如同简单的将它的输出结果剪切并粘贴到文档字符串中。

doctest 是 Python 的一个内置模块,它允许你通过在你的代码中嵌入可执行的示例来编写单元测试。这些示例可以被 doctest 模块提取并执行,然后比较它们的实际输出和期望输出。如果两者匹配,测试通过;否则,测试失败。

下面是一个使用 doctest 的简单示例:

def add(a, b):  
    """  
    This function adds two numbers.  
      
    >>> add(1, 2)  
    3  
    >>> add(-1, -2)  
    -3  
    """  
    return a + b  
  
if __name__ == "__main__":  
    import doctest  
    doctest.testmod()

在这个例子中,add 函数的文档字符串包含了两个 doctest 示例。当你运行这个脚本时,doctest.testmod() 会找到这些示例并执行它们,然后比较它们的实际输出和期望输出。

这个脚本的输出应该是这样的:

**********************************************************************  
File "__main__", line 7, in __main__.add  
Failed example:  
    add(1, 2)  
Expected:  
    3  
Got:  
    3  
**********************************************************************  
File "__main__", line 9, in __main__.add  
Failed example:  
    add(-1, -2)  
Expected:  
    -3  
Got:  
    -3  
**********************************************************************  
2 items had failures:  
   1 of   2 in __main__.add  
   2 of   2 in __main__  
***Test Failed*** 2 failures.
  • Expected(预期结果)和Got(实际结果)相同,表示测试用例正确。

unittest模块不像 doctest模块那么容易使用,不过它可以在一个独立的文件里提供一个更全面的测试集:
创建一个test.py的脚本文件,代码如下:

import unittest

def average(values):
     return sum(values) / len(values)

class TestStatisticalFunctions(unittest.TestCase):

    def test_average(self):
        self.assertEqual(average([20, 30, 70]), 40.0)
        self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
        self.assertRaises(ZeroDivisionError, average, [])
        self.assertRaises(TypeError, average, 20, 30, 70)

unittest.main() # Calling from the command line invokes all tests

执行test.py文件输出如下:

C:\Users\Lenovo\Desktop>python test.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

以上我们看到的只是 Python3 标准库中的一部分模块,还有很多其他模块可以在官方文档中查看完整的标准库文档:https://docs.python.org/zh-cn/3/library/index.html

你可能感兴趣的:(python基础入门,python,开发语言)