python自动化开发 day06

Author:@南非波波

课程大纲:

day05

http://www.cnblogs.com/alex3714/articles/5161349.html

day06

http://www.cnblogs.com/alex3714/articles/5188179.html

一、模块回顾

1. os模块

2. sys模块

3. shutil模块

高级的 文件、文件夹、压缩包 处理模块

shutil.copyfileobj(fsrc, fdst[, length])

功能:将文件内容拷贝到另一个文件中,可以部分内容

shutil.copyfile(src, dst)

功能:仅拷贝文件

shutil.copymode(src, dst)

功能:仅拷贝权限,内容、组、用户均不变

shutil.copystat(src, dst)

功能:拷贝状态的信息,包括:mode bits, atime, mtime, flags

shutil.copy(src, dst)

功能:拷贝文件和权限

shutil.copy2(src, dst)

功能:拷贝文件和状态信息

1. zipfile


2. tarfile

4. shelve模块

二次封装pickle模块功能,对比pickle而言,shelve实现了按照‘键’来取值

示例:

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import shelve

name = ['swht','shen','test']
class Test(object):
    def __init__(self,n):
        self.n = n
t1 = Test(1234)
t2 = Test(123456)

#存数据
# shelve_file = shelve.open('ret.txt')
# shelve_file['use'] = name
# shelve_file['t1'] = t1
# shelve_file['t2'] = t2
# shelve_file.close()

#取数据
shelve_load = shelve.open('ret.txt')
a = shelve_load.get('use')
print(a)
b = shelve_load.get('t1')
print(b.n)
c = shelve_load.get('t2')
print(c.n)
shelve_load.close()

5.configparser模块

示例:

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import configparser

#生成文档
#["DEFAULT"]是一个全局模块,对所有的模块生效
'''
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)
'''

#查询
'''
config = configparser.ConfigParser()
config.read('example.ini')
print(config.sections())  #['bitbucket.org', 'topsecret.server.com']
if 'bitbucket.org' in config:
    print('True')
print("['bitbucket.org']['User']:",config['bitbucket.org']['User'])
print("['bitbucket.org']['Compression']:",config['bitbucket.org']['Compression'])
for key in config['bitbucket.org']:
    print(key)
'''
#读
'''
config = configparser.ConfigParser()
config.read('example.ini')
secs = config.sections()
print(secs) #['bitbucket.org', 'topsecret.server.com']

options = config.options('topsecret.server.com')
print(options) #['host port', 'forwardx11', 'compression', 'serveraliveinterval', 'compressionlevel']

item_list = config.items('bitbucket.org')
print(item_list) #[('compression', 'yes'), ('serveraliveinterval', '45'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]

val = config.get('bitbucket.org','compression')
print(val)
'''

#改写
config = configparser.ConfigParser()
config.read('example.ini')

#实现从原来的文件中读取,删除[bitbucket.org]模块后将其他内容写到example_new.ini文件中
# sec = config.remove_section('bitbucket.org')
# config.write(open('example_new.ini', "w"))

#添加[swht]模块
# sec = config.has_section('swht')
# sec = config.add_section('swht')
# config.write(open('example_new1.ini', "w"))

6. hashlib模块

该模块提供了多个算法对字符串进行加密操作。

示例代码:

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import hashlib

'''
#md5加密
md5num = hashlib.md5()
md5num.update(b"shendiaoxia1278@sohu.com")
print(md5num.hexdigest()) #7e023c9fafc96423da854e4923f466a1
'''

'''
#sha1加密
sha1num = hashlib.sha1()
sha1num.update(b"shendiaoxia1278@sohu.com")
print(sha1num.hexdigest()) #dd8d5deaa16c2dde03785aac99943f8f75bfaba9
'''

'''
#sha256加密
hash = hashlib.sha256()
hash.update(b"shendiaoxia1278@sohu.com")
print(hash.hexdigest()) #14b03e2271da2cc9b0cc3ff73727c6d3ba6ba17077470a92162f7b46c9d1d968
'''

'''
#sha384加密
hash = hashlib.sha384()
hash.update(b"shendiaoxia1278@sohu.com")
print(hash.hexdigest()) #a27bbc0d66d6b8b00a7ebfcad662ebed385fe2098898dfe23b88ffa88e1b6565d82e7eee5c9950c90231d0c0aa286e00
'''

