要一直走下去

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Random模块:

#!/usr/bin/env python
#_*_encoding: utf-8_*_
import random
print (random.random())  #0.6445010863311293  
#random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0
print (random.randint(1,7)) #4
#random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。
# 其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b
print (random.randrange(1,10)) #5
#random.randrange的函数原型为:random.randrange([start], stop[, step]),
# 从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),
# 结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。
# random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。
print(random.choice('liukuni')) #i
#random.choice从序列中获取一个随机元素。
# 其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。
# 这里要说明一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。
# list, tuple, 字符串都属于sequence。有关sequence可以查看python手册数据模型这一章。
# 下面是使用choice的一些例子:
print(random.choice("学习Python"))#
print(random.choice(["JGood","is","a","handsome","boy"]))  #List
print(random.choice(("Tuple","List","Dict")))   #List
print(random.sample([1,2,3,4,5],3))    #[1, 2, 5]
#random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。

#############Random模块实际应用##########
#随机整数:
print( random.randint(0,99))  #70
 
#随机选取0到100间的偶数:
print(random.randrange(0, 101, 2)) #4
 
#随机浮点数:
print( random.random()) #0.2746445568079129
print(random.uniform(1, 10)) #9.887001463194844
 
#随机字符:
print(random.choice('abcdefg&#%^*f')) #f
 
#多个字符中选取特定数量的字符:
print(random.sample('abcdefghij',3)) #['f', 'h', 'd']
 
#随机选取字符串:
print( random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )) #apple
#洗牌#
items = [1,2,3,4,5,6,7]
print(items) #[1, 2, 3, 4, 5, 6, 7]
random.shuffle(items)
print(items) #[1, 4, 7, 2, 5, 3, 6]

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>
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)
遍历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')
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 = '33'
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
age.text = '19'
 
et = ET.ElementTree(new_xml) #生成文档对象
et.write("test.xml", encoding="utf-8",xml_declaration=True)
 
ET.dump(new_xml) #打印生成的格式
创建XML

 

json模块:

 

>>> import json
>>> print json.dumps('你好')
"\u4e2d\u56fd"

>>> print json.dumps('你好',  ensure_ascii=False)

"你好"

 

json支持的序列化类型: int,float,bool,None,str,list,tuple,dict,python对象

import json
from json import JSONEncoder
from datetime import datetime


class DateTimeJSONEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        else:
            return super(DateTimeJSONEncoder, self).default(obj)


r = json.dumps(cls=DateTimeJSONEncoder, obj={"a": 1, "b": False, "c": datetime.now()})
print(r)     # {"a": 1, "b": false, "c": "2020-06-26 21:16:03"}
让json支持datetime序列化

 

'''
json模块
1、把内存中的数据类型序列化为字符串或者字符串反序列化
2、用于不同的平台之间的数据交换,所以序列化的对象类型应是通用的
例如:字符串、列表、字典
3、一次dump,一次load
'''

#################json序列化#################
import json
f = open('test.txt','w')
info = {'name':'alex','age':22}
json.dump(info,f,ensure_ascii=False)   #等价于 f.write(json.dumps(info, ensure_ascii=False)) ensure_ascii防止中文乱码
f.close()           #test.txt中存放{'name': 'alex', 'age': 22}
#################json反序列化#################
f = open('test.txt','r')
data = json.load(f)  #等价于 f.loads(f.read())
print(data['name'])      # alex

 pickle模块:

'''
pickle模块:
1、只能Python中使用
2、可存放所有对象
3、一次dump,一次load
'''
##################pickle序列化##################
import pickle
def sayhi(name):
    print('hello',name)
info = {'func':sayhi}
f = open('test.txt','wb')
pickle.dump(info,f)  # 或者 f.write(pickle.dumps(info))
f.close()            # 序列化为二进制文件
##################pickle反序列化##################
f = open('test.txt','rb')
data = pickle.load(f)       # 或者pickle.loads(f.read())
data['func']('alex')        # hello,alex

 shelve模块:

'''
shelve模块
可以让你一次dump很多对象,取的时候按名称取。shelve是对pickle更上一层的封装
'''

import shelve
import datetime
#####################序列化#######################
d = shelve.open("test")
info = {'name':'alex','age':22}
pets = {'dog','cat'}
d['info'] = info
d['pets'] = pets
d['date'] = datetime.datetime.now()

#####################反序列化#######################
d = shelve.open("test")
print(d.get('info'))        # {'name': 'alex', 'age': 22}
print(d.get('pets'))        # {'dog', 'cat'}
print(d.get('date'))        # 2018-07-17 22:43:41.091981

 time模块

'''
时间的表示格式:
1、格式化字符串"2018-07-01 13:45:557"
2、时间戳,从1970-1-1到现在的秒数1531908307.0743685
3、元祖,time.localtime() 年月日时分秒等元素
时区UTC+8
'''
import time
time.time()  #获取时间戳,float
time.sleep(2) #暂停2毫秒
time.gmtime(1000) #时间戳1000秒==>为元祖的表示形式UTC
time.localtime(1000) #时间戳1000秒==>为元祖表示形式UTC+8
time.mktime(tuple)  #传入元祖==>时间戳
time.strftime("%Y-%m-%d",tuple)  #元祖==>格式化字符串
time.strptime("2016-09-02","%Y-%m-%d") #格式化字符串==>为元祖
time.asctime(tuple)  #把元祖==>Sat Aug 20 14:59:45 2016格式表示
time.ctime(3232342) #把时间戳==>Sat Aug 20 14:59:45 2016格式表示

datetime模块

import datetime

print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
print(datetime.datetime.now() )
print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分

c_time  = datetime.datetime.now()
print(c_time.replace(minute=3,hour=2)) #时间替换

 os模块

