• 技术文章 >Python技术 >Python高级

    详解Python标准库

    silencementsilencement2019-07-17 13:22:39原创2287

    操作系统接口

    os 模块提供了大量和操作系统进行交互的函数:

    1

    2

    3

    4

    5

    6

    >>> import os

    >>> os.getcwd()      # 返回当前工作路径

    'C:\\Python37'

    >>> os.chdir('/server/accesslogs')   # 改变当前工作路径

    >>> os.system('mkdir today')   # 调用系统shell自带的mkdir命令

    0

    请确保使用 import os 而不是 from os import *。第二种方法会导致 os.open() 覆盖系统自带的 open() 函数,这两个函数的功能有很大的不同。

    自带的 dir() 和 help() 函数在使用大型模块如 os 时能够成为非常有用的交互工具:

    1

    2

    3

    4

    5

    >>> import os

    >>> dir(os)

    <返回一个包含os模块所有函数的list>

    >>> help(os)

    <返回一个从os模块docstring产生的手册>

    对于日常的文件或者目录管理任务,shutil 模块提供了更高层次的接口,可以让用户更容易地使用:

    1

    2

    3

    4

    5

    >>> import shutil

    >>> shutil.copyfile('data.db', 'archive.db')

    'archive.db'

    >>> shutil.move('/build/executables', 'installdir')

    'installdir'

    文件通配符

    glob 模块提供了一个函数,用于在目录中进行通配符搜索,得到一个文件列表。

    1

    2

    3

    >>> import glob

    >>> glob.glob('*.py')

    ['primes.py', 'random.py', 'quote.py']

    命令行参数

    常见的工具类脚本经常需要处理命令行参数。 这些参数储存在 sys 模块的 argv 属性中,作为一个列表存在。例如,以下是在命令行运行 python demo.py one two three 的结果输出:

    1

    2

    3

    >>> import sys

    >>> print(sys.argv)

    ['demo.py', 'one', 'two', 'three']

    getopt 模块使用 Unix 约定的 getopt() 函数处理 sys.argv 。更强大、灵活的命令行处理由 argparse 模块提供。

    错误输出重定向和退出程序

    sys 模块有 stdin,stdout 和 stderr 这些属性。后者在处理警告和错误信息时非常有用,就算 stdout 被重定向了,还是能看见错误信息:

    1

    2

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

    Warning, log file not found starting a new one

    退出程序最直接的方法是用 sys.exit()。

    字符串匹配

    re 模块为字符串的进阶处理提供了正则表达式的工具。对于复杂的匹配操作,正则表达式给出了简洁有效的解决方案:

    1

    2

    3

    4

    5

    >>> import re

    >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')

    ['foot', 'fell', 'fastest']

    >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')

    'cat in the hat'

    当只需要简单的功能时,采用字符串的方法更简洁易懂:

    1

    2

    >>> 'tea for too'.replace('too', 'two')

    'tea for two'

    数学库

    math 模块可以访问 C 语言编写的浮点类型数学库函数:

    1

    2

    3

    >>> import math

    >>> math.cos(math.pi / 4)0.70710678118654757

    >>> math.log(1024, 2)10.0

    random 模块提供了进行随机选择的工具:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    >>> import random

    >>> random.choice(['apple', 'pear', 'banana'])

    'apple'

    >>> random.sample(range(100), 10)   # 不重复抽样

    [30, 83, 16, 4, 8, 81, 41, 50, 18, 33]

    >>> random.random()    # 随机的 float 类型输出

    0.17970987693706186

    >>> random.randrange(6)    # 从 range(6) 的返回范围内产生随机数

    4

    网络请求

    有一大堆模块可以访问网络并根据各自网络协议来处理数据。其中最简单的两个分别是用于从 URL 获取数据的 urllib.request 和用于发送邮件的 smtplib :

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    >>> from urllib.request import urlopen

    >>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:

    ...     for line in response:

    ...         line = line.decode('utf-8')  # 解码.

    ...         if 'EST' in line or 'EDT' in line:  # 查看是否是EST或EDT时间

    ...             print(line)

     

    <BR>Nov. 25, 09:43:32 PM EST

     

    >>> import smtplib

    >>> server = smtplib.SMTP('localhost')

    >>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',

    ... """To: jcaesar@example.org

    ... From: soothsayer@example.org

    ...

    ... Beware the Ides of March.

    ... """)

    >>> server.quit()

    日期和时间

    datetime 模块提供了多种用于简单处理和复杂处理日期和时间的类。支持日期时间的运算、时间解析、格式化输出等,实现上重点优化了效率。模块也支持了时区的概念。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    >>> # 日期对象能非常方便的构建和输出

    >>> from datetime import date

    >>> now = date.today()

    >>> now

    datetime.date(2003, 12, 2)

    >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")

    '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

     

    >>> # 支持日期运算

    >>> birthday = date(1964, 7, 31)

    >>> age = now - birthday

    >>> age.days

    14368

    专题推荐:标准库
    上一篇:初学者必看的Python模块讲解 下一篇:Python中lambda表达式的优缺点及使用场景

    相关文章推荐

    • 转行IT为什么必须学Python?Python的职业发展是什么?• 初学者必看的Python模块讲解

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网