python模块概况,json/pickle,time/datetime,logging

参考:

http://www.cnblogs.com/wupeiqi/articles/5501365.html

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

1、模块的分类

内置模块:存放在lib目录下

第三方模块:通常放到site-packages目录下

自定义模块:可以通过sys.path.append(module_path)添加模块到搜索路径

2、 模块的调用顺序

按path列表从前到后的顺序按模块名搜索模块。一定避免模块重名,不要和内置模块重名。

import sys
for i in sys.path:
    print(i)

打印结果类似下面:

/usr/local/lib/python35.zip
/usr/local/lib/python3.5
/usr/local/lib/python3.5/plat-linux
/usr/local/lib/python3.5/lib-dynload
/root/.local/lib/python3.5/site-packages
/usr/local/lib/python3.5/site-packages

3、导入模块的几种方法

import module   导入同级目录下的单模块
from module.xx.xx import xx    导入嵌套在文件夹下的模块
from module.xx.xx import xx as rename      as后面是模块的别名
from module.xx.xx import *

4、安装第三方包

python3自带pip模块,因此可以使用 pip install <package name>  安装第三方包

也可以使用源码安装。去官网 https://pypi.org/ 搜索你要下载的包,解压后,转到安装包目录下,运行 python setup.py install 

5、json/pickle模块,序列化与反序列化

json.dumps(data)  将基本数据类型转换为字符串

json.loads(str)  将字符串转换为基本数据类型。注意:通过loads反序列化时,一定要用双引号把字符串括起来(因为在其他程序语言中,字符串是用双引号括起来的)

json.dump(data,open('file','w'))  将基本数据类型转换为字符串,并将其写入文件file

json.load(open('file','r'))   从文件file读字符串,将字符串转换为python基本数据类型

dic = {1:'a',2:'b'}
print(dic,type(dic))      #{1:'a',2:'b'},  class 'dict'
res = json.dumps(dic)   #将字典dic转换为字符串res
print(res,type(res))       # "{1:'a',2:'b'}" class 'str'


li = '[1,2,"kaye"]'    # 内层用双引号,外层用单引号,否则会报错!!
print(li,type(li))   #'[1,2,"kaye"]', class 'str'
res = json.loads(li)   #将字符串li转换为列表res
print(res, type(res))   #[1,2,"kaye"], class 'list'

requests.get()方法从API获取字符串,用json.loads()把字符串转换为python基本数据类型。代码如下:

import requests
import json

res = requests.get('http://wthrcdn.etouch.cn/weather_minni?city=北京')
requests.encoding = 'utf-8'
dic = json.loads(res.text)
print(dic,type(dic))

pickle.dumps(data) 将python对象转换为字符串

pickle.loads(str)  将文件内容转换为python对象

pickle.dump(data,open('file','wb')) 将python对象转换为字符串,并将其写入文件file,一定要加b(表示以二进制存储到文件),不然会报错

pickle.load(str,open('file','r'))  从文件file读字符串,将文件内容转换为python对象

json VS pickle

json模块可以支持跨语言的基本数据类型(支持python,c#,php.....等多种语言,但是只支持基本数据类型包括列表、字典、元组等等)

pickle模块可以对复杂类型做操作,比如对象,但是不能支持python以外的其他语言

6、time/datetime模块

import time

print(time.time())      # 返回当前时间戳(从1970年1月1日开始计时到现在,一共有多少秒)
print(time.ctime())     # 返回当前时间,可读性更好
print(time.gmtime())    # 获得格林威治时间(UTC时间)的struct_time模式(时间对象),该对象属性包括tm_yaer,tm_mon,tm_mday,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst
print(time.localtime()) # 和gmtime类似,但返回的是本地时间
print(time.mktime())    # 将stuct_time格式转换为时间戳
print(time.sleep())     # 程序在这里睡眠/延迟,用于处理阻塞
print(time.strftime())  # 将stuct_time格式转换为指定的字符串格式,eg. time.strftime("%Y-%m-%d %H:%M:%S")
print(time.strptime())  # 将字符串格式的时间转换成struct_time格式, eg. time.strptime("2016-09-21","%Y-%m-%d")

datetime模块是对time模块是封装。datetime取日期更方便,time模块取时间戳更方便。

import time
import datetime

print(datetime.date.today())                     # 返回格式2016-09-21
print(datetime.date.fromtimestamp(time.time())          # 将时间戳转换为人类可读的格式
print(datetime.datetime.now()                      # 返回当前时间
pritn(datetime.datetime.now().timetuple()                 # 返回struct_time格式
print(datetime.datetime.now() + datetime.timedelta(days=10))    # 比现在加10天
print(datetime.datetime.now() + datetime.timedelta(days=-10))   # 比现在减10天
print(datetime.datetime.now() + datetime.timedelta(hours=-10))  # 比现在减10小时
print(datetime.datetime.now().replace(2014,5,15))               # 把当前时间中的年月日替换成2014,5,15
print(datetime.strptime())                       # 将字符串的时间转换为struct_time格式

 盗图几张

7、logging模块

import logging
  
logging.basicConfig(filename='log.log',
                    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',
                    level=10)
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
logging.log(10,'log')

日志的种类:

LevelWhen 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.

 日志等级:

CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0

注:只有【当前写等级】大于【日志等级】时,日志文件才被记录。

import logging
 
logging.basicConfig(filename='example.log',level=logging.INFO)       # logging.INFO = 20
logging.debug('This message should go to the log file')      # debug等级是10,小于当前写等级20,因此不会写入到日志文件
logging.info('So should this')    #info等级是20
logging.warning('And this, too')   #warning等级是30

如果想同时把log打印在屏幕和文件日志里,就需要了解一点复杂的知识 了

The logging library takes a modular approach and offers several categories of components: loggers, handlers, filters, and formatters.

logging模块提供了几个组件,包括logger, handlers, filters, formatters

  • Loggers expose the interface that application code directly uses.                             loggers把接口暴露给代码直接使用
  • Handlers send the log records (created by loggers) to the appropriate destination.   handlers发送日志信息到相应的目的地
  • Filters provide a finer grained facility for determining which log records to output.    filters提供细粒度的工具来决定哪些日志信息要输出
  • Formatters specify the layout of log records in the final output.                           formatters声明日志信息的输出结果应该如何布局
import logging
 
#create logger
logger = logging.getLogger('TEST-LOG')   # 获取日志对象
logger.setLevel(logging.DEBUG)     #  全局日志级别
 
 
# 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)     # 设置输出到文件时的日志级别
# 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) # 对输出到文件的句柄,设置输出格式 # add ch and fh to logger logger.addHandler(ch) # ch句柄添加到logger logger.addHandler(fh) # fh句柄添加到logger # 'application' code logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message')

全局日志级别 VS 局部日志级别

当全局日志级别高于局部日志级别,以全局日志级别为准

当全局日志级别低于局部日志级别,以局部日志级别为准

小结一下上面代码中的逻辑:

1,创建一个logger,为logger设定日志级别(setLevel)

2,创建handler(输出到屏幕的是StreamHandler,输出到文件的是FileHandler),为handler设置日志级别(setLevel)

3,创建formatter,将formatter注册到handler(setFormatter)

4,将handler注册到logger

 Formatter对象的属性如下:

原文地址:https://www.cnblogs.com/huamingao/p/5888609.html