import os
os.getcwd() #获取当前工作目录,即pwd
os.chdir("dirname")  #改变当前脚本工作目录;相当于shell下cd
os.curdir  #返回当前目录: ('.')
os.pardir  #获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2')    #可生成多层递归目录
os.removedirs('dirname1')  #只能删空目录,为空则删除并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname')    #生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname')    #删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname')    #列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove()  #删除一个文件
os.rename("oldname","newname")  #重命名文件/目录
os.stat('path/filename')  #获取文件/目录信息
os.sep    #输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep    #输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
os.pathsep    #输出分隔环境变量path的分隔符,win下为; Linux下为:
os.name    #输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command")  #运行shell命令,直接显示
os.environ  #获取系统环境变量
os.path.abspath(path)  #返回path规范化的绝对路径
os.path.split(path)  #将path分割成目录和文件名二元组返回
os.path.dirname(path)  #返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path)  #返回path最后的文件名。如果path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path)  #如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path)  #如果path是绝对路径,返回True
os.path.isfile(path)  #如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path)  #如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]])  #将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path)  #返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path)  #返回path所指向的文件或者目录的最后修改时间
View Code

sys模块

sys.argv           #命令行参数List,第一个元素是程序本身路径
sys.exit(n)        #退出程序,正常退出时exit(0)
sys.version        #获取Python解释程序的版本信息
sys.maxint         #最大的Int值
sys.path           #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform       #返回操作系统平台名称
sys.stdout.write('please:')
val = sys.stdin.readline()[:-1]
View Code

shutil模块:进行压缩和解压的模块,拷贝文件删除文件等

直接参考http://www.cnblogs.com/wupeiqi/articles/4963027.html

 

 pyYAMAL模块

/etc/http/conf/http.conf:
  file.managed:
    - source: salt://apache/http.conf
    - user: root
    - group: root
    - mode: 644
    - attrs: ai
    - template: jinja
    - defaults:
        custom_var: "default value"
        other_var: 123
{% if grains['os'] == 'Ubuntu' %}
    - context:
        custom_var: "override"
{% endif %}
YAMAL格式配置文件

参考文档:http://pyyaml.org/wiki/PyYAMLDocumentation 

 configparser模块

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[bitbucket.org]
User = hg
 
[topsecret.server.com]
Port = 50022
ForwardX11 = no
ConfigParser配置文件
import configparser
 
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9'}
 
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'     # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
   config.write(configfile)
生成ConfigParser配置文件
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['bitbucket.org']: print(key)
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'
读ConfigParser配置
[section1]
k1 = v1
k2:v2
  
[section2]
k1 = v1
 
import ConfigParser
  
config = ConfigParser.ConfigParser()
config.read('i.cfg')
  
# ########## 读 ##########
#secs = config.sections()
#print secs
#options = config.options('group2')
#print options
  
#item_list = config.items('group2')
#print item_list
  
#val = config.get('group1','key')
#val = config.getint('group1','key')
  
# ########## 改写 ##########
#sec = config.remove_section('group1')
#config.write(open('i.cfg', "w"))
  
#sec = config.has_section('wupeiqi')
#sec = config.add_section('wupeiqi')
#config.write(open('i.cfg', "w"))
  
  
#config.set('group2','k1',11111)
#config.write(open('i.cfg', "w"))
  
#config.remove_option('group2','age')
#config.write(open('i.cfg', "w"))
修改ConfigParser配置

 hashlib模块:用于计算对象的hash值的相关操作,3.x里代替了md5模块和sha模块,主要提供sha1,sha224,sha256,sha384,sha512,md5加密算法

 

import hashlib
 
m = hashlib.md5()
m.update(b"Hello")
m.update(b"It's me")
print(m.digest())
########简便写法###########
hashlib.md5("abc".encode()).digest()
########################
m.update(b"It's been a long time since last time we ...")
 
print(m.digest()) #2进制格式hash
print(len(m.hexdigest())) #16进制格式hash
'''
def digest(self, *args, **kwargs): # real signature unknown
    """ Return the digest value as a string of binary data. """
    pass
 
def hexdigest(self, *args, **kwargs): # real signature unknown
    """ Return the digest value as a string of hexadecimal digits. """
    pass
 
'''
import hashlib
 
# ######## md5 ########
 
hash = hashlib.md5()
hash.update('admin')
print(hash.hexdigest())
 
# ######## sha1 ########
 
hash = hashlib.sha1()
hash.update('admin')
print(hash.hexdigest())
 
# ######## sha256 ########
 
hash = hashlib.sha256()
hash.update('admin')
print(hash.hexdigest())
 
 
# ######## sha384 ########
 
hash = hashlib.sha384()
hash.update('admin')
print(hash.hexdigest())
 
# ######## sha512 ########
 
hash = hashlib.sha512()
hash.update('admin')
print(hash.hexdigest())
hashlib

 

'''
python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密
散列消息鉴别码,简称HMAC,是一种基于消息鉴别码MAC(Message Authentication Code)的鉴别机制。
使用HMAC时,消息通讯的双方,通过验证消息中加入的鉴别密钥K来鉴别消息的真伪;
一般用于网络通信中消息加密,前提是双方先要约定好key,就像接头暗号一样,
然后消息发送把用key把消息加密,接收方用key + 消息明文再加密,
拿加密后的值 跟 发送者的相对比是否相等,这样就能验证消息的真实性,及发送者的合法性了。
'''
import hmac
h = hmac.new(b'abcd', '你好'.encode(encoding="utf-8"))
print(h.hexdigest())
双重加密

 

posted on 2018-07-06 09:36  要一直走下去  阅读(233)  评论(0编辑  收藏  举报