模块

模块

何为模块?在python中一个.py文件就是一个模块

模块的好处

1、代码重用

2、系统命名空间的划分

3、实现共享服务和数据

pythond的代码目录就称为包

__init__.py文件的作用是声明和初始化模块包,没有这个文件不能导入模块

导入包

复制代码
glance/                   #Top-level package

├── __init__.py      #Initialize the glance package

├── api                  #Subpackage for api

│   ├── __init__.py

│   ├── policy.py

│   └── versions.py

├── cmd                #Subpackage for cmd

│   ├── __init__.py

│   └── manage.py

└── db                  #Subpackage for db

    ├── __init__.py

    └── models.py

1、import

必须在glance同级目录下导入

import glance.db.models
glance.db.models.register_models('mysql')

2、from ... import

需要注意的是from后import导入的模块,必须是明确的一个不能带点,否则会有语法错误,如:from a import b.c是错误语法

from glance.cmd import manage

常用模块

  • random模块
  • shutil模块
  • pickle&json&shelve模块
  • time
  • datetime
  • os
  • subprocess

random模块

>>> random.randint(1,3)
3
>>> random.randrange(1,3)
2
>>> random.choice("aasdfdfew%^&")
'd'
>>> random.sample("asddasf",3)
['d', 'f', 'd']
>>> ''.join(random.sample(string.ascii_lowercase + string.digits, 6))
'q9xlsh'
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.shuffle(a)
>>> a
[4, 5, 7, 2, 3, 0, 9, 8, 1, 6]

random模块实现6位随机验证码,验证码至少包含一个数字,一个小写字母,一个大写字母

import string
import random
res1 = random.sample(string.digits, 2)
res2 = random.sample(string.ascii_lowercase, 2)
res3 = random.sample(string.ascii_uppercase, 2)
# print(res1, res2, res3)
res_num = res1 + res2 + res3
print(res_num)
# print(random.shuffle(res_num))  # None random.shuffle固定返回None
random.shuffle(res_num)
print(''.join(res_num))

shutil模块

import shutil
shutil.copyfileobj(open("old.xml", "r"), open("new.xml", "w"))  # 将文件内容copy到另一个文件

shutil.copyfile(src, dst)
拷贝文件

shutil.copyfile('f1.log', 'f2.log') #目标文件无需存在

shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变

shutil.copymode('f1.log', 'f2.log') #目标文件必须存在

shutil.copystat(src, dst)
仅拷贝状态的信息,包括:mode bits, atime, mtime, flags

shutil.copystat('f1.log', 'f2.log') #目标文件必须存在

shutil.copy(src, dst)
拷贝文件和状态信息

import shutil
shutil.copy2('f1.log', 'f2.log')

shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件夹

import shutil
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除

shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件

import shutil
shutil.rmtree('folder1')

shutil.move(src, dst)
递归的去移动文件,它类似mv命令,其实就是重命名。

import shutil
shutil.move('folder1', 'folder3')

shutil.make_archive(base_name, format,...)

创建压缩包并返回文件路径,例如:zip、tar
创建压缩包并返回文件路径,例如:zip、tar
base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,

ormat: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
root_dir: 要压缩的文件夹路径(默认当前目录)
owner: 用户,默认当前用户
group: 组,默认当前组
logger: 用于记录日志,通常是logging.Logger对象

例子

#将 /data 下的文件打包放置当前程序目录
import shutil
ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data')

#将 /data下的文件打包放置 /tmp/目录
import shutil
ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')

pickle & json

json,用于字符串 和 python数据类型间进行转换

pickle,用于python特有的类型 和 python的数据类型间进行转换

Json模块提供了四个功能:dumps、dump、loads、load

pickle模块提供了四个功能:dumps、dump、loads、load

序列化

def sayhi(name):
    print('hello',name)
info={
    'name':'alex',
    'age':22,
    'func':sayhi,
    }
f=open("test.text",'wb')
# f.write(pickle.dumps(info))
pickle.dump(info,f)
f.close()

反序列化

import pickle
def sayhi(name):
    print('hello2',name)

f=open("test.text","rb")

# data=pickle.loads(f.read())
data = pickle.load(f)
print(data["func"]("alex"))
f.close()

pickle和json对比

JSON:

优点:跨语言、体积小

缺点:只能支持intstrlist	upledict

Pickle:

优点:专为python设计,支持python所有的数据类型

缺点:只能在python中使用,存储数据占空间大

shelve模块

shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式

序列化:

import shelve

f = shelve.open('shelve_test')  # 打开一个文件



names = ["alex", "rain", "test"]
info = {'name':'alex','age':22}


