模块,用一堆代码实现了某个功能的代码的集合。
类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。
如:os 是系统相关的模块;file是文件操作相关的模块
模块分为三种:
- 自定义模块
- 内置标准模块(又称标准库)
- 开源模块
自定义模块
1.定义模块
情境一:
在主目录下建立.py文件,根据实际需要能完成相应功能的文件
情景二:
在子目录下建立的.py文件
2.导入模块
Python之所以应用越来越广泛,在一定程度上也依赖于其为程序员提供了大量的模块以供使用,如果想要使用模块,则需要导入。导入模块有一下几种方法:
1 import module2 from module.xx.xx import xx3 from module.xx.xx import xx as rename 4 from module.xx.xx import *
导入模块其实就是告诉Python解释器去解释那个py文件
- 导入一个py文件,解释器解释该py文件
- 导入一个包,解释器解释该包下的 __init__.py 文件
那么问题来了,导入模块时是根据那个路径作为基准来进行的呢?即:sys.path
import sysprint sys.path 结果:['/Users/wupeiqi/PycharmProjects/calculator/p1/pp1', '/usr/local/lib/python2.7/site-packages/setuptools-15.2-py2.7.egg', '/usr/local/lib/python2.7/site-packages/distribute-0.6.28-py2.7.egg', '/usr/local/lib/python2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.10-x86_64.egg', '/usr/local/lib/python2.7/site-packages/xlutils-1.7.1-py2.7.egg', '/usr/local/lib/python2.7/site-packages/xlwt-1.0.0-py2.7.egg', '/usr/local/lib/python2.7/site-packages/xlrd-0.9.3-py2.7.egg', '/usr/local/lib/python2.7/site-packages/tornado-4.1-py2.7-macosx-10.10-x86_64.egg', '/usr/local/lib/python2.7/site-packages/backports.ssl_match_hostname-3.4.0.2-py2.7.egg', '/usr/local/lib/python2.7/site-packages/certifi-2015.4.28-py2.7.egg', '/usr/local/lib/python2.7/site-packages/pyOpenSSL-0.15.1-py2.7.egg', '/usr/local/lib/python2.7/site-packages/six-1.9.0-py2.7.egg', '/usr/local/lib/python2.7/site-packages/cryptography-0.9.1-py2.7-macosx-10.10-x86_64.egg', '/usr/local/lib/python2.7/site-packages/cffi-1.1.1-py2.7-macosx-10.10-x86_64.egg', '/usr/local/lib/python2.7/site-packages/ipaddress-1.0.7-py2.7.egg', '/usr/local/lib/python2.7/site-packages/enum34-1.0.4-py2.7.egg', '/usr/local/lib/python2.7/site-packages/pyasn1-0.1.7-py2.7.egg', '/usr/local/lib/python2.7/site-packages/idna-2.0-py2.7.egg', '/usr/local/lib/python2.7/site-packages/pycparser-2.13-py2.7.egg', '/usr/local/lib/python2.7/site-packages/Django-1.7.8-py2.7.egg', '/usr/local/lib/python2.7/site-packages/paramiko-1.10.1-py2.7.egg', '/usr/local/lib/python2.7/site-packages/gevent-1.0.2-py2.7-macosx-10.10-x86_64.egg', '/usr/local/lib/python2.7/site-packages/greenlet-0.4.7-py2.7-macosx-10.10-x86_64.egg', '/Users/wupeiqi/PycharmProjects/calculator', '/usr/local/Cellar/python/2.7.9/ works/Python. work/Versions/2.7/lib/python27.zip', '/usr/local/Cellar/python/2.7.9/ works/Python. work/Versions/2.7/lib/python2.7', '/usr/local/Cellar/python/2.7.9/ works/Python. work/Versions/2.7/lib/python2.7/plat-darwin', '/usr/local/Cellar/python/2.7.9/ works/Python. work/Versions/2.7/lib/python2.7/plat-mac', '/usr/local/Cellar/python/2.7.9/ works/Python. work/Versions/2.7/lib/python2.7/plat-mac/lib- packages', '/usr/local/Cellar/python/2.7.9/ works/Python. work/Versions/2.7/lib/python2.7/lib-tk', '/usr/local/Cellar/python/2.7.9/ works/Python. work/Versions/2.7/lib/python2.7/lib-old', '/usr/local/Cellar/python/2.7.9/ works/Python. work/Versions/2.7/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/site-packages', '/Library/Python/2.7/site-packages']
如果sys.path路径列表没有你想要的路径,可以通过 sys.path.append('路径') 添加。
通过os模块可以获取各种目录,例如:

