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的更多相关文章
随机推荐
- 用Handler图片轮播练习
XML代码 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:andr ...
- 滤镜与CSS3效果
-webkit-filter是css3的一个属性,Webkit率先支持了这几个功能,感觉效果很不错.一起学习一下filter这个属性吧. 现在规范中支持的效果有: grayscale 灰度 ...
- hdu 1057 (simulation, use sentinel to avoid boudary testing, use swap trick to avoid extra copy.) 分类: hdoj 2015-06-19 11:58 25人阅读 评论(0) 收藏
use sentinel to avoid boudary testing, use swap trick to avoid extra copy. original version #include ...
- 使用函数库(JAVA API)
/*使用函数库(JAVA API) * 在JAVA的API里类被封装在一个个的package,要使用package的类之前必须 * 要知道这个类属于哪个package * 引用类方式: * 1.通过i ...
- goldengate 12c 12.2 新特性(updated)
GoldenGate 12.2已经提供下载,增加了不少新特性 1. 异构配置加强不在需要sourceDefs和AssumeTargetDefs文件,在队列文件中已经包含metadata信息,比如tab ...
- Android 微信UI 、点击操作
上一篇,我们介绍了微信界面的相关知识点.今天我们就来把微信的界面做出来. 首先我们新建一个layout-->LinearLayout-->weixin.xml 我们使用上中下线性布局,采用 ...
- no package 'webkit-1.0' found
linux安装程序的时候 ./configure 提示 no package 'webkit-1.0' found 解决方法: 安装 libwebkitgrk-dev包 1. sudo apt-get ...
- RABBITMQ/JAVA (主题)
上篇博文中,我们进一步改良了日志系统.即使用Direct类型的转换器,使得接受者有能力进行选择性的接收日志,而非fanout那样,只能够无脑的转发. 虽然使用Direct类型的转换器改进了日志系统.但 ...
- 简介C#读取XML的两种方式
简介C#读取XML的两种方式 作者: 字体:[增加 减小] 类型:转载 时间:2013-03-03 在程序中访问进而操作XML文件一般有两种模型,分别是使用DOM(文档对象模型)和流模型,使用DOM的 ...
- F - To the Max
Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous s ...