2016/09/20
Posted 你的踏板车要滑向哪里
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2016/09/20相关的知识,希望对你有一定的参考价值。
1. Python序列化之pickle模块
- 用于[python特有的类型]和[python基本数据类型]间进行转换
- pickle模块提供了四个功能:dumps、dump、loads、load
- json更加适合跨语言 基本数据类型的序列化
pickle仅适用于python 复杂类型的序列化
# import json # dic = {‘k1‘: ‘v1‘} # print(dic, type(dic)) # # res = json.dumps(dic) # 将python的基本数据类型转化成字符串类型 # print(res,type(res)) # # # s1 = ‘{"abc": 123}‘ # 外面单引号,里面双引号 # dic2 = json.loads(s1) # 将python的字符串类型转化成基本数据类型 # print(dic2, type(dic2)) import json li = [11,22,33] json.dump(li, open(‘db‘, ‘w‘)) # dump:列表转化为字符串,再写入文件 li = json.load(open(‘db‘,‘r‘)) # load:读取文件,并将字符串转化为列表 print(type(li),li)
2. Python时间处理之time/datetime模块
- time_module.py
import time # print(time.time()) # 时间戳,1970年1月1日到当前的秒 # print(time.ctime()) # Tue Sep 20 09:47:33 2016 当前时间 # print(time.ctime(time.time()-86400)) # Mon Sep 19 09:49:00 2016 减一天 # time_obj = time.gmtime() # time.struct_time(tm_year=2016, tm_mon=9, tm_mday=20, tm_hour=1, tm_min=57, tm_sec=1, tm_wday=1, tm_yday=264, tm_isdst=0) # print(time_obj) # print(‘{year}-{month}‘.format(year=time_obj.tm_year,month=time_obj.tm_mon)) # print(time.localtime()) # 本地时间 struct_time # print(time.mktime(time.localtime())) # 转换为时间戳 # time.sleep(4) # 延迟4s # print(‘dfadfa‘) # print(time.strftime(‘%Y-%m-%d %H:%M:%S‘,time.gmtime())) # 2016-09-20 02:11:52 UTC时间 格式化 # print(time.strftime(‘%Y-%m-%d %H:%M:%S‘,time.localtime())) # 2016-09-20 10:12:47 本地时间 格式化 # print(time.strptime(‘2016-09-20 10:15‘,‘%Y-%m-%d %H:%M‘)) # 字符串转为struct_time格式 import datetime # print(datetime.date.today()) # 2016-09-20 # print(datetime.datetime.now()) # 2016-09-20 10:21:50.901668 # print(datetime.datetime.now() + datetime.timedelta(days=10)) # 比现在加10天 # current_time = datetime.datetime.now() # print(current_time.replace(2088,8,8)) # 2088-08-08 10:31:34.615685 # %Y Year with century as a decimal number. # %m Month as a decimal number [01,12]. # %d Day of the month as a decimal number [01,31]. # %H Hour (24-hour clock) as a decimal number [00,23]. # %M Minute as a decimal number [00,59]. # %S Second as a decimal number [00,61]. # %z Time zone offset from UTC. # %a Locale‘s abbreviated weekday name. # %A Locale‘s full weekday name. # %b Locale‘s abbreviated month name. # %B Locale‘s full month name. # %c Locale‘s appropriate date and time representation. # %I Hour (12-hour clock) as a decimal number [01,12]. # %p Locale‘s equivalent of either AM or PM.
3. Python日志处理之logging模块
- logging_module.py
- 日志等级
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
- 同时把log打印在屏幕和文件日志里
import logging # create logger logger = logging.getLogger(‘TEST-LOG‘) # get the logger object first logger.setLevel(logging.DEBUG) # set a global log level # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create file handler and set level to warning fh = logging.FileHandler("access.log") fh.setLevel(logging.WARNING) fh_err = logging.FileHandler("error.log") fh_err.setLevel(logging.ERROR) # create formatter formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘) # add formatter to ch and fh ch.setFormatter(formatter) fh.setFormatter(formatter) fh_err.setFormatter(formatter) # add ch and fh to logger logger.addHandler(ch) logger.addHandler(fh) logger.addHandler(fh_err) # ‘application‘ code logger.debug(‘debug message‘) logger.info(‘info message‘) logger.warn(‘warn message‘) logger.error(‘error message‘) logger.critical(‘critical message‘)
- 日志记录格式
4. 反射
- 利用字符串的形式去对象(模块)中操作(寻找/检查/删除/设置)成员,反射
# getattr()
# hasattr()
# delattr()
# setattr()
- 利用字符串的形式导入模块
# obi = __import__(m)
# obj = __import__(‘lib.‘ + m, fromlist=True)
- 实例:伪造Web框架的路由系统
# import commons # def run(): # inp = input(‘请输入要访问的url‘) # if inp == ‘login‘: # commons.login() # elif inp == ‘logout‘: # commons.logout() # elif inp == ‘home‘: # commons.home() # else: # print(‘404‘) # getattr() # hasattr() # delattr() # setattr() def run(): inp = input(‘请输入要访问的url‘) # inp字符串类型 inp = ’login‘ m, f = inp.split(‘/‘) obj = __import__(‘lib.‘ + m, fromlist=True) if hasattr(obj, f): func = getattr(obj, f) # 利用字符串的形式去对象(模块)中操作(寻找/检查/删除/设置)成员,反射 func() else: print(‘404‘) if __name__ == ‘__main__‘: run()
5. 模块
- logging
- time/datetime
- json/pickle
- requests
补充的模块中特殊变量:
- __doc__ # 文件的注释
- __cached__ # pyc缓存
- __package__
- __file__ # 当前py文件所在的路径
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
- __name__ # 只有执行当前文件时,当前文件的特殊变量 __name__ == __main__
def run(): if __name__ == ‘__main__‘: print(‘run‘)
- sys
- 相关操作:
sys.argv 命令行参数List,第一个元素是程序本身路径
sys.exit(n) 退出程序,正常退出时exit(0)
sys.version 获取Python解释程序的版本信息
sys.maxint 最大的Int值
sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform 返回操作系统平台名称
sys.stdin 输入相关
sys.stdout 输出相关
sys.stderror 错误相关
- 进度条
import sys import time def view_bar(num, total): rate = num / total rate_num = int(rate * 100) r = ‘\r%d%%%s‘ % (rate_num,‘=‘*int(num/2), ) # print(r) sys.stdout.write(r) sys.stdout.flush() if __name__ == ‘__main__‘: for i in range(0, 101): time.sleep(0.05) view_bar(i, 100)
- os
- os.path.abspath(path) 返回path规范化的绝对路径
- os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
- os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
- hashlib 用于加密相关的操作
import hashlib obj = hashlib.md5() obj.update(bytes(‘123‘,encoding=‘utf-8‘)) result = obj.hexdigest() result1 = obj.digest() print(result) print(result1)
- re
- 字符
- 次数
- match
以上是关于2016/09/20的主要内容,如果未能解决你的问题,请参考以下文章