import sysimport ospre_path = os.path.abspath('../')sys.path.append(pre_path)
开源模块
一、下载安装

yum pipapt-get...

下载源码解压源码进入目录编译源码 python setup.py build安装源码 python setup.py install注:在使用源码安装时,需要使用到gcc编译和python开发环境,所以,需要先执行:

yum install gccyum install python-devel或apt-get python-dev
安装成功后,模块会自动安装到 sys.path 中的某个目录中,如:
/usr/lib/python2.7/site-packages/
二、导入模块
同自定义模块中导入的方式
还有一个模块 paramiko,paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的paramiko来现实。(不是很了解)
内置模块
一、os
用于提供系统级别的操作
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cdos.curdir 返回当前目录: ('.')os.pardir 获取当前目录的父目录字符串名:('..')os.makedirs('dirname1/dirname2') 可生成多层递归目录os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirnameos.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirnameos.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印os.remove() 删除一个文件os.rename("oldname","newname") 重命名文件/目录os.stat('path/filename') 获取文件/目录信息os.sep 输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"os.linesep 输出当前平台使用的行终止符,win下为" ",Linux下为" "os.pathsep 输出用于分割文件路径的字符串os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'os.system("bash command") 运行shell命令,直接显示os.environ 获取系统环境变量os.path.abspath(path) 返回path规范化的绝对路径os.path.split(path) 将path分割成目录和文件名二元组返回os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素os.path. name(path) 返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素os.path.exists(path) 如果path存在,返回True;如果path不存在,返回Falseos.path.isabs(path) 如果path是绝对路径,返回Trueos.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回Falseos.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回Falseos.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
二、sys
用于提供对解释器相关的操作
sys.argv 命令行参数List,第一个元素是程序本身路径sys.exit(n) 退出程序,正常退出时exit(0)sys.version 获取Python解释程序的版本信息sys.maxint 最大的Int值sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值sys.platform 返回操作系统平台名称sys.stdout.write('please:')val = sys.stdin.readline()[:-1]
三、hashlib
用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
import hashlib # ######## md5 ######## hash = hashlib.md5()hash.update('admin')print hash.hexdigest() # ######## sha1 ######## hash = hashlib.sha1()hash.update('admin')print hash.hexdigest() # ######## sha256 ######## hash = hashlib.sha256()hash.update('admin')print hash.hexdigest() # ######## sha384 ######## hash = hashlib.sha384()hash.update('admin')print hash.hexdigest() # ######## sha512 ######## hash = hashlib.sha512()hash.update('admin')print hash.hexdigest()
以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。
import hashlib # ######## md5 ######## hash = hashlib.md5('898oaFs09f')hash.update('admin')print hash.hexdigest()
更高及的另一种加密方式,python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密.
import hmach = hmac.new('wueiqi')h.update('hellowo')print h.hexdigest()
四、json 和 pickle
可以参考上一篇中的内容https://www.cnblogs.com/Young111/p/9298627.html
五、shutil
高级的 文件、文件夹、压缩包 处理模块
shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另一个文件中,可以部分内容.

def copyfileobj(fsrc, fdst, length=16*1024): """copy data from file-like fsrc to file-like fdst""" while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf)
shutil.copyfile(src, dst)
拷贝文件

