序列化:序列化指把内存里的数据类型转成字符串,以使其能存储到硬盘或通过网络传输到远程,因为硬盘或网络传输时只能接受bytes
为什么要序列化:可以直接把内存数据(eg:10个列表,3个嵌套字典)存到硬盘上,下次程序再启动,再从硬盘上读回来,还是原来的格式。

用于序列化的两个模块:
json: 字符串 和python数据类型间进行转换 (dumps/dump/loads/load)
pickle: python特有的类型 和python的数据类型进行转换 (dumps/dump/loads/load)

----------------------------------------------------

json 模块

data={字典}
s = json.dumps(data) #把数据类型转成字符串
data = json.loads(s) #把字符串转成数据类型 json.dump(data,open('test.json','w',encoding='utf-8')) #把数据类型转成->字符串->存到文件里
data = json.load(open('test.json','r',encoding='utf-8')) #打开文件从->字符串->转成数据类型 dumps loads 存在的意义:1.远程传给其他人 2.不同语言之间的交互

pickle 模块

data={字典} sayhi=(函数)
s = pickle.dumps(data)
data = pickle.loads(s)
pickle.dump(data,open('test.json','wb'))
data = pickle.load(open('test.json','rb')) s = pickle.dumps(sayhi)
data = pickle.loads(s)
pickle.dump(sayhi,open('test1.json','wb'))
pickle.load(open('test1.json','rb'))()

json和pickle区别:

json    可转化的数据类型有 int str list tuple dict 不支持set
pickle python独有的,支持python的所有数据类型,支持函数

shelve 模块

pickle封装了shelve模块,只能在python中使用,支持python的所有数据类型
    #可增加 删除 可整体重新赋值

names = ["alex", "rain", "test"]
info = {'name':'alex','age':22}
f = shelve.open('shelve_test')
f["names"] = names #持久化列表
f['info_dic'] = info
f.close() d = shelve.open('shelve_test')
print(d['names'])
del d['test']

xml 模块

作用:
1.不同语言之间内存数据得交换
2.内存的数据可转换成xml存到硬盘上

