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

时间: 2024-08-02 02:39:22

2016/09/20的相关文章

2016/02/20 codes

<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title>2016/02/20</title></head><body><div id="mainDiv"> <div id = "content"> <div id = &qu

2016.09.21 公司裁员想到的

公司最近裁员,好多同事都走了. 想到了,不管在那里都要努力工作,成为该领域的专家,才能立于不败之地. 得之何喜,失之何忧. 加油,最好自己,无愧我心. 不断进步,不断上升 2016.09.21 晚 于北京朝阳

【英语学习】2016.09.11 Culture Insider: Teacher&#39;s Day in ancient China

Culture Insider: Teacher's Day in ancient China 2016-09-10 CHINADAILY Today is the 32nd Chinese Teacher's Day – a festival celebrating the 2,300-year tradition of respecting teachers and education in China. It's similar to the birthday of Confucius o

【转】DBMS_STATS.GATHER_TABLE_STATS详解 2012-04-22 09:20:10

[转]DBMS_STATS.GATHER_TABLE_STATS详解 2012-04-22 09:20:10 分类: Linux 由于Oracle的优化器是CBO,所以对象的统计数据对执行计划的生成至关重要! 作用:DBMS_STATS.GATHER_TABLE_STATS统计表,列,索引的统计信息(默认参数下是对表进行直方图信息收集,包含该表的自身-表的行数.数据块数.行长等信息:列的分析--列值的重复数.列上的空值.数据在列上的分布情况:索引的分析-索引页块的数量.索引的深度.索引聚合因子)

2016/7/20 1:18:29 PyQT5 炫酷的左侧导航效果

2016/7/20 1:18:29  完整code from PyQt5.QtWidgets import (QApplication, QWidget, QHBoxLayout, QTreeWidget, QTreeWidgetItem, QGroupBox) from PyQt5.QtGui import QIcon, QPixmap from PyQt5.QtCore import QSize class Bar_Navigation(QWidget): def __init__(self

2016.9.20小程序--1

在员工管理的GUI练习中加入数据验证.也就是在添加对象进数组之前,先作数据合法性的验证,数据合法再作添加. 姓名:2个以上的字母或汉字 性别:必须是男或女 年龄:必须为数字 电话:13.15.18开始的11位数字 或者  028-99823345 1.员工类 1 public class Staff { 2 private String name ; 3 private int age ; 4 private String sex ; 5 private String tel ; 6 7 8 9

分布式技术一周技术动态 2016.03.20

分布式系统实践 1. 基于Mesos和Docker的分布式计算平台 https://mp.weixin.qq.com/s?__biz=MzAxMDgzOTA2Mw==&mid=402769128&idx=1&sn=cea3ad1357bd9312acf1768c0a493bfd&scene=1&srcid=0318BTuxT0fsFYwPjpeyuDOa&key=710a5d99946419d90fbc1e7600cce055b6e997d6afafc74c

Bentley.Microstran.Advanced.09.20.01.21 1CD

Bentley.Limcon.03.63.01.14 1CD Bentley.MSTower.06.20.01.09 1CD Geometric.Glovius.Pro.v3.9.Win32_64 1CD Koch.Glitsch.KG.TOWER.v5.01.013 1CD Latitude Geographics Geocortex Essentials v4.1.3 1CD GeoStru.EasyHVSR.v2014.16.2.155 1CD Gexcon.FLACS.v9.0 1CD

2016/09/19

1. Python视频 1) 多层装饰器 USER_INFO = {} def check_login(func): def inner(*args, **kwargs): if USER_INFO.get('is_login', None): ret = func(*args, **kwargs) return ret else: print('please login') return inner def check_admin(func): def inner(*args, **kwarg