def copyfile(src, dst): """Copy data from src to dst""" if _samefile(src, dst): raise Error("`%s` and `%s` are the same file" % (src, dst)) for fn in [src, dst]: try: st = os.stat(fn) except OSError: # File most likely does not exist pass else: # XXX What about other special files? (sockets, devices...) if stat.S_ISFIFO(st.st_mode): raise SpecialFileError("`%s` is a named pipe" % fn) with open(src, 'rb') as fsrc: with open(dst, 'wb') as fdst: copyfileobj(fsrc, fdst)
shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变

def copymode(src, dst): """Copy mode bits from src to dst""" if hasattr(os, 'chmod'): st = os.stat(src) mode = stat.S_IMODE(st.st_mode) os.chmod(dst, mode)
shutil.copystat(src, dst)
拷贝状态的信息,包括:mode bits, atime, mtime, flags

def copystat(src, dst): """Copy all stat info (mode bits, atime, mtime, flags) from src to dst""" st = os.stat(src) mode = stat.S_IMODE(st.st_mode) if hasattr(os, 'utime'): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, 'chmod'): os.chmod(dst, mode) if hasattr(os, 'chflags') and hasattr(st, 'st_flags'): try: os.chflags(dst, st.st_flags) except OSError, why: for err in 'EOPNOTSUPP', 'ENOTSUP': if hasattr(errno, err) and why.errno == getattr(errno, err): break else: raise
shutil.copy(src, dst)
拷贝文件和权限

def copy(src, dst): """Copy data and mode bits ("cp src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path. name(src)) copyfile(src, dst) copymode(src, dst)
shutil.copy2(src, dst)
拷贝文件和状态信息

def copy2(src, dst): """Copy data and all stat info ("cp -p src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path. name(src)) copyfile(src, dst) copystat(src, dst)
shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, sym s=False, ignore=None)
递归的去拷贝文件
例如:copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*')
shutil.rmtree(path[, ignore_errors[, ]])
递归的去删除文件
shutil.make_archive( _name, format,...)
创建压缩包并返回文件路径,例如:zip、tar
- _name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
如:www =>保存至当前路径
如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/ - format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
- root_dir: 要压缩的文件夹路径(默认当前目录)
- owner: 用户,默认当前用户
- group: 组,默认当前组
- logger: 用于记录日志,通常是logging.Logger对象
View Code#将 /Users/young/Downloads/test 下的文件打包放置当前程序目录 import shutilret = shutil.make_archive("dddddd", 'gztar', root_dir='/Users/young/Downloads/test') #将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录import shutilret = shutil.make_archive("/Users/young/dddddd", 'gztar', root_dir='/Users/young/Downloads/test')
shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:

import zipfile# 压缩z = zipfile.ZipFile('laxi.zip', 'w')z.write('a.log')z.write('data.data')z.close()# 解压z = zipfile.ZipFile('laxi.zip', 'r')z.extractall()z.close()

import tarfile# 压缩tar = tarfile.open('your.tar','w')tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip')tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip')tar.close()# 解压tar = tarfile.open('your.tar','r')tar.extractall() # 可设置解压地址tar.close()
六、shelve
shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式

import shelve d = shelve.open('shelve_test') #打开一个文件 class Test( ): def __init__(self,n): self.n = n t = Test(123) t2 = Test(123334) name = ["young","Jon","test"]d["test"] = name #持久化列表d["t1"] = t #持久化类d["t2"] = t2 d.close()
七、
是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用 呀,至今很多传统公司如金融行业的很多系统的接口还主要是 。
的格式如下,就是通过<>节点来区别数据结构的:

<? version="1.0"?><data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country></data>
协议在各个语言里的都 是支持的,在python中可以用以下模块操作

import .etree.ElementTree as ET tree = ET.parse(" test. ")root = tree.getroot()print(root.tag) #遍历 文档for child in root: print(child.tag, child.attrib) for i in child: print(i.tag,i.text) #只遍历year 节点for node in root.iter('year'): print(node.tag,node.text)
修改和删除 文件

