python之旅六【第六篇】模块
json和pickle
用于序列化的两个模块
json,用于字符串 和 python数据类型间进行转换
pickle,用于python特有的类型 和 python的数据类型间进行转换
json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load
json dumps把数据类型转换成字符串 dump把数据类型转换成字符串并存储在文件中 loads把字符串转换成数据类型 load把文件打开从字符串转换成数据类型
pickle同理
1 import json 2 ''' 3 json dumps把数据类型转换成字符串 dump把数据类型转换成字符串并存储在文件中 4 loads把字符串转换成数据类型 load把文件打开从字符串转换成数据类型 5 ''' 6 name = {'name':'dicky','age':19} 7 print type(json.dumps(name)) #数据类型转换成字符串 8 print json.dumps(name) 9 print json.loads(json.dumps(name)) 10 print type(json.loads(json.dumps(name))) #字符串转换成字典 11 12 结果 13 <type 'str'> 14 {"age": 19, "name": "dicky"} 15 {u'age': 19, u'name': u'dicky'} 16 <type 'dict'>
1 ''' 2 dump把数据类型转换成字符串并存储在文件中 3 load把文件打开从字符串转换成数据类型 4 ''' 5 new_list = {'age':19,'work':'IT'} 6 with open ('test1','w') as openfile: 7 json.dump(new_list,openfile) 8 print "以上就是dump......." 9 10 with open('test1','rb') as readfile: 11 result=json.load(readfile) 12 print "load完成",type(result) 13 print result 14 15 16 结果 17 以上就是dump....... 18 load完成 <type 'dict'> 19 {u'age': 19, u'work': u'IT'}
ConfigParser
用于对特定的配置进行操作,当前模块的名称在 python 3.x 版本中变更为 configparser。
1 import ConfigParser 2 3 ''' 4 test1 5 [section1] 6 name = dicky 7 k2 = v2 8 age = 13 9 10 [section2] 11 k1 = v1 12 work=IT 13 [shuaige] 14 name = dicky 15 ''' 16 config=ConfigParser.ConfigParser() 17 config.read('test1') 18 #读取 19 sec=config.sections() 20 print sec 21 option=config.options('section1') 22 print option 23 item=config.items('section1') 24 print item 25 val = config.get('section1','name') 26 print val 27 val1 = config.getint('section1','age') 28 print val1 29 #修改 30 sec1=config.remove_section('section3') #删除色彩tion3 31 config.write(open('test1','w')) 32 # sec = config.add_section('shuaige') 33 # config.write(open('test1','w')) 34 # 35 # config.set('shuaige','name','dicky') 36 # config.write(open('test1','w')) 37 38 config.remove_option('section2','work') 39 config.write(open('test1','w')) 40 41 结果 42 ['section1', 'section2', 'shuaige'] 43 ['name', 'k2', 'age'] 44 [('name', 'dicky'), ('k2', 'v2'), ('age', '13')] 45 dicky 46 13
操作系统相关命令
os.system() #执行系统命令
其他的都废弃掉了,以后使用subprocess代替了
主要介绍subprocess
call
1 subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False) 2 执行命令,返回状态码 3 ret = subprocess.call(["ls", "-l"], shell=False) 4 ret = subprocess.call("ls -l", shell=True) 5 shell = True ,允许 shell 命令是字符串形式,也就是使用shell来执行,一般情况下,我们要使用shell=False,也是默认的一种形式,模式就是shell=False
check_call
1 subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False) 2 执行命令,如果执行状态码是 0 ,则返回0,否则抛异常 3 subprocess.check_call(["ls", "-l"]) 4 subprocess.check_call("exit 1", shell=True)
check_output
1 subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False) 2 执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常 3 subprocess.check_output(["echo", "Hello World!"]) 4 subprocess.check_output("exit 1", shell=True) 5 捕获异常 6 若要在结果中捕获标准错误,可以使用 stderr=subprocess.STDOUT 7 >>> subprocess.check_output( 8 ... "ls non_existent_file; exit 0", 9 ... stderr=subprocess.STDOUT, 10 ... shell=True) 11 'ls: non_existent_file: No such file or directory\n'
Popen
1 class subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0) 2 参数 3 args:shell命令,可以是字符串或者序列类型(如:list,元组)最好传入序列 4 bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲 5 stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄 6 preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用 7 close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。 8 所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。 9 shell:同上 10 cwd:用于设置子进程的当前目录 11 env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。 12 universal_newlines:不同系统的换行符不同,True -> 同意使用 \n 13 startupinfo与createionflags只在windows下有效 14 将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
args
如果args 是一个字符串,该字符串将解释为要执行的程序的名字或路径。然而,这只能在不传递参数给程序时可行。
如下解决
1 前提是创建好文件egg.txt 2 >>> import shlex, subprocess 3 >>> command_line = raw_input() 4 /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" 5 >>> args = shlex.split(command_line) 6 >>> print args 7 ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] 8 >>> p = subprocess.Popen(args) # Success!
简单执行命令
1 ret1 = subprocess.Popen(["mkdir","t1"]) 2 ret2 = subprocess.Popen("mkdir t2", shell=True)
Popen 类的实例具有以下方法
1 Popen.poll() 检查子进程是否已经终止 2 Popen.wait() 等待子进程终止 3 Popen.communicate(input=None) 4 与进程交互:将数据发送到标准输入。从标准输出和标准错误读取数据,直至到达文件末尾。等待进程终止。可选的input 参数应该是一个要发送给子进程的字符串,如果没有数据要发送给子进程则应该为None。 5 注意如果你需要发送数据到进程的标准输入,你需要以stdin=PIPE创建Popen对象。类似地,在结果的元组中若要得到非None的数据,你还需要给出stdout=PIPE和/或stderr=PIPE。 6 Popen.send_signal(signal) 发送信号signal 给子进程。 7 Popen.terminate() 终止子进程。 8 Popen.kill() 杀死子进程。 9 Popen.stdin 如果stdin 参数为PIPE,则该属性为一个文件对象,它提供子进程的输入。否则,为None。 10 Popen.stdout 如果stdout 参数为PIPE,则该属性是一个文件对象,它提供子进程中的输出。否则,为None。 11 Popen.stderr 如果stderr 参数为PIPE,则该属性是一个文件对象,它提供子进程中的错误输出。否则,为None。 12 Popen.pid 子进程的进程ID。 13 注意如果你设置shell 参数为True,那么它是产生的shell的进程ID。
View Code
依赖,进入某环境输入
import subprocessobj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)
保存输出
1 import subprocess 2 3 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 4 out_error_list = obj.communicate('print "hello"') 5 print out_error_list 6 7 import subprocess 8 9 obj = subprocess.Popen(["ls"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 10 out_error_list = obj.communicate() 11 print out_error_list
另外一种
stdout.read()
1 import subprocess 2 3 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 4 obj.stdin.write('print 1 \n ') 5 obj.stdin.write('print 2 \n ') 6 obj.stdin.write('print 3 \n ') 7 obj.stdin.write('print 4 \n ') 8 obj.stdin.close() 9 10 cmd_out = obj.stdout.read() 11 obj.stdout.close() 12 cmd_error = obj.stderr.read() 13 obj.stderr.close() 14 15 print cmd_out 16 print cmd_error
加密模块
md5已经废弃
1 import md5 2 hash = md5.new() 3 hash.update('admin') 4 print hash.hexdigest()
View Code
sha废弃
1 import sha 2 hash = sha.new() 3 hash.update('admin') 4 print hash.hexdigest()
View Code
hashlib替代了以上的加密
1 import hashlib 2 hash = hashlib.md5() 3 hash.update('admin') 4 print hash.hexdigest()
1 sha加密 2 hash = hashlib.sha1() 3 hash.update('admin') 4 print hash.hexdigest()
其他的一样,就不一一列举了
以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。
import hashlib# ######## md5 ########hash = hashlib.md5('898oaFs09f') #自定义的key hash.update('admin') print hash.hexdigest()
还不够吊?python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密
1 import hmac 2 h = hmac.new('wueiqi') 3 h.update('hellowo') 4 print h.hexdigest()
日志模块logging
简单用法
1 import logging 2 3 logging.basicConfig(filename='log.log', 4 format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', 5 datefmt='%Y-%m-%d %H:%M:%S %p', 6 level=10) 7 8 logging.debug('debug') 9 logging.info('info') 10 logging.warning('warning') 11 logging.error('error') 12 logging.critical('critical') 13 logging.log(10,'log') 14 15 级别 16 CRITICAL = 50 17 FATAL = CRITICAL 18 ERROR = 40 19 WARNING = 30 20 WARN = WARNING 21 INFO = 20 22 DEBUG = 10 23 NOTSET = 0
详细参考链接:http://www.jianshu.com/p/feb86c06c4f4
转载于:https://www.cnblogs.com/Dicky-Zhang/p/7406736.html
python之旅六【第六篇】模块相关推荐
- 【Python之旅】第五篇(三):Python Socket多线程并发
1.多线程模块 主要是socketserver模块,如下图示: 2.多线程原理 如下图示说明: 3.SockteServer例子说明 服务器端: 客户端: 4.演示 还是以前面例子,对代码进行修改,作 ...
- python socket多线程并发_【Python之旅】第五篇(三):Python Socket多线程并发
前面的几个例子都是单线程的,下面再来说说多线程的. 1.多线程模块 主要是socketserver模块,如下图示: 2.多线程原理 如下图示说明: 3.SockteServer例子说明 服务器端: 客 ...
- 【Python之旅】第四篇(二):Python异常处理与异常捕捉
在Python程序的执行过程中,难免会出现异常的情况,如果做的是跟用户交互的程序,当用户输入不可接受的内容时,在可预见的范围内,我们当然是希望可以给用户一些提示,而不是原来Python内置异常中的那些 ...
- python redis 订阅发布_【Python之旅】第七篇(三):使用Redis订阅服务
在C/S架构中,可以充分地利用Redis订阅服务,实现服务器端和客户端的信息收发,下面说说在Python中如何使用Redistribute的订阅服务. 这里要举的例子是,Server端进行服务的订阅, ...
- 【Python之旅】第五篇(一):Python Socket通信原理
1.Socket socket也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄.应用程序通常通过"套接字"向网络发出请求或者应答网络请求.可以列举中 ...
- 【Python之旅】第七篇(二):Redis使用基础
0.说明 由于学习开发监控软件的需要,因此需要使用到Redis,这里简单介绍. 注意,使用的环境为:Ubuntu 15.10 1.安装 可以采用源码安装,也可以采用apt-get来安装,都比较简单. ...
- 【Python之旅】第四篇(四):基于面向对象的模拟人生游戏类
需要用面向对象的思想编写一个模拟人生的小游戏,其实就目前学的知识来说,最多只能写个故事叙述类的小游戏,因此这里只是给出该游戏中有关class的代码,代码是Alex老师写的,对进一步加深Python面向 ...
- python通信原理实验报告_【Python之旅】第五篇(一):Python Socket通信原理-阿里云开发者社区...
只要和网络服务涉及的,就离不开Socket以及Socket编程,下面就说说Python Socket通信的基本原理. 1.Socket socket也称作"套接字",用于描述IP地 ...
- [Python从零到壹] 六十四.图像识别及经典案例篇之图像傅里叶变换和傅里叶逆变换详解
祝大家新年快乐,阖家幸福,健康快乐! 欢迎大家来到"Python从零到壹",在这里我将分享约200篇Python系列文章,带大家一起去学习和玩耍,看看Python这个有趣的世界.所 ...
最新文章
- Javascript Event事件-总结
- 安装和配置本地maven(三)
- 【百战GAN】新手如何开始你的第一个生成对抗网络(GAN)任务
- element-ui踩坑
- 参数NLS_LENGTH_SEMANTICS的设置问题
- tcpdump使用实例——基于ip统计流量
- python如何安装wordcloud_不知如何利用Python中wordcloud的安装和使用?这里手把手教你...
- android集合优化,android-性能优化之集合类优化
- oracle修改字符集
- Hadoop如何迎击大数据分析的挑战
- 跟我一起认识axure(二)
- leetcode刷题日记-保持城市天际线
- 介绍一款JS适用于现代Web浏览器的电子表格开源在线Excel
- 常见词根-词缀-需要记忆
- java计算两个经纬度之间的直线距离
- 乐高打印机robotc
- 吉利有后手,魅族没有
- wps怎么关闭视图保护_怎么在PPT2013中清除编辑受保护视图功能?
- Exchange控制台错误:WinRM客户端已将请求发送到HTTP服务器
- salvage 数据块打捞工具