day5-内置函数、列表生成器、常用模块使用
学习内容:
1. 内置函数
2. 列表生成器
3. 常用模块使用:
time模块
datetime模块
random模块
os,sys模块
pickle,json模块
logging模块
1. 内置函数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# abs: 返回数字绝对值 print(abs(-100)) # all:接收可迭代对象为参数,如果这些参数的bool值都为true,则返回true; 如果参数为空,返回true # bool值为False的情况: 0 , None , 空 print(all([1,2,3,4,5,6])) print(all([0,1,2,3,4,5,6])) print(all([])) # any: 可迭代参数中,只要有任意1个为True则返回True print(any([0,1,2])) print(any(["",1,2])) print(any(["",0,1])) # ascii:返回字符串的ascii print(ascii("hi,草泥马!")) # bin: 返回数字的二进制 print(bin(128)) # bool: 返回布尔值:True 或 False print(bool(0)) print(bool(1)) print(bool("")) # bytearray: 直接修改字符串 a = "hello world" b = a.encode() # b[0] = 'H' # TypeError: 'bytes' object does not support item assignment b2 = bytearray(b) b2[0] = 96 print(b2,type(b2)) # callable: 是否可调用 print(callable("abc")) # char: 数字转为ascii print(chr(97)) # classmethod # eval: 把字符串形式的表达式解析并执行 a = "2 * 3 + 4 * 5" print(eval(a)) # exec: 把字符串形式的代码解析并执行 a = 'print("hello world")' exec(a) # compile: 把一个代码文件加载进来,按exec or eval的方式解析并执行 f = open("job1.py") func = compile('f.read()','','exec') print(func) exec(func) # delattr: 面向对象的会用到 # dict: 把一个对象转换为字典 # dir: 查看对象的方法 a = "hello" print(dir(a)) # divmod: 返回两个数相除的余数和商 print(divmod(10,3)) # enumerate: 遍历序列结构的索引和值 a = [1,2,3,4,5,6,7,8,9] for index,i in enumerate(range(1,10)): print(index) # filter:将列表中的第个值,通过lambda函数来判断,返回符合条件的值。 b = filter(lambda x:x > 5,range(0,10)) for i in b: print(i) # float: 转换数字为浮点类型 print(float(10)) # format:格式化字符串 name = "jerry" age = 99 job = "full stack" info2 = ''' name: {_name} age: {_age} job: {_job} '''.format(_name=name, _age=age, _job=job) print(info2) info3 = ''' ----------info of {0}-------- name: {0} age: {1} job: {2} '''.format(name,age,job) print(info3) # frozenset:不可变集合 a = {1,2,5,4,32} b = frozenset(a) # globals: 打印当前程序中的所有全局变量以字典的形式打印出来(判断一个变量是否存在) a = 1 b = [2,3,4] print(globals()) # hash: 输出hash值: hash值只在当前程序不变,而md5值,在所有程序都一样。 print(hash("你大爷的")) # hex: 把数字转换为16进制 print(hex(255)) # id: 打印内存地址 print(id("hello,guys")) # int: 把对象转换为整数类型 print(int("100")) # isinstance: 判断一个对象是不是一个实例 # issubclass: # iter: # list: 把一个对象转换为列表 # locals: 以字典形式打印局部变量 print(locals()) # map: 将列表作为lambda函数的输入参数,返回lambda操作后的值 a = map(lambda x:x * x,range(1,10)) for i in a: print(i) # reduce: 求列表中所有对象之和 from functools import reduce a = reduce(lambda x,y:x + y,range(1,101)) print(a) # memoryview: 操作内存(只能处理byetes格式):在进行切片并赋值数据时,不需要重新copy原列表数据,可以直接映射原数据内存。 import time for n in (100000,200000,300000,400000): data = b'x' * n start = time.time() b = data while b: b = b[1:] print('bytes',n,time.time() - start) # 输出: # bytes 100000 0.6840388774871826 # bytes 200000 4.017229795455933 # bytes 300000 3.1421799659729004 # bytes 400000 5.833333492279053 import time for n in (100000,200000,300000,400000): data = b'x' * n start = time.time() b = memoryview(data) while b: b = b[1:] print('bytes',n,time.time() - start) # 输出: # bytes 100000 0.019001007080078125 # bytes 200000 0.03800225257873535 # bytes 300000 0.05700325965881348 # bytes 400000 0.07700443267822266 # print: 打印操作 print("hello") # 默认换行 print("hello world",end="") # 不换行打印 # 打印#号进度条 import time for i in range(100): time.sleep(0.5) print("#",end="",flush="True") # 打印到文件 f = open("test.txt","w") print("print to file....",file=f) # reversed: 反转 a = list(range(10)) print(a) a = list(reversed(a)) print(a) # round: 四舍五入 print(round(4.3332)) # slice: 切片 a = list(range(10)) pattern = slice(1,10,2) # 相当于a[1:10:2] for i in a[pattern]: print(i)
2. 列表生成器
l = [x for x in range(0,10)] print(l) 输出: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3.常用模块
time模块:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import time # 打印自1970-01-01 00:00:00至今经历了多少秒 print(time.time()) 输出: 1497418107.8999949 # 打印本地时间 print(time.localtime()) 输出: time.struct_time(tm_year=2017, tm_mon=6, tm_mday=14, tm_hour=13, tm_min=28, tm_sec=55, tm_wday=2, tm_yday=165, tm_isdst=0) # 打印UTC时间 print(time.gmtime()) 输出: time.struct_time(tm_year=2017, tm_mon=6, tm_mday=14, tm_hour=5, tm_min=29, tm_sec=24, tm_wday=2, tm_yday=165, tm_isdst=0) # 打印自定义字段 struct_time = time.localtime(time.time()) print(struct_time.tm_year,struct_time.tm_mon,struct_time.tm_mday) 输出: 2017 6 14 # 转换second 为local time,同time.ctime(seconds) print(time.ctime()) print(time.asctime(time.localtime())) 输出: Wed Jun 14 13:31:00 2017 Wed Jun 14 13:31:00 2017 # 格式化输出 struct_time = time.localtime(time.time() - 60 * 60 * 24 * 7) print(time.strftime("%Y-%m-%d %H:%M:%S",struct_time)) 输出: 2017-06-07 13:31:00 # struct_time 转换为seconds s_time = time.strptime("2017-02-14","%Y-%m-%d") print(time.mktime(s_time)) print(time.mktime(time.gmtime(time.time()))) print(time.mktime(time.localtime(time.time()))) print(time.time()) 输出: 1487001600.0 1497389460.0 1497418260.0 1497418260.5737274
datetime模块:
import datetime # 打印当前时间 print(datetime.datetime.now()) print(datetime.datetime.fromtimestamp(time.time())) 输出: 2017-06-14 13:34:11.529649 2017-06-14 13:34:11.529649 # 打印3小时10分钟之后的时间 print(datetime.datetime.now() + datetime.timedelta(hours=+3,minutes=10)) 输出: 2017-06-14 16:48:24.829137 # 替换年月日....... print(datetime.datetime.now().replace(year=2001,month=10)) 输出: 2001-10-14 13:39:47.690876
random模块:
import random,string random_string = string.ascii_lowercase + string.ascii_uppercase + string.digits print("".join(random.sample(random_string,6))) 输出: fima6N
os,sys模块:
import os,sys # 获取当前工作目录 print(os.getcwd()) 输出: D:\PyCode\day5 # 切换目录 print(os.chdir("D:\\")) # 打印当前文件所有目录 filepath = os.path.abspath(__file__) print(os.path.dirname(filepath)) 输出: D:\PyCode\day5 # 打印文件名 print(os.path.basename(filepath)) 输出: blog.py # 分割目录与文件 print(os.path.split(filepath)) 输出: ('D:\\PyCode\\day5', 'blog.py') # 拼接目录 print(os.path.join("D:\\","PyCode","day5")) 输出: D:\PyCode\day5 # 打印模块的搜索路径 print(sys.path) ['D:\\PyCode\\day5', 'D:\\PyCode', 'D:\\Python36\\python36.zip', 'D:\\Python36\\DLLs', 'D:\\Python36\\lib', 'D:\\Python36', 'D:\\Python36\\lib\\site-packages'] # 打印系统平台 print(sys.platform) 输出: win32
pickle,json模块:
pickle:
-------------------------------------------------------->
# 通过pickle写入文件
import pickle
info = {
"name":"jerry",
"salary":100000
}
f = open("account.txt","wb")
f.write(pickle.dumps(info))
f.close()
# 通过pickle从文件中加载
f = open("account.txt","rb")
account = pickle.loads(f.read())
print(account)
f.close()
# 修改salary的值,保存至文件
account["salary"] = 50000
f = open("account","wb")
f.write(pickle.dumps(account))
print(account)
f.close()
json:
-------------------------------------------------------->
# 通过json写入文件
import json
info2 = {
"name":"jerry",
"age":99,
"sex":"female",
"salary":100000
}
f = open("account2.txt","w")
f.write(json.dumps(info2))
f.close()
# 通过json加载文件
f = open("account2.txt","r")
account = json.loads(f.read())
print(account)
print(account["salary"])
f.close()
logging模块:
很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug()
, info()
, warning()
, error()
and critical() 5个级别,
下面我们看一下怎么用。
看一下这几个日志级别分别代表什么意思:
Level | When it’s used |
---|---|
DEBUG |
Detailed information, typically of interest only when diagnosing problems. |
INFO |
Confirmation that things are working as expected. |
WARNING |
An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. |
ERROR |
Due to a more serious problem, the software has not been able to perform some function. |
CRITICAL |
A serious error, indicating that the program itself may be unable to continue running. |
日志格式
%(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 |
用户输出的消息 |
如果想同时把log打印在屏幕和文件日志里,就需要了解一点复杂的知识 了
Python 使用logging模块记录日志涉及四个主要类,使用官方文档中的概括最为合适:
logger提供了应用程序可以直接使用的接口;
handler将(logger创建的)日志记录发送到合适的目的输出;
filter提供了细度设备来决定输出哪条日志记录;
formatter决定日志记录的最终输出格式。
logger
每个程序在输出信息之前都要获得一个Logger。Logger通常对应了程序的模块名,比如聊天工具的图形界面模块可以这样获得它的Logger:
LOG=logging.getLogger(”chat.gui”)
而核心模块可以这样:
LOG=logging.getLogger(”chat.kernel”)
Logger.setLevel(lel):指定最低的日志级别,低于lel的级别将被忽略。debug是最低的内置级别,critical为最高
Logger.addFilter(filt)、Logger.removeFilter(filt):添加或删除指定的filter
Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或删除指定的handler
Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():可以设置的日志级别
handler
handler对象负责发送相关的信息到指定目的地。Python的日志系统有多种Handler可以使用。有些Handler可以把信息输出到控制台,有些Logger可以把信息输出到文件,还有些
Handler可以把信息发送到网络上。如果觉得不够用,还可以编写自己的Handler。可以通过addHandler()方法添加多个多handler
Handler.setLevel(lel):指定被处理的信息级别,低于lel级别的信息将被忽略
Handler.setFormatter():给这个handler选择一个格式
Handler.addFilter(filt)、Handler.removeFilter(filt):新增或删除一个filter对象
每个Logger可以附加多个Handler。接下来我们就来介绍一些常用的Handler:
1) logging.StreamHandler
使用这个Handler可以向类似与sys.stdout或者sys.stderr的任何文件对象(file object)输出信息。它的构造函数是:
StreamHandler([strm])
其中strm参数是一个文件对象。默认是sys.stderr
2) logging.FileHandler
和StreamHandler类似,用于向一个文件输出日志信息。不过FileHandler会帮你打开这个文件。它的构造函数是:
FileHandler(filename[,mode])
filename是文件名,必须指定一个文件名。
mode是文件的打开方式。参见Python内置函数open()的用法。默认是’a',即添加到文件末尾。
3) logging.handlers.RotatingFileHandler
这个Handler类似于上面的FileHandler,但是它可以管理文件大小。当文件达到一定大小之后,它会自动将当前日志文件改名,然后创建
一个新的同名日志文件继续输出。比如日志文件是chat.log。当chat.log达到指定的大小之后,RotatingFileHandler自动把
文件改名为chat.log.1。不过,如果chat.log.1已经存在,会先把chat.log.1重命名为chat.log.2。。。最后重新创建
chat.log,继续输出日志信息。它的构造函数是:
RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
其中filename和mode两个参数和FileHandler一样。
maxBytes用于指定日志文件的最大文件大小。如果maxBytes为0,意味着日志文件可以无限大,这时上面描述的重命名过程就不会发生。
backupCount用于指定保留的备份文件的个数。比如,如果指定为2,当上面描述的重命名过程发生时,原有的chat.log.2并不会被更名,而是被删除。
4) logging.handlers.TimedRotatingFileHandler
这个Handler和RotatingFileHandler类似,不过,它没有通过判断文件大小来决定何时重新创建日志文件,而是间隔一定时间就
自动创建新的日志文件。重命名的过程与RotatingFileHandler类似,不过新的文件不是附加数字,而是当前时间。它的构造函数是:
TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
其中filename参数和backupCount参数和RotatingFileHandler具有相同的意义。
interval是时间间隔。
when参数是一个字符串。表示时间间隔的单位,不区分大小写。它有以下取值:
S 秒
M 分
H 小时
D 天
W 每星期(interval==0时代表星期一)
midnight 每天凌晨
import logging from logging import handlers # create logger logger = logging.getLogger("test_logs") logger.setLevel(logging.ERROR) # create console handler ch = logging.StreamHandler() ch.setLevel(logging.INFO) # create file hadnler fh = handlers.RotatingFileHandler("access.log",maxBytes=4,backupCount=3) fh.setLevel(logging.WARNING) # crete formatter formatter = logging.Formatter('%(asctime)s pid:%(process)d %(filename)s:%(funcName)s:%(lineno)d %(message)s') # add format to ch and fh ch.setFormatter(formatter) fh.setFormatter(formatter) # add ch and fh to logger 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')
输出:
2017-06-14 15:13:08,013 pid:13832 blog.py:<module>:183 error message
2017-06-14 15:13:08,015 pid:13832 blog.py:<module>:184 critical message