import .etree.ElementTree as ET tree = ET.parse(" test. ")root = tree.getroot() #修改for node in root.iter('year'): new_year = int(node.text) + 1 node.text = str(new_year) node.set("updated","yes") tree.write(" test. ") #删除nodefor country in root.findall('country'): rank = int(country.find('rank').text) if rank > 50: root.remove(country) tree.write('output. ')
自己创建 文档

import .etree.ElementTree as ET new_ = ET.Element("namelist")name = ET.SubElement(new_ ,"name",attrib={"enrolled":"yes"})age = ET.SubElement(name,"age",attrib={"checked":"no"})sex = ET.SubElement(name,"sex")sex.text = '33'name2 = ET.SubElement(new_ ,"name",attrib={"enrolled":"no"})age = ET.SubElement(name2,"age")age.text = '19' et = ET.ElementTree(new_ ) #生成文档对象et.write("test. ", encoding="utf-8", _declaration=True) ET.dump(new_ ) #打印生成的格式
八、PyYAML
参考文档:http://pyyaml.org/wiki/PyYAMLDocumentation
九、ConfigParser
用于对特定的配置进行操作,当前模块的名称在 python 3.x 版本中变更为 configparser。

# 注释1; 注释2 [section1]k1 = v1k2:v2 [section2]k1 = v1import ConfigParser config = ConfigParser.ConfigParser()config.read('i.cfg') # ########## 读 ###########secs = config.sections()#print secs#options = config.options('group2')#print options #item_list = config.items('group2')#print item_list #val = config.get('group1','key')#val = config.getint('group1','key') # ########## 改写 ###########sec = config.remove_section('group1')#config.write(open('i.cfg', "w")) #sec = config.has_section('wupeiqi')#sec = config.add_section('wupeiqi')#config.write(open('i.cfg', "w")) #config.set('group2','k1',11111)#config.write(open('i.cfg', "w")) #config.remove_option('group2','age')#config.write(open('i.cfg', "w"))
十、logging
用于便捷记录日志且线程安全的模块,logging的日志可以分为 debug(), info(), warning(), error() and critical() 5个级别,下面我们看一下怎么用。
import logging logging.basicConfig(filename='log.log', format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S %p', level=10) logging.debug('debug')logging.info('info')logging.warning('warning')logging.error('error')logging.critical('critical')logging.log(10,'log')
相应等级:
1 CRITICAL = 502 FATAL = CRITICAL3 ERROR = 404 WARNING = 305 WARN = WARNING6 INFO = 207 DEBUG = 10
日志格式:
%(name)s | Logger的名字 |
%(levelno)s | 数字形式的日志级别 |
%(levelname)s | 文本形式的日志级别 |
%(pathname)s | 调用日志输出函数的模块的完整路径名,可能没有 |
%(filename)s | 调用日志输出函数的模块的文件名 |
%(module)s | 调用日志输出函数的模块名 |
%(funcName)s | 调用日志输出函数的函数名 |
%(lineno)d | 调用日志输出函数的语句所在的代码行 |
%(created)f | 当前时间,用UNIX标准的表示时间的浮 点数表示 |
%(relativeCreated)d | 输出日志信息时的,自Logger创建以 来的毫秒数 |
%(asctime)s | 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 |
%(thread)d | 线程ID。可能没有 |
%(threadName)s | 线程名。可能没有 |
%(process)d | 进程ID。可能没有 |
%(message)s | 用户输出的消息
|
如果想同时把log打印在屏幕和文件日志里,就需要了解一点复杂的知识 了
Python 使用logging模块记录日志涉及四个主要类,使用官方文档中的概括最为合适:
logger提供了应用程序可以直接使用的接口;
handler将(logger创建的)日志记录发送到合适的目的输出;
filter提供了细度设备来决定输出哪条日志记录;
formatter决定日志记录的最终输出格式。
logger
每个程序在输出信息之前都要获得一个Logger。Logger通常对应了程序的模块名,比如聊天工具的图形界面模块可以这样获得它的Logger:
LOG=logging.getLogger(”chat.gui”)
而核心模块可以这样:
LOG=logging.getLogger(”chat.kernel”)
Logger.setLevel(lel):指定最低的日志级别,低于lel的级别将被忽略。debug是最低的内置级别,critical为最高
Logger.addFilter(filt)、Logger.removeFilter(filt):添加或删除指定的filter
Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或删除指定的handler
Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():可以设置的日志级别
handler
handler对象负责发送相关的信息到指定目的地。Python的日志系统有多种Handler可以使用。有些Handler可以把信息输出到控制台,有些Logger可以把信息输出到文件,还有些 Handler可以把信息发送到网络上。如果觉得不够用,还可以编写自己的Handler。可以通过addHandler()方法添加多个多handler
Handler.setLevel(lel):指定被处理的信息级别,低于lel级别的信息将被忽略
Handler.setFormatter():给这个handler选择一个格式
Handler.addFilter(filt)、Handler.removeFilter(filt):新增或删除一个filter对象
每个Logger可以附加多个Handler。接下来我们就来介绍一些常用的Handler:
1) logging.StreamHandler
使用这个Handler可以向类似与sys.stdout或者sys.stderr的任何文件对象(file )输出信息。它的构造函数是:
StreamHandler([strm])
其中strm参数是一个文件对象。默认是sys.stderr
2) logging.FileHandler
和StreamHandler类似,用于向一个文件输出日志信息。不过FileHandler会帮你打开这个文件。它的构造函数是:
FileHandler(filename[,mode])
filename是文件名,必须指定一个文件名。
mode是文件的打开方式。参见Python内置函数open()的用法。默认是’a',即添加到文件末尾。
3) logging.handlers.RotatingFileHandler
这个Handler类似于上面的FileHandler,但是它可以管理文件大小。当文件达到一定大小之后,它会自动将当前日志文件改名,然后创建 一个新的同名日志文件继续输出。比如日志文件是chat.log。当chat.log达到指定的大小之后,RotatingFileHandler自动把 文件改名为chat.log.1。不过,如果chat.log.1已经存在,会先把chat.log.1重命名为chat.log.2。。。最后重新创建 chat.log,继续输出日志信息。它的构造函数是:
RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
其中filename和mode两个参数和FileHandler一样。
maxBytes用于指定日志文件的最大文件大小。如果maxBytes为0,意味着日志文件可以无限大,这时上面描述的重命名过程就不会发生。
backupCount用于指定保留的备份文件的个数。比如,如果指定为2,当上面描述的重命名过程发生时,原有的chat.log.2并不会被更名,而是被删除。
4) logging.handlers.TimedRotatingFileHandler
这个Handler和RotatingFileHandler类似,不过,它没有通过判断文件大小来决定何时重新创建日志文件,而是间隔一定时间就 自动创建新的日志文件。重命名的过程与RotatingFileHandler类似,不过新的文件不是附加数字,而是当前时间。它的构造函数是:
TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
其中filename参数和backupCount参数和RotatingFileHandler具有相同的意义。
interval是时间间隔。
when参数是一个字符串。表示时间间隔的单位,不区分大小写。它有以下取值:
S 秒
M 分
H 小时
D 天
W 每星期(interval==0时代表星期一)
midnight 每天凌晨