f["names"] = names  # 持久化列表
f['info_dic'] = info

f.close()

反序列化:

mport shelve

d = shelve.open('shelve_test')  # 打开一个文件

print(d['names'])
print(d['info_dic'])


#del d['test'] #还可以删除

time

time.localtime([secs]):将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。

time.gmtime([secs]):和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time

time.time(): 返回当前时间的时间戳。

time.mktime(t): 将一个struct_time转化为时间戳

time.sleep(secs):线程推迟指定的时间运行。单位为秒。

time.asctime([t]):把一个表示时间的元组或者struct_time表示为这种形式:'Sun Oct 1 12:04:38 2017'。如果没有参数,将会将time.localtime()作为参数传入。

time.ctime([secs]):把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。如果参数未给或者为None的时候,将会默认time.time()为参数。它的作用相当于time.asctime(time.localtime(secs))。

time.strftime(format[, t]):
把一个代表时间的元组或者struct_time(如由time.localtime()和time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。

举例:time.strftime("%Y-%m-%d %X", time.localtime()) #输出'2017-10-01 12:14:23'

datetime

datetime.date:表示日期的类。常用的属性有year, month, day;
datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond;
datetime.datetime:表示日期时间。
datetime.timedelta:表示时间间隔,即两个时间点之间的长度。
datetime.tzinfo:与时区有关的相关信息。(这里不详细充分讨论该类,感兴趣的童鞋可以参考python手册)

常用方法

1、d=datetime.datetime.now() 返回当前的datetime日期类型

d.timestamp(),d.today(), d.year,d.timetuple()等方法可以调用

2.datetime.date.fromtimestamp(322222) 把一个时间戳转为datetime日期类型

3、时间运算

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2018, 1, 12, 20, 29, 40, 979928)
datetime.datetime(2018, 1, 16, 20, 31, 44, 389966)
>>> datetime.datetime.now() + datetime.timedetla(hours=4)
>>> datetime.datetime.now() + datetime.timedelta(hours=4)
datetime.datetime(2018, 1, 13, 0, 33, 16, 373267)

4、时间替换

>>> d = datetime.datetime.now()
>>> d
datetime.datetime(2018, 1, 12, 20, 37, 12, 802933)
>>> d.replace(year=2999,month=11,day=24)
datetime.datetime(2999, 11, 24, 20, 37, 12, 802933)

5、实现过期验证

user_data = {"expire_date": "2021-01-01", "id": 1234}
time_str = user_data["expire_date"]
print(time_str)
string_2_struct = time.strptime(time_str, "%Y-%m-%d")  # 字符串转时间戳对象
print(string_2_struct)
time_stamp = int(time.mktime(string_2_struct))  # 时间戳对象转时间戳数字
print(time_stamp)
res = time.time() - time_stamp
if res > 0:
    print("过期了")
else:
    print("没过期")

os模块

得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd()
返回指定目录下的所有文件和目录名:os.listdir()
函数用来删除一个文件:os.remove()
删除多个目录:os.removedirs(r“c:python”)
检验给出的路径是否是一个文件:os.path.isfile()
检验给出的路径是否是一个目录:os.path.isdir()
判断是否是绝对路径:os.path.isabs()
检验给出的路径是否真地存:os.path.exists()
返回一个路径的目录名和文件名:os.path.split()     e.g os.path.split('/home/swaroop/byte/code/poem.txt') 结果:('/home/swaroop/byte/code', 'poem.txt') 
分离扩展名:os.path.splitext()       e.g  os.path.splitext('/usr/local/test.py')    结果:('/usr/local/test', '.py')
获取路径名:os.path.dirname()
获得绝对路径: os.path.abspath()  
获取文件名:os.path.basename()
运行shell命令: os.system()
读取操作系统环境变量HOME的值:os.getenv("HOME") 
返回操作系统所有的环境变量: os.environ 
设置系统环境变量,仅程序运行时有效:os.environ.setdefault('HOME','/home/alex')
给出当前平台使用的行终止符:os.linesep    Windows使用'
',Linux and MAC使用'
'
指示你正在使用的平台:os.name       对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'
重命名:os.rename(old, new)
创建多级目录:os.makedirs(r“c:python	est”)
创建单个目录:os.mkdir(“test”)
获取文件属性:os.stat(file)
修改文件权限与时间戳:os.chmod(file)
获取文件大小:os.path.getsize(filename)
结合目录名与文件名:os.path.join(dir,filename)
改变工作目录到dirname: os.chdir(dirname)
获取当前终端的大小: os.get_terminal_size()
杀死进程: os.kill(10884,signal.SIGKILL)

sunprocess

run()

