参考:

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')

日志的种类:

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.

日志等级:

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对象的属性如下:

python模块概况,json/pickle,time/datetime,logging的更多相关文章

  1. python模块之json pickle

    1.json模块 功能:将其他形式的数据类型转化为json字符串类型,将json字符串转化为其他对应的数据类型 方法:json.dumps()  作用:将所有单引号变成双引号:将所有数据类型变成字符串 ...

  2. [re模块、json&pickle模块]

    [re模块.json&pickle模块] re模块 什么是正则? 正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法.或者说:正则就是用来描述一类事物的规则 ...

  3. python模块之JSON

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python模块之JSON #1.JSON #JSON表示的对象就是标准的JavaScript语言的对象 # ...

  4. Python包,json&pickle,time&datetime,random模块

    补充内容: 解决模块循环导入的两种方法:(不得已而为之,表示程序结构不够严谨) 将导入模块语句放在文件最下方 保证语句导入之前函数内代码能够被执行 将导入语句放进函数体内 使其不影响整个函数的运行 包 ...

  5. python 模块 - 序列化 json 和 pickle

    1,引入 之前我们学习过用eval内置方法可以将一个字符串转成python对象,不过,eval方法是有局限性的,对于普通的数据类型,json.loads和eval都能用,但遇到特殊类型的时候,eval ...

  6. 常用模块---sys&logging&序列化模块(json&pickle)

    sys 模块 sys.argv 命令行参数List,第一个元素是程序本身路径,通常用来避免io 阻塞 print('欢迎进入') info=sys.argv ': print('login succe ...

  7. python序列化: json & pickle & shelve 模块

    一.json & pickle & shelve 模块 json,用于字符串 和 python数据类型间进行转换pickle,用于python特有的类型 和 python的数据类型间进 ...

  8. python 序列化及其相关模块(json,pickle,shelve,xml)详解

    什么是序列化对象? 我们把对象(变量)从内存中编程可存储或传输的过程称之为序列化,在python中称为pickle,其他语言称之为serialization ,marshalling ,flatter ...

  9. python序列化及其相关模块(json,pickle,shelve,xml)详解

    什么是序列化对象? 我们把对象(变量)从内存中编程可存储或传输的过程称之为序列化,在python中称为pickle,其他语言称之为serialization ,marshalling ,flatter ...

随机推荐

  1. 循环打印i值(面试题)

    /* * 下面的代码,为了实现每隔1秒说一句话, * 找出存在的问题,并改正,然后描述一下你的解决方案. * */ var arr = [ '第一句话', '第二句话', '第三句话', '第四句话' ...

  2. Unparsed aapt error(s)! Check the console for output解决方法

    在Eclipse平台进行Android 应用开发时,编辑,修改或增删 res/下资源文件时有时会遇到如下错误提示:“Unparsed  aapt error(s)! Check the console ...

  3. Android ContentResolve使用

    在Android中使用ContentResolve访问其他程序的数据: http://developer.android.com/reference/android/content/ContentPr ...

  4. 一些常用的vim设置

    以下内容皆来源于网络,感谢原作者.如果引用出处错误,请告知以便修改. 1. vim的几种模式和按键映射 转载自:[1] Map是Vim强大的一个重要原因,可以自定义各种快捷键,用起来自然得心应手.vi ...

  5. node.js之windows下环境终极配置

    大家都知道现在node.js相当流行,出门在外,如果都没听说过node.js,基本上算是out了,前段时间做一个项目,用到了实时通讯功能,当时用的就是node.js来做的,我有幸有研究了一番,别的不敢 ...

  6. mysql 批量更新和批量插入

    1. 批量更新 update table_name set field_name = CASE id WHEN id1 THEN  field_value, WHEN id1 THEN  field_ ...

  7. mysql常用&实用语句

    Mysql是最流行的关系型数据库管理系统,也是目前最常用的数据库之一,掌握其常用的操作语句是必不可少的. 下面是自己总结的mysqp常用&实用的sql语句: 1.mysql -u root - ...

  8. 将war包部署到服务器的详细步骤

    第一步: 先将项目打包成war文件,也就是将在项目上单击鼠标右键,选择Export: 选择WAR file,点击下一步: 会出现如下所示,选择你要保存的位置,点击完成: 在你所选择的地方会有个如下所示 ...

  9. Apache日志轮替规则

     linux : |/usr/local/sbin/cronolog /web/apache/logs/%Y%m%daccess_log    <IfModule log_config_modu ...

  10. 2.b统计字符串长度

    import java.util.*;public class Main {    public static void main(String args[]){    String a;    Sc ...