1 import logging 2 3 #create logger 4 logger = logging.getLogger('TEST-LOG') 5 logger.setLevel(logging.DEBUG) 6 7 8 # create console handler and set level to debug 9 ch = logging.StreamHandler()10 ch.setLevel(logging.DEBUG)11 12 # create file handler and set level to warning13 fh = logging.FileHandler("access.log")14 fh.setLevel(logging.WARNING)15 # create formatter16 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')17 18 # add formatter to ch and fh19 ch.setFormatter(formatter)20 fh.setFormatter(formatter)21 22 # add ch and fh to logger23 logger.addHandler(ch)24 logger.addHandler(fh)25 26 # 'application' code27 logger.debug('debug message')28 logger.info('info message')29 logger.warn('warn message')30 logger.error('error message')31 logger.critical('critical message')
文件自动截断例子:

import loggingfrom logging import handlerslogger = logging.getLogger(__name__)log_file = "timelog.log"#fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=3)fh = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3)formatter = logging.Formatter('%(asctime)s %(module)s:%(lineno)d %(message)s')fh.setFormatter(formatter)logger.addHandler(fh)logger.warning("test1")logger.warning("test12")logger.warning("test13")logger.warning("test14")
十一、re
常用的正则表达式
1 '.' 默认匹配除 之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行 2 '^' 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a"," abc eee",flags=re.MULTILINE) 3 '$' 匹配字符结尾,或e.search("foo$","bfoo sdfsf",flags=re.MULTILINE).group()也可以 4 '*' 匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac") 结果为['abb', 'ab', 'a'] 5 '+' 匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab', 'abb'] 6 '?' 匹配前一个字符1次或0次 7 '{m}' 匹配前一个字符m次 8 '{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb', 'ab', 'abb'] 9 '|' 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC'10 '(...)' 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abcabca456c11 12 13 'A' 只从字符开头匹配,re.search("Aabc","alexabc") 是匹配不到的14 '' 匹配字符结尾,同$15 'd' 匹配数字0-916 'D' 匹配非数字17 'w' 匹配[A-Za-z0-9]18 'W' 匹配非[A-Za-z0-9]19 's' 匹配空白字符、 、 、 , re.search("s+","ab c1 3").group() 结果 ' '20 21 '(?P<name>...)' 分组匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 结果{'province': '3714', 'city': '81', 'birthday': '1993'}
最常用的匹配语法
re.match 从头开始匹配re.search 匹配包含re.findall 把所有匹配到的字符放到以列表中的元素返回re.splitall 以匹配到的字符当做列表分隔符re.sub 匹配字符并替换仅需轻轻知道的几个匹配模式
re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同)M(MULTILINE): 多行模式,改变'^'和'$'的行为(参见上图)S(DOTALL): 点任意匹配模式,改变'.'的行为
十二、time
时间相关的操作,时间有三种表示方式:
- 时间戳 1970年1月1日之后的秒,即:time.time()
- 格式化的字符串 2014-11-11 11:11, 即:time.strftime('%Y-%m-%d')
- 结构化时间 元组包含了:年、日、星期等... time.struct_time 即:time.localtime()