subprocess.run(['df','-h'],stderr=subprocess.PIPE,stdout=subprocess.PIPE,check=True)

涉及管道命令

subprocess.run('df -h|grep disk1',shell=True) #shell=True的意思是这条命令直接交给系统去执行,不需要python负责解析

call()

#执行命令,返回命令执行状态 , 0 or 非0
>>> retcode = subprocess.call(["ls", "-l"])

#执行命令,如果命令结果为0,就正常返回,否则抛异常
>>> subprocess.check_call(["ls", "-l"])
0

#接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果 
>>> subprocess.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')

#接收字符串格式命令,并返回结果
>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls'

#执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res
>>> res=subprocess.check_output(['ls','-l'])
>>> res
b'total 0
drwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM
'

Popen()

a=subprocess.run('sleep 10',shell=True,stdout=subprocess.PIPE)  # 等待命令结果
a=subprocess.Popen('sleep 10',shell=True,stdout=subprocess.PIPE)  # 不等待命令结果,并行

https://www.luffycity.com/python-book/di-4-zhang-python-ji-chu-2014-chang-yong-mo-kuai/subprocess-mo-kuai.html

sys模块

sys.argv           命令行参数List,第一个元素是程序本身路径
sys.exit(n)        退出程序,正常退出时exit(0)
sys.version        获取Python解释程序的版本信息
sys.maxint         最大的Int值
sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform       返回操作系统平台名称
sys.stdout.write('please:')  #标准输出 , 引出进度条的例子, 注,在py3上不行,可以用print代替
val = sys.stdin.readline()[:-1] #标准输入
sys.getrecursionlimit() #获取最大递归层数
sys.setrecursionlimit(1200) #设置最大递归层数
sys.getdefaultencoding()  #获取解释器默认编码
sys.getfilesystemencoding  #获取内存数据存到文件里的默认编码

xml处理模块

xml文档

<?xml 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操作xml

import xml.etree.ElementTree as ET

tree = ET.parse("XML_T.xml")
root = tree.getroot()
print('-->%s'%root.tag)

# 遍历xml文档
for child in root:
    print(child.tag, child.attrib)
    for i in child:
        if i.tag=='neighbor':
            print(i.tag,i.attrib)
        else:
            print(i.tag, i.text)
# 只遍历year 节点
for node in root.iter('year'):
    print(node.tag, node.text)

修改和删除xml

import xml.etree.ElementTree as ET
 
tree = ET.parse("XML_T.xml")
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("xmltest.xml")
 
 
#删除node
for country in root.findall('country'):
   rank = int(country.find('rank').text)
   if rank > 50:
     root.remove(country)
 
tree.write('output.xml')

自己创建xml文档

import xml.etree.ElementTree as ET

new_xml = ET.Element("personinfolist")
personinfo = ET.SubElement(new_xml, "personinfo", attrib={"enrolled": "yes"})
name = ET.SubElement(personinfo, "name")
name.text='alex'
age = ET.SubElement(personinfo, "age", attrib={"checked": "33"})
sex = ET.SubElement(personinfo, "sex")
sex.text = 'MAN'
personinfo2 = ET.SubElement(new_xml, "personinfo2", attrib={"enrolled": "no"})
name = ET.SubElement(personinfo, "name")
name.text='oldboy'
age = ET.SubElement(personinfo, "age")
age.text = '19'

et = ET.ElementTree(new_xml)  # 生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True)

ET.dump(new_xml)  # 打印生成的格式

hashlib模块

用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __author__:JasonLIN
import hashlib


m = hashlib.md5()
m.update(b"Hello")  # 必须为bytes类型
print(m.digest())

print(m.digest())  # 2进制格式hash
print(m.hexdigest())  # 16进制格式hash

# ######## md5 ########

hash = hashlib.md5()
hash.update(b'admin')
print(hash.hexdigest())

# ######## sha1 ########

hash = hashlib.sha1()
hash.update(b'admin')
print(hash.hexdigest())

# ######## sha256 ########

hash = hashlib.sha256()
hash.update(b'admin')
print(hash.hexdigest())

# ######## sha384 ########

hash = hashlib.sha384()
hash.update(b'admin')
print(hash.hexdigest())

# ######## sha512 ########

hash = hashlib.sha512()
hash.update(b'admin')
print(hash.hexdigest())

hashmac模块

import hmac
h=hmac.new('天王盖地虎'.encode(encoding='utf-8'),'你是250'.encode(encoding='utf-8'))
print(h.hexdigest())

configerpraser模块

https://i.cnblogs.com/EditPosts.aspx?postid=7636272

原文地址:https://www.cnblogs.com/Jason-lin/p/8362238.html