day6_1
一、加密模块
1.hashlib
>>> data=hashlib.md5()
>>> data.update(b'hello')
>>> print data.hexdigest()
5d41402abc4b2a76b9719d911017c592
>>> data=hashlib.sha512()
>>> data.update('')
>>> print data.hexdigest()
ba3253876aed6bc22d4a6ff53d8406c6ad864195ed144ab5c87621b6c233b548baeae6956df346ec8c17f5ea10f35ee3cbc514797ed7ddd3145464e2a0bab413
2.hmac
>>> import hmac
>>> h=hmac.new(b'hello')
>>> h.update(b'test')
>>> print h.hexdigest()
0c7490a8663ddd7b947eeec4e2ce85f9
二、执行系统命令
1、os.system 只能返回执行之后的状态码
>>> result=os.system('ver')
Microsoft Windows [版本 6.1.7601]
>>> result
0
2、subprocess
可以执行shell命令的相关模块和函数有:
- os.system
- os.spawn*
- os.popen* --废弃
- popen2.* --废弃
- commands.* --废弃,3.x中被移除
import commands
result = commands.getoutput('cmd')
result = commands.getstatus('cmd')
result = commands.getstatusoutput('cmd')
以上执行shell命令的相关的模块和函数的功能均在 subprocess 模块中实现,并提供了更丰富的功能。
call
执行命令,返回状态
ret = subprocess.call(["ls", "-l"], shell=False)
ret = subprocess.call("ls -l", shell=True)shell = True ,允许 shell 命令是字符串形式
check_call
执行命令,如果执行状态码是 0 ,则返回0,否则抛异常
subprocess.check_call(["ls", "-l"])
subprocess.check_call("exit 1", shell=True)check_output
执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常
subprocess.check_output(["echo", "Hello World!"])
subprocess.check_output("exit 1", shell=True)subprocess.Popen(...)
用于执行复杂的系统命令
参数:
- args:shell命令,可以是字符串或者序列类型(如:list,元组)
- bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
- stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
- preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
- close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。
所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。 - shell:同上
- cwd:用于设置子进程的当前目录
- env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
- universal_newlines:不同系统的换行符不同,True -> 同意使用 \n
- startupinfo与createionflags只在windows下有效
将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
import subprocess
ret1 = subprocess.Popen(["mkdir","t1"])
ret2 = subprocess.Popen("mkdir t2", shell=True)
终端输入的命令分为两种:
- 输入即可得到输出,如:ifconfig
- 输入进行某环境,依赖再输入,如:python
import subprocess
obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)
import subprocess
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n ')
obj.stdin.write('print 2 \n ')
obj.stdin.write('print 3 \n ')
obj.stdin.write('print 4 \n ')
obj.stdin.close()
cmd_out = obj.stdout.read()
obj.stdout.close()
cmd_error = obj.stderr.read()
obj.stderr.close()
print cmd_out
print cmd_error
import subprocess
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n ')
obj.stdin.write('print 2 \n ')
obj.stdin.write('print 3 \n ')
obj.stdin.write('print 4 \n ')
out_error_list = obj.communicate()
print out_error_list
import subprocess obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out_error_list = obj.communicate('print "hello"')
print out_error_list
shutil 文件复制
import shutil
shutil.make_archive('','gztar')#打包格式为gz.tar
shutil.make_archive('','bztar')#打包格式为gz.tar
shutil.make_archive('','zip')#打包格式为zip
shutil.copyfile('123.txt','456.txt')#复制文件
shutil.copy('1/1.txt','test')#把目录中的文件复制到指定的目录中
shutil.rmtree('')#递归删除目录
三、持久化
1、json
2、pickle
3、shelve
shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式
import shelve def shelve_write():
dict1={'username':'root','password':123,'host':'localhost','prot':3306}
list1=['name','root','db','mysql'] d=shelve.open('shelve_test.txt')
d['D1']=dict1 #持久化字典
d['L1']=list1 #持久化列表
d.close() def shelve_read():
d=shelve.open('shelve_test.txt')
print(d['D1']) #读取字典
print(d['L1']) #读取列表
shelve_read()
四、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>
import xml.etree.ElementTree as ET
tree=ET.parse('test.xml')
root=tree.getroot()
# print root.tag
#遍历xml文档
for data in root:
print data.tag,data.attrib
for i in data:
print i.tag,i.text
print '------'
#只遍历year节点
for node in root.iter('rank'):
print node.tag,node.text
# #修改year节点
for node in root.iter('year'):
new_year=int(node.text)+20
node.text=str(new_year)
node.set('update','yes')
tree.write('xym.xml')
#删除
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country)
tree.write('output.xml')
#创建xml文档
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("test11.xml", encoding="utf-8",xml_declaration=True)
ET.dump(new_xml) #打印生成的格式
configparser
import configparser #创建配置文件
config = configparser.ConfigParser() #调用模块中的类,并实例化
config['DEFAULT']={'name':'xym'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes' with open('example.ini', 'w') as configfile:
config.write(configfile) #查询指定的内容
print(config.read('example.ini'))
result=config.sections()
print(result)
print(config['DEFAULT']['forwardx11'])
print(config.defaults()) for key in config['topsecret.server.com']:
print(key) #读取配置
print(config['topsecret.server.com'])
config.read('example.ini')
print(config.sections())
print(config.options('bitbucket.org'))
print(config.items('bitbucket.org'))
print(config.get('bitbucket.org','user'))#获取value
print(config.getint('bitbucket.org','user'))#如果值不为数值为报错 #删除
data=config.remove_section('bitbucket.org')
config.write(open('i.cfg','wb'))
logging 日志
日志等级: CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0 只有大于当前日志等级的操作才会被记录
import logging
logger=logging.getLogger('test-log') #实例化
logger.setLevel(logging.DEBUG) #设置全局的日志等级
ch=logging.StreamHandler() #屏幕
ch.setLevel(logging.DEBUG) #屏幕的日志等级,输出的日志级别大于DEBUG才显示
fh=logging.FileHandler('access.log') #日志记录到文件
fh.setLevel(logging.WARN) #文件的日志等级,输出的日志级别大于DEBUG才记录
formatter=logging.Formatter('%(asctime)s -%(name)s -%(levelname)s - %(message)s') #日志格式
ch.setFormatter(formatter)
fh.setFormatter(formatter)
logger.addHandler(ch)
logger.addHandler(fh)
#logger.debug('debug message')
#logger.info('info message')
#logger.warning('warning message')
#logger.error('error message')
#logger.critical('critical message')
day6_1的更多相关文章
随机推荐
- Objective-C 与 C++ 的异同
stackflow 上有同学提问"C++ 与 Objective-C 有什么异同?"楼下的提供的两个资料挺不错的. 其一是: Pierre Chatelier 写的 <Fro ...
- MySQLdb 1031 Error
Python import MySQLdb 有可能报:site-packages/pkg_resources.py:1031: UserWarning: /home/***/.python-eggs ...
- Oracle Metadata Management (OMM)元数据管理 12.2.1发布
元数据管理元数据管理是解决大量关键业务和技术挑战的基础,这些挑战包括元数据实体有多少,上游数据变化的影响,在浏览器中提供友好的分析展现界面,或提供企业范围内的元数据现状分析和改进视图.OMM是一款基于 ...
- ;function($,undefined) 前面的分号是什么用处
;function($,undefined) 前面的分号是什么用处 ;(function($){$.extend($.fn...现般在一些 JQuery 函数前面有分号,在前面加分号可以有多种用途:1 ...
- HTML5实战——svg学习
百度百科: SVG可缩放矢量图形(Scalable Vector Graphics)是基于可扩展标记语言(XML),用于描述二维矢量图形的一种图形格式.SVG是W3C制定的一种新的二维矢量图形格式,也 ...
- LEETCODE —— Single Number
Given an array of integers, every element appears twice except for one. Find that single one. Note:Y ...
- 黑马程序员——JAVA基础之IO流缓冲区,转换流,字节流
------- android培训.java培训.期待与您交流! ---------- 字符流的缓冲区 缓冲区的出现提高了对数据的读写效率. 对应类 • BufferedWriter ...
- django 过滤器 、日期格式化参数
http://blog.csdn.net/xyp84/article/details/7945094 django1.4 html页面从数据库中读出DateTimeField字段时,显示的时间格式和数 ...
- 清华申请退学博士作品:完全用Linux工作
http://www.cnblogs.com/cbscan/articles/3252872.html 下文地址 http://blog.oldboyedu.com/use-linux/ 按: 尽管我 ...
- android国际化操作
1.简单介绍 我们知道在java中通过.properties文件来配置资源文件,一般用的有中文message_zh_CN.properties和英文message_en_US.properties两个 ...