1 print time.time() 2 print time.mktime(time.localtime()) 3 4 print time.gmtime() #可加时间戳参数 5 print time.localtime() #可加时间戳参数 6 print time.strptime('2014-11-11', '%Y-%m-%d') 7 8 print time.strftime('%Y-%m-%d') #默认当前时间 9 print time.strftime('%Y-%m-%d',time.localtime()) #默认当前时间10 print time.asctime()11 print time.asctime(time.localtime())12 print time.ctime(time.time())13 14 import datetime15 '''16 datetime.date:表示日期的类。常用的属性有year, month, day17 datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond18 datetime.datetime:表示日期时间19 datetime.timedelta:表示时间间隔,即两个时间点之间的长度20 timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])21 strftime("%Y-%m-%d")22 '''23 import datetime24 print datetime.datetime.now()25 print datetime.datetime.now() - datetime.timedelta(days=5)
十三、random
随机数
mport randomprint random.random()print random.randint(1,2)print random.randrange(1,10)
随机验证码例子:
import randomcheckcode = ''for i in range(4): current = random.randrange(0,4) if current != i: temp = chr(random.randint(65,90)) else: temp = random.randint(0,9) checkcode += str(temp)print checkcode
继续阅读与本文标签相同的文章
python基础day4
python之面向对象编程一
-
请问如何在出错后能恢复到改变设置前的状态?
2026-05-25栏目: 教程
-
在DotNetNuke中通过修改ascx文件源码自定义界面
2026-05-25栏目: 教程
-
”A page can have only one server-side Form tag“错误
2026-05-25栏目: 教程
-
DotNetNuke(DNN)网站发布、部署、迁移和重建
2026-05-25栏目: 教程
-
10 Productivity Tips
2026-05-25栏目: 教程