'''
#sha512加密
hash = hashlib.sha512()
hash.update(b"shendiaoxia1278@sohu.com")
print(hash.hexdigest()) #42bb1886bba49373c8f8177fba32a58a1f31af7272219789db52776428789f4a39970da9a36fdef6ab76651ed9f07e0fa140e4fa7dd325cb52559389bb80ceab
'''

高级加密代码

'''
# import hashlib

# ######## md5 #######
hash = hashlib.md5(b'898oaFs09f')
hash.update(b"shendiaoxia1278@sohu.com")
print(hash.hexdigest()) #2aa29d812ca08b39d96f9441775420ba
'''

'''
import hmac

#可以使用在用户登录的时候,使用用户输入的用户名和密码进行加密后作为用户的密码

hash = hmac.new(b"shendiaoxia1278@sohu.com")
hash.update(b"swht")
print(hash.hexdigest()) #c65d9bc3f37d6cfb9a9c959a18463bf4

'''

7. subprocess模块

1. python2.7

    import subprocess
    #默认状态shell = False,必须使用一个列表的方式将shell命令传递进去
    ret = subprocess.call(["ls", "-l"], shell=False)
    #使用shell = True告诉subprocess模块对用户传入的shell命令不转义,即使用原生shell命令
    ret = subprocess.call("ls -l", shell=True)


2. python3.5

8. logging模块

示例:

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import logging

# logging.warning("user [swht] is start the systerm!")
# logging.critical("server is down!")
#创建日志
logger = logging.getLogger('[Test-Log]')
logger.setLevel(logging.DEBUG) #全局级别优先级较高

#创建一个控制台的handler并设置日志级别
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

#创建一个文件的handler并设置日志级别
fh = logging.FileHandler("access.log")
fh.setLevel(logging.WARNING)
#创建日期格式

fomatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s',datefmt='%Y-%m-%d %H:%M:%S')

#add formatter to ch and fh
ch.setFormatter(fomatter)
fh.setFormatter(fomatter)

logger.addHandler(ch)
logger.addHandler(fh)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

#输出格式:
'''
2016-02-20 16:53:27 [Test-Log] DEBUG debug message
2016-02-20 16:53:27 [Test-Log] INFO info message
2016-02-20 16:53:27 [Test-Log] WARNING warn message
2016-02-20 16:53:27 [Test-Log] ERROR error message
2016-02-20 16:53:27 [Test-Log] CRITICAL critical message
'''

二、面向对象编程

1. 面向对象的介绍

1.    不要写重复的代码
2.    代码易扩展,程序遵循易读、易改的原则

2. 面向对象的特性

1.    封装
2.    继承
    1.    基类或父类或超类
    2.    子类或派生类
    一般情况下,一个子类只能有一个基类,但在python中,一个子类是可以继承多个基类,实现多重继承,可以通过多级继承来实现;继承的过程就是从一般到特殊的过程
3.    多态
    实现接口的重用

3. 类、方法

类 class

示例:

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
class Role(object):
    def __init__(self,name,role,weapon,life_value):
        self.name = name
        self.role = role
        self.weapon = weapon
        self.life_value = life_value
    def buy_weapon(self,weapon):
        self.weapon = weapon
        print("%s 成功购买[%s]" % (self.name,weapon))

#实例化
p1 = Role('swht','p','A11',100)
t1 = Role('shen','t','A11',100)

print("p1[weapon]初始值:",p1.weapon)
print("t1[weapon]初始值:",t1.weapon)

#买枪行为
p1.buy_weapon("AK65")
t1.buy_weapon("AK60")

print("p1[weapon]当前值:",p1.weapon)
print("t1[weapon]当前值:",t1.weapon)

作业:

模拟人生游戏

    1.    至少有两个不同的角色
    2.    玩的过程中,必须有交互
    3.    根据不同的交互产生不同的行为
    4.    一定要用到面向对象编程的语法及思想
文章目录
  1. 一、模块回顾
    1. 1. os模块
    2. 2. sys模块
    3. 3. shutil模块
    4. 4. shelve模块
    5. 5.configparser模块
    6. 6. hashlib模块
    7. 7. subprocess模块
      1. 8. logging模块
  2. 二、面向对象编程
    1. 1. 面向对象的介绍
    2. 2. 面向对象的特性
    3. 3. 类、方法
      1. 类 class
      2. 作业: