您的位置:首页 > 编程语言 > Python开发

python学习笔记五之模块下(基础篇)

2016-02-22 22:35 826 查看
shevle 模块

扩展pickle模块。。。

1.潜在的陷进

>>> import shelve
>>> s = shelve.open("nb")
>>> s['x'] = ['a','b','c']
>>> s['x'].append('d')
>>> s['x']
['a', 'b', 'c']


解析:当你在shelve对象中查找元素的时候,这个对象都会根据已经存储的版本进行重新构建,当你将元素赋值给某个键的时候,
它就被存储上了。上述例子操作如下:
列表['a','b','c']存储键x下
获得存储的表示,并且根据它来创建新的列表,而‘d’被添加到这个副本中。修改的版本还没有被保存。
最终再次获得的版本没有包含'd'
为了正确的使用shelve模块修改存储的对象,必须使用临时变量版定到获得的副本上,并且在修改后重新存储在这个副本。

>>>temp=s['x']
>>>temp.append("d")
>>>s['x'] = temp
>>>s['x']
['a', 'b', 'c','d']


2.支持的数据类型

d = shelve.open('shelve_test') #打开一个文件

class Test(object):
def __init__(self,n):
self.n = n

t = Test(123)
t2 = Test(123334)
name = ["alex","rain","test"]

d["test"] = name #持久化列表
d["t1"] = t      #持久化类
d["t2"] = t2

d.close()


shevel 与 pickle 比较而已 shelve更像是通过key存放数据,而pickle每次dump完数据都需要通过相应顺序的load(导出的是最先dump的数据),即dump两次需要load两次才能取到

最新的数据。

logging模块

简单输入到屏幕 #logging级别默认为warning

logging.debug("print this !!!")
logging.info("just see it !!!")
logging.warning("user [koka] attempted wrong password more than 3 times")
logging.error("user [koka] has locked.")
logging.critical("roomsvr is down")

输入出结果:

WARNING:root:user [koka] attempted wrong password more than 3 times
ERROR:root:user [koka] has locked.
CRITICAL:root:roomsvr is down


basicConfig函数对日志的输出格式及方式做相关配置

logging.basicConfig(
filename='log.log',
level=logging.INFO,
format="%(asctime)s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S")
logging.warning("is when this event was logged.")

2016-02-22 22:25:24 is when this event was logged.


见在logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有

filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。

filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。

format:指定handler使用的日志显示格式。

datefmt:指定日期时间格式。

level:设置rootlogger(后边会讲解具体概念)的日志级别

stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。

format参数中可能用到的格式化串:

%(name)s Logger的名字

%(levelno)s 数字形式的日志级别

%(levelname)s 文本形式的日志级别

%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有

%(filename)s 调用日志输出函数的模块的文件名

%(module)s 调用日志输出函数的模块名

%(funcName)s 调用日志输出函数的函数名

%(lineno)d 调用日志输出函数的语句所在的代码行

%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示

%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数

%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒

%(thread)d 线程ID。可能没有

%(threadName)s 线程名。可能没有

%(process)d 进程ID。可能没有
%(message)s用户输出的消息
将日志同时输入到屏幕和文件

logger = logging.getLogger("KOKA")
logger.setLevel(logging.DEBUG)

# 创建一个handler,用于屏幕输出
ch = logging.StreamHandler()
#定义日志级别,同全局定义级别间取等级高的
ch.setLevel(logging.INFO)

# 创建一个handler,用于写入日志文件
fh = logging.FileHandler("access.log")
fh.setLevel(logging.WARNING)

# 定义handler的输出格式formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
fh.setFormatter(formatter)

# 给logger添加handler
logger.addHandler(ch)
logger.addHandler(fh)

logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

屏幕输出
2016-02-21 22:29:43,113 - KOKA - INFO - info message
2016-02-21 22:29:43,113 - KOKA - WARNING - warn message
2016-02-21 22:29:43,113 - KOKA - ERROR - error message
2016-02-21 22:29:43,114 - KOKA - CRITICAL - critical message

文件输出
2016-02-21 22:29:43,113 - KOKA - WARNING - warn message
2016-02-21 22:29:43,113 - KOKA - ERROR - error message
2016-02-21 22:29:43,114 - KOKA - CRITICAL - critical message


configParser 模块

1.基本的读取配置文件

-read(filename) 直接读取ini文件内容
-sections() 得到所有的section,并以列表的形式返回
-options(section) 得到该section的所有option
-items(section) 得到该section的所有键值对
-get(section,option) 得到section中option的值,返回为string类型
-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

2.基本的写入配置文件
-add_section(section) 添加一个新的section
-set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件。

利用configParser生成一个配置文件
import configparser
#生成实例
config = configparser.ConfigParser()

#方式一 直接定义一个字典内容
config["DEFAULT"] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'}

config['DEFAULT']['ForwardX11'] = 'yes'

#方式二 定义空字典然后赋值
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

#写入文件
with open('example.ini', 'w') as configfile:
config.write(configfile)

#example.ini
[DEFAULT] #全局配置文件
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[bitbucket.org] #节点,继承全局配置
user = hg

[topsecret.server.com]
host port = 50022
forwardx11 = no


读取配置文件

import configparser
config = configparser.ConfigParser()
print(config.sections())
config.read("example.ini")
a = config.sections()
print(config.options("bitbucket.org"))
c = config.items('bitbucket.org')
b = config['bitbucket.org']['User']
c = config['DEFAULT']['Compression']
topsecret = config['topsecret.server.com']
d = topsecret['ForwardX11']
e = topsecret["host port"]
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
print(g)

结果:
[]
['bitbucket.org', 'topsecret.server.com']
['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
hg
yes
no
50022

########### 改写 ##########
configs = configparser.ConfigParser()
configs.read("example.ini")
#移除节点
configs.remove_section('topsecret.server.com')

#判断节点是否存在
print(configs.has_section('wlgc'))

#添加节点
configs.add_section('wlgc')

#修改节点下选项配置
configs.set('bitbucket.org','user','koka')

#移除选项
configs.remove_option('wlgc','name')

configs.write(open('newexample.ini', "w"))


hashlib

hashlib 用于加密相关的操作,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())
m.update(b"It's been a long time since last time we ...")
print(m.digest()) #2进制格式hash
print(len(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

'''

# ######## md5 ########

hash = hashlib.md5()
hash.update(b'admin')
print(hash.hexdigest())

# ######## sha1 ########

hash = hashlib.sha1()
hash.update(b'admin')
print(hash.hexdigest())

# ######## sha256 ########

hash = hashlib.sha256()
hash.update(b'admin')
print(hash.hexdigest())

# ######## sha384 ########

hash = hashlib.sha384()
hash.update(b'admin')
print(hash.hexdigest())

# ######## sha512 ########

hash = hashlib.sha512()
hash.update(b'admin')
print(hash.hexdigest())


View Code
shutil模块

文件和目录处理模块

import shutil
import os

#copyfileobj 拷贝文件对象
#将文件内容拷贝到另一个文件中,可以部分内容
r = open('a','r')
w = open('b','w')
r.close()
w.close()
shutil.copyfileobj(r,w)

#copyfile 拷贝文件
shutil.copyfile('a','c')

#copy 拷贝文件和权限
shutil.copy('a','d')

#copymode 仅拷贝权限。内容、组、用户均不变
shutil.copymode(src, dst)

#copystat 拷贝状态的信息,包括:mode bits, atime, mtime, flag
shutil.copystat(src, dst)

#copy2 拷贝文件和状态信息
shutil.copy2(src, dst)

#copytree 递归拷贝文件
#shutil.ignore_patterns(*patterns) 添加匹配条件
shutil.copytree(os.curdir,'e',symlinks=False, ignore=None)

#rmtree 递归的去移动文件
shutil.move(src, dst)

#move 递归的去移动文件
shutil.move(src, dst)

ret = shutil.make_archive(r'F:\test1','gztar',root_dir=r"F:\test") #压缩文件并返回文件路径
print(ret)

#zip方式
import zipfile
z = zipfile.ZipFile("wlgc.zip",'w')
z.write('c') #添加至压缩包
z.write('d')
z.close()

unz = zipfile.ZipFile("wlgc.zip",'r')
unz.extractall()#可设置解压路径
unz.close()

#tar方式
import tarfile
tar = tarfile.open("wlgc.tar",'w')
tar.add("log.log")
tar.add("example.ini")
tar.close()

untar = tarfile.open("wlgc.tar",'r')
untar.extractall(r'C:\Users\Administrator\Desktop')#可设置解压地址
untar.close()


subprocess 模块

执行系统命令

subprocess.call

语法:
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
语义:
运行由args指定的命令,直到命令结束后,返回 返回码的属性值。


import subprocess
subprocess.call("nslookup 127.0.0.1",shell=True)  #call调用shell ,shell=True表示保持原有的shell方式
subprocess.call(["ping","-w","1","-n","1","127.0.0.1"])


#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()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等


a = subprocess.Popen(["ping","-w","1","-n","1","127.0.0.1"],stdout=subprocess.PIPE)
print(a.stdout.read())


subprocessor.check_call
语法:
    subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
语义:
运行由args指定的命令,直到命令执行完成。果返回码为零,则返回。否则,抛出 CalledProcessError异常。
CalledProcessError对象包含有返回码的属性值。


recode = subprocess.check_call("ipconfig")
print(recode)


subprocess.check_output
语法:
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
语义:
运行args定义的命令,并返回一个字符串表示的输出值。如果返回码为非零,则抛出 CalledProcessError异常。


ret = subprocess.check_output(["nslookup","127.0.0.1"])
print(ret)


optparse模块


def parser_argv(args):
import optparse
parser = optparse.OptionParser()
parser.add_option("-u", "--user", type="string", help="input hostname")
parser.add_option("-g", "--group", type="string", help="input groupname")
parser.add_option("-c", "--cmd", type="string", help="input cmd")
(option,arg) = parser.parse_args(args)
print("user:",option.host)
print("group:",option.group)
print("cmd:",option.cmd)
print("----->",arg)

parser_argv(sys.argv[1:])

result :

python common.py --cmd dir --host host1 --group grou1 ce shi yi xia
host: host1
group: grou1
cmd: dir
-----> ['ce', 'shi', 'yi', 'xia'] #args,它是一个由 positional arguments 组成的列表。


使用流程:

首先,必须 import OptionParser 类,创建一个 OptionParser 对象:


import optparse
parser = optparse.OptionParser()


然后,使用 add_option 来定义命令行参数:

#每个命令行参数就是由参数名字符串和参数属性组成的。如 -u 或者 --user 分别是长短参数名:
parser.add_option("-u", "--user", type="string", help="input hostname")
parser.add_option("-g", "--group", type="string", help="input groupname")
parser.add_option("-c", "--cmd", type="string", help="input cmd")


最后,一旦你已经定义好了所有的命令行参数,调用 parse_args() 来解析程序的命令行:

(option,arg) = parser.parse_args(args)


注: 你也可以传递一个命令行参数列表到 parse_args();否则,默认使用 sys.argv[:1]。

parse_args() 返回的两个值:

options,它是一个对象(optpars.Values),保存有命令行参数值。只要知道命令行参数名,如 user,就可以访问其对应的值: options.user 。

args,它是一个由 positional arguments 组成的列表。

生成程序帮助

optparse 另一个方便的功能是自动生成程序的帮助信息。你只需要为 add_option() 方法的 help 参数指定帮助信息文本,当 optparse 解析到 -h 或者 –help 命令行参数时,会调用 parser.print_help() 打印程序的帮助信息:

parser.add_option("-u", "--user", type="string", help="input hostname")

python common.py --help

Usage: common.py [options]

Options:
-h, --help            show this help message and exit
-u USER, --user=USER  input hostname
-g GROUP, --group=GROUP
input groupname
-c CMD, --cmd=CMD     input cmd

注意: 打印出帮助信息后,optparse 将会退出,不再解析其它的命令行参数


自定义的程序使用方法信息(usage message):

usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)


这行信息会优先打印在程序的选项信息前。当中的 %prog,optparse 会以当前程序名的字符串来替代:如 os.path.basename.(sys.argv[0])。

如果用户没有提供自定义的使用方法信息,optparse 会默认使用: “usage: %prog [options]”。

默认值

parse_args() 方法提供了一个 default 参数用于设置默认值。如:

parser.add_option("-f","--file", action="store", dest="filename", default="foo.txt")
parser.add_option("-v", action="store_true", dest="verbose", default=True)

又或者使用 set_defaults():

parser.set_defaults(filename="foo.txt",verbose=True)
parser.add_option(...)
(options, args) = parser.parse_args()


更多内容见:http://www.cnblogs.com/captain_jack/archive/2011/01/11/1933366.html


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: