目录

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

Python Revisited Day 05(模块)的更多相关文章

  1. Python(五)模块

    本章内容: 模块介绍 time & datetime random os sys json & picle hashlib XML requests ConfigParser logg ...

  2. python函数和常用模块(三),Day5

    递归 反射 os模块 sys模块 hashlib加密模块 正则表达式 反射 python中的反射功能是由以下四个内置函数提供:hasattr.getattr.setattr.delattr,改四个函数 ...

  3. Python自动化之常用模块

    1 time和datetime模块 #_*_coding:utf-8_*_ __author__ = 'Alex Li' import time # print(time.clock()) #返回处理 ...

  4. Python常用内建模块

    Python常用内建模块 datetime 处理日期和时间的标准库. 注意到datetime是模块,datetime模块还包含一个datetime类,通过from datetime import da ...

  5. Day5 - Python基础5 常用模块学习

    Python 之路 Day5 - 常用模块学习   本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shel ...

  6. Python一路走来 - 模块

    模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要多个函数才 ...

  7. Python多线程(threading模块)

    线程(thread)是操作系统能够进行运算调度的最小单位.它被包含在进程之中,是进程中的实际运作单位.一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务. ...

  8. python 学习day5(模块)

    一.模块介绍 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能 ...

  9. Python之旅Day6 模块应用

    time datetime random os sys shutil pickle json shelv xml configparser hashlib subprocess logging re ...

随机推荐

  1. 【Zabbix】CentOS6.9系统下部署Zabbix-agent

    目录 安装Zabbix-agent 1.安装YUM源 2.安装Zabbix agent端 3.配置zabbix_agentd.conf文件 4.启动zabbix agent服务 5.zabbix图形界 ...

  2. .net core使用ViewComponent将页面图片转码成base64

    using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; usi ...

  3. 大型网站架构演进(6)使用NoSQL和搜索引擎

    随着网站业务越来越复杂,对数据存储和检索的需求也越来越复杂,网站需要采用一些非关系型数据库技术(即NoSQL)和非数据库查询技术如搜索引擎.NoSQL数据库一般使用MongoDb,搜索引擎一般使用El ...

  4. 解决echarts饼图不显示数据为0的数据

    如图所示 饼图数据为0但是还是会显示lableline和lable 解决方法 var echartData = [{ value: data_arry[0]==0?null:data_arry[0], ...

  5. Archive & Backup 概念

    Archive & Backup 提起归档和备份两个词,给人感觉上是相同的概念,就是对指定文件的一个copy而已.archive和backup感觉是相似的,但是他们有着明显的不同de. arc ...

  6. ABP大型项目实战(1) - 目录

    前面我写了<如何用ABP框架快速完成项目>系列文章,讲述了如何用ABP快速完成项目.   然后我收到很多反馈,其中一个被经常问到的问题就是,“看了你的课程,发现ABP的优势是快速开发,那么 ...

  7. IDEA工具教程

    刚从myeclipse工具转成IntelliJ IDEA工具,在“传智播客*黑马程序员”学习了相关操作和配置,因此整理在该文章中.   文章大纲 教程文档下载地址 链接:https://pan.bai ...

  8. 【Linux】SSH证书免密码远程登陆Linux(Putty)

    1.前言 新购置一台便宜服务器做数据库服务器,减轻Web服务器的压力. 为了安全性,root密码设置的非常复杂(随机生成),厌倦了拷贝密码登陆的历史. Putty基本用法都不会的请先花10分钟自行学习 ...

  9. PJSUA2开发文档--第十二章 PJSUA2 API 参考手册

    12 PJSUA2 API 参考手册 12.1 endpoint.hpp PJSUA2基本代理操作.  namespace pj PJSUA2 API在pj命名空间内. 12.1.1 class En ...

  10. c/c++ 重载运算符 ==和!=的重载

    重载运算符 ==和!=的重载 问题:假如有一个类似于vector的类,这个类只能存放string,当有2个这个类的对象时,如何比较这2个对象. 自己重载==和!= 代码(重载==,!=) #inclu ...