Python Revisited Day 05(模块)

5.1 模块与包

在命令行输入以下,检查模块是否存在

python -c "import 模块名"

在这里插入图片描述
表示没有相应的模块。
对于自定义模块,可以采用首字母大写来避免与标准库重复。

5.1.1 包

Graphics/
    __init__.py
    Bmp.py
    Jpeg.py
    Png.py
    Tiff.py
    Xpm.py

上面目录包含了_init_.py文件,使其成了一个包。只要包目录是程序目录的子目录,或者存在于Python路径中,就可以导入这些模块。

import Graphics.Bmp

若我们编辑_init_.py为:

#__init__.py
__all__ = ['Bmp', 'Jpeg', 'Png', 'Tiff', 'Xpm']

那么,就可以使用下面的命令:

from Graphics import *

多层嵌套也可以的。

Tips docstring 测试 doctest

#testdoc.py
def simpledoc(real, dream='sky'):
    """ Returns the text I can not control now...

    real is any string; dream is the same as well, while it has default value 'sky'.
    Of course, your different people has various dreams, but we all need to confront
    the real life.
    >>> simpledoc('god')
    'haha happy'
    >>> simpledoc('god', 'earth')
    "don't cry, go forward..."
    """

    if real == 'god' and dream == 'sky':
        return "haha happy"
    else:
        return "don't cry, go forward..."


if __name__ == "__main__":
    import doctest
    doctest.testmod()

在命令行内输入(路径啥的得弄好)

python testdoc.py -v

得到:

Trying:
    simpledoc('god')
Expecting:
    'haha happy'
ok
Trying:
    simpledoc('god', 'earth')
Expecting:
    "don't cry, go forward..."
ok
1 items had no tests:
    __main__
1 items passed all tests:
    2 tests in __main__.simpledoc
2 tests in 2 items.
2 passed and 0 failed.
Test passed.

5.2 Python 标准库概览

5.2.1 字符串处理

String

Struct

struct模块提供了struct.pack(), struct.unpack()以及其他一些函数,还提供了struct.Struct()类。struct.pack()函数以一个struct格式化字符串以及一个或多个值为参数,并返回一个bytes对象,其中存放的是按照改格式规范表示的所有这些参数值。

data = struct.pack("<2h", 11, -9) # data == b'\x0b\x00\xf7\xff'
items = struct.unpack("<2h", data) # items == (11,-9)
TWO_SHORTS = struct.Struct("<2h")
data = TWO_SHORTS.pack(11, -9)
items = TWO_SHORTS.unpack(data) # (data, items)

格式是"<2h",表示,将俩个有符号的16位整数以小端的方法打包在一起,其中:
"\x0b\x00" 表示11,事实上,11的16进制表示为"0x000b",以小端的方式存储就是"\x0b\x00",即低位在前,高位在后。
"\xf7\xff"表示-9,-9的16进制表示为"\xff\xf7",注意,因为是负数,所以-9需要通过9的补码来表示。9 --> 0b00001001, 其反码为:0b11110110, 补码等于反码加1:0b11110111, 所以,16进制就是:"\xff\xf7"

另外: "<H16s" 表示 第一个参数为16位无符号整数, 第二个参数为长度16的字节字符串。

符号 符号说明
< little-endian 小端 低位 --> 高位
> | ! big-endian 大端 高位 --> 低位
b 8位有符号整数
B 8位无符号整数
h 16位有符号整数
H 16位无符号整数
i 32位有符号整数
I 32位无符号整数
q 64位有符号整数
Q 64位无符号整数
f 32位浮点数
d 64位浮点数
? 布尔型
s bytes或bytearray

difflib

re

io.StringIO 类

sys.stdout = io.StringIO()

5.2.3 命令行设计

fileinput

optparse

5.2.4 数学与数字

int

float

complex

decimal

fractions

math

cmath 用于复数数学函数

random

Tips isinstance(a, type)

isinstance(1, int) #True
isinstance(1.0, int) #False
isinstance(1.0, str) #False
isinstance([], list) #list

Scipy

Numpy

5.2.5 时间与日期

import calendar, datetime, time

moon_datetime_a = datetime.datetime(1969, 7, 20,
                                    20, 17, 40) #datetime.datetime(1978, 7, 20, 20, 17, 40)
moon_time = calendar.timegm(moon_datetime_a.utctimetuple()) #269813860
moon_datetime_b = datetime.datetime.utcfromtimestamp(moon_time) #datetime.datetime(1978, 7, 20, 20, 17, 40)
moon_datetime_a.isoformat() #datetime.datetime(1978, 7, 20, 20, 17, 40)
moon_datetime_b.isoformat() #datetime.datetime(1978, 7, 20, 20, 17, 40)
time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(moon_time)) #'1978-07-20T20:17:40'

calendar

datatime

dateutil

mxDateTime

5.2.7 算法与组合数据类型

bisect

heapq

collections

array

weakref

5.2.8 文件格式、编码与数据持久性

base64 --> RFC 3548

quopri --> quoted-printable

uu --> uuencoded

xdrlib

bz2 --> .bz2

gzip --> .gz

tarfile --> .tar | .tar.gz | .tar.bz2

zipfile --> .zip

aifc --> AIFF

wave --> .wav

audioop

sndhdr

configparser

pickle

shelve

DBM

5.2.9 文件、目录与进程处理

Shutil

tempfile --> 临时文件与目录

filecmp --> 文件目录的比较

subprocess | multiprocessing

os --> 对操作系统功能的访问接口

date_from_name = {}
path = "."
for name in os.listdir(path):
    fullname = os.path.join(path, name)
    if os.path.isfile(fullname):
        date_from_name[fullname] = os.path.getmtime(fullname)
date_from_name
import os, collections

data = collections.defaultdict(list)
path = "C:/Py"  #or "C:\\Py"
for root, dirs, files in os.walk(path):
    for filename in files:
        fullname = os.path.join(root, filename)
        key = (os.path.getsize(fullname), filename)
        data[key].append(fullname)


for key, value in data.items():

    print(key, value)

5.2.10 网络与Internet程序设计

socket --> 大多数基本的网络功能

http.cookies, http.cookiejar --> 管理cookies

http.client --> HTTP请求

urllib

html.parser --> 分析HTML XHTML

urllib.parse --> URL

urllib.robotparser --> robots.txt

json --> JSON

xmlrpc.client, xmlrpc.server --> XML-RPC

ftplib --> FTP

nntplib --> NNTP

telnetlib --> TELNET

smtpd --> SMTP

smtplib --> SMTP

imaplib --> IMAP4

poplib --> POP3

mailbox --> Mailboxes

email

Django

Turbogears

Zope

5.2.11 XML

xml.dom --> DOM

xml.dom.minidom --> DOM

xml.sax --> SAX

xml.etree.ElementTree

猜你喜欢

转载自www.cnblogs.com/MTandHJ/p/10528176.html