1.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> 2.xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml   
import xml.etree.ElementTree as ET tree = ET.parse("xmltest.xml")
root = tree.getroot()
print(root.tag) #遍历xml文档
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) 3.修改和删除xml文档内容
import xml.etree.ElementTree as ET tree = ET.parse("xmltest.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') 4.自己创建xml文档
import xml.etree.ElementTree as ET new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
age = ET.SubElement(name,"age",attrib={"checked":"no"})
sex = ET.SubElement(name,"sex")
sex.text = ''
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
age.text = '' et = ET.ElementTree(new_xml) #生成文档对象
et.write("test.xml", encoding="utf-8",xml_declaration=True) ET.dump(new_xml) #打印生成的格式

configparser 模块

作用:用于生成和修改常见配置文档

1.来看一个好多软件的常见配置文件格式如下
***.ini [DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes [bitbucket.org]
User = hg [topsecret.server.com]
Port = 50022
ForwardX11 = no ***.cfg
[group1]
k1 = v1
k2:v2 [group2]
k1 = 2222
k2 = 1111
k3 = 'asd' [group3] ------------
import configparser
config = configparser.ConfigParser()
config.read('config.ini') print(config.sections())
print(config['bitbucket.org']['User'])
print(config['bitbucket.org']['Compression'])
print(config['topsecret.server.com']['CompressionLevel']) import configparser
config = configparser.ConfigParser()
config.read('conf.cfg') print(config.sections())
print(config.options('group2'))
print(config.items('group2'))
print(config.get('group2','k3'))
print(config.getint('group2','k1')) config.set('group2','k3','alice')
config.write(open('conf.cfg','w')) print(config.has_section('group5'))
config.add_section('group5')
config.write(open('conf.cfg','w')) config.remove_section('group5')
config.write(open('conf.cfg','w')) config.remove_option('group3','k1')
config.write(open('conf.cfg','w'))

hashlib 模块

hash (152位)  退出程序 hash() 值就变了   两个不同的变量有可能hash值是相同的
MD5 (128位) 退出程序MD5() 值不变 基于hash()的 >>> import hashlib
>>> m = hashlib.md5()
>>> m.update(b'alice')
>>> m.hexdigest() #十六进制格式的MD5
'6384e2b2184bcbf58eccf10ca7a6563c'
>>> m.digest() #二进制格式的MD5
b'\x93$(\x86\x1a\xb0\xb8\x15\x1fzP\x81H\x1eJ\x0b' MD5 功能 1.任意长度处理后都是128位 2.不同的输入得到不同的结果 唯一性
MD5 特点 1.压缩性 2.容易计算 3.抗修改性 4.强抗碰撞
MD5 用途 1.防止被篡改 2.防止直接看到明文 3.防止抵赖(数字签名) hashlib.md5() #128位
hashlib.sha1() #160位
hashlib.sha256() #256位
hashlib.sha384() #384位
hashlib.sha512() #512位

subprocess 模块

通过Python去执行一条系统命令或脚本,os.system('ls') commands popen2 等也可以
官方推出subprocess,提供统一的模块来是实现对系统命令或脚本的调用

三种执行命令的方法
subprocess.run(*popenargs, input=None, timeout=None, check=False, **kwargs) #官方推荐
subprocess.call(*popenargs, timeout=None, **kwargs) #跟上面实现的内容差不多,另一种写法
subprocess.Popen() #上面各种方法的底层封装

1.
标准写法
subprocess.run(['df','-h'],stderr=subprocess.PIPE,stdout=subprocess.PIPE,check=True) 涉及到管道|的命令需要这样写
subprocess.run('df -h|grep disk1',shell=True) #shell=True的意思是这条命令直接交给系统去执行,不需要python负责解析 subprocess.run('python test.py')
subprocess.run(['calc'],stderr=subprocess.PIPE,stdout=subprocess.PIPE,check=True) #calc mspaint tasklist
subprocess.run(['netstat','-ano'],stderr=subprocess.PIPE,stdout=subprocess.PIPE,check=True) 2.
subprocess.call('python test.py')
subprocess.call(['netstat','-ano']) #执行命令 返回执行状态 返回 0 或 非0
subprocess.check_call(['netstat','-ano']) #执行命令 结果位为0 正常返回 否则 抛异常
subprocess.getstatusoutput('dir 4.模块') #接收字符串格式命令 返回元组形式 第1个为执行状态 ,第二个为命令结果
subprocess.getoutput('dir 4.模块') #接收字符串格式命令 返回执行结果
subprocess.check_output(['netstat','-ano']) #执行命令 返回结果 3.
subprocess.Popen('python test.py')
subprocess.Popen('python3 guess_age.py',stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE,shell=True)
a=subprocess.run('sleep 10',shell=True,stdout=subprocess.PIPE)
a=subprocess.Popen('sleep 10',shell=True,stdout=subprocess.PIPE)

json/pickle/shelve/xml/configparser/hashlib/subprocess - 总结的更多相关文章

  1. python笔记-7(shutil/json/pickle/shelve/xml/configparser/hashlib模块)

    一.shutil模块--高级的文件.文件夹.压缩包处理模块 1.通过句柄复制内容 shutil.copyfileobj(f1,f2)对文件的复制(通过句柄fdst/fsrc复制文件内容) 源码: Le ...

  2. 模块 - json/pickle/shelve/xml/configparser

    序列化: 序列化是指把内存里的数据类型转变成字符串,以使其能存储到硬盘或通过网络传输到远程,因为硬盘或网络传输时只能接受bytes. 为什么要序列化: 有种办法可以直接把内存数据(eg:10个列表,3 ...

  3. PYTHON-模块 json pickle shelve xml

    """ pickle 和 shevle 序列化后得到的数据 只有python才能解析 通常企业开发不可能做一个单机程序 都需要联网进行计算机间的交互 我们必须保证这个数据 ...

  4. Python学习笔记——基础篇【第六周】——json & pickle & shelve & xml处理模块

    json & pickle 模块(序列化) json和pickle都是序列化内存数据到文件 json和pickle的区别是: json是所有语言通用的,但是只能序列化最基本的数据类型(字符串. ...

  5. python 序列化及其相关模块(json,pickle,shelve,xml)详解

    什么是序列化对象? 我们把对象(变量)从内存中编程可存储或传输的过程称之为序列化,在python中称为pickle,其他语言称之为serialization ,marshalling ,flatter ...

  6. 常用模块(json/pickle/shelve/XML)

    一.json模块(重点) 一种跨平台的数据格式 也属于序列化的一种方式 介绍模块之前,三个问题: 序列化是什么? 我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化. 反序列化又是什么? 将 ...

  7. python序列化及其相关模块(json,pickle,shelve,xml)详解

    什么是序列化对象? 我们把对象(变量)从内存中编程可存储或传输的过程称之为序列化,在python中称为pickle,其他语言称之为serialization ,marshalling ,flatter ...

  8. Python模块 shelve xml configparser hashlib

    常用模块1. shelve 一个字典对象模块 自动序列化2.xml 是一个文件格式 写配置文件或数据交换 <a name="hades">123</a>3. ...

  9. python模块(shelve,xml,configparser,hashlib,logging)

    1.1shelve模块 shelve 模块比pickle模块简单,只有一个open函数,返回类似字典对象,可读可写:key必须为字符串, 而值可以是python所支持的数据类型. shelve模块主要 ...

随机推荐

  1. atitit.jndi的架构与原理以及资源配置and单元测试实践

    atitit.jndi的架构与原理以及资源配置and单元测试实践 1. jndi架构 1 2. jndi实现原理 3 3. jndi资源配置 3 3.1. resin  <database> ...

  2. git commit 、CHANGELOG 和版本发布的标准自动化

    一直以来,因为团队项目迭代节奏很快,每次发布的更新日志和版本更新都是通过人肉来完成的.有时候实在忙的团团转,对于手动的写这些更新信息就显得力不从心了.对于团队新来的小伙伴,有时候遇到些紧急情况,就更显 ...

  3. 使用ss命令代替 netstat

    ss是Socket Statistics的缩写. 顾名思义,ss命令可以用来获取socket统计信息,它可以显示和netstat类似的内容.但ss的优势在于它能够显示更多更详细的有关TCP和连接状态的 ...

  4. 迅搜sdk试用

    1. sdk支持PHP 2. 针对mysql的某个库的某个表??进行索引,简单的说就是一个project,需要对应一个配置文件: 3. 分索引服务与搜索服务两个,另带中文分词功能:索引数据会有演示,但 ...

  5. find命令应用exec及xargs

    find最普通的用法是查找文件,然后要对文件进行处理就需要用到参数-exec. 先看下manpage中介绍: -exec command ; Execute command; status is re ...

  6. ARP-Address Resolution Protocol-地址解析协议

    主要内容摘自:图解TCP/IP ARP是一种解决地址问题的协议.以目标IP地址为线索,用来定位下一个应该接受数据分包的网络设备的mac地址. 如果目标主机不在同一个链路上时,可以通过ARP查找下一跳路 ...

  7. yii save model return id null

    /** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' ...

  8. Respond.js – 让不懂爱的 IE6-8 支持 CSS3 Media Query

    respond.min.js <script src="js/respond.min.js"></script> respond.min.js代码: /*! ...

  9. html5 webwork

    在Web开发的时候经常会遇到浏览器不响应事件进入假死状态,甚至弹出“脚本运行时间过长“的提示框,如果出现这种情况说明你的脚本已经失控了. 一个浏览器至少存在三个线程:js引擎线程(处理js).GUI渲 ...

  10. Asp.net中使用文本框的值动态生成控件的方法

    这篇文章主要介绍了Asp.net中使用文本框的值动态生成控件的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下 看到一个网友,有论坛上问及,动态的生成checkbox控件,在文本框中输入一个“花 ...