day5-模块、包、时间/日志/正则模块

 

第1章 模块介绍

1.1 什么是模块?

#常见的场景:一个模块就是一个包含了一组功能的python文件,好比spam.py,模块名为spam,能够经过import spam使用。html

#在python中,模块的使用方式都是同样的,但其实细说的话,模块能够分为四个通用类别: python

  1 使用python编写的.py文件mysql

  2 已被编译为共享库或DLL的C或C++扩展git

  3 把一系列模块组织到一块儿的文件夹(注:文件夹下有一个__init__.py文件,该文件夹称之为包)程序员

  4 使用C编写并连接到python解释器的内置模块github

1.2 为什么要使用模块?

1.2.1 从文件级别组织程序,更方便管理

随着程序的发展,功能愈来愈多,为了方便管理,咱们一般将程序分红一个个的文件,这样作程序的结构更清晰,方便管理。这时咱们不只仅能够把这些文件当作脚本去执行,还能够把他们当作模块来导入到其余的模块中,实现了功能的重复利用正则表达式

1.2.2 拿来主义,提高开发效率

一样的原理,咱们也能够下载别人写好的模块而后导入到本身的项目中使用,这种拿来主义,能够极大地提高咱们的开发效率sql

#ps:shell

若是你退出python解释器而后从新进入,那么你以前定义的函数或者变量都将丢失,所以咱们一般将程序写到文件中以便永久保存下来,须要时就经过python test.py方式去执行,此时test.py被称为脚本script。express

 

1.3 以spam.py为例来介绍模块的使用:文件名spam.py,模块名spam

#spam.py

print('from the spam.py')

 

money=1000

 

def read1():

    print('spam模块:',money)

 

def read2():

    print('spam模块')

    read1()

 

def change():

    global money

    money=0
spam.py

第2章 使用模块之import

2.1 如何使用模块-》import spam

一、第一次导入模块,会发生3件事,重复导入只会引用以前加载好的结果

1)产生一个新的名称空间

2)运行spam.py代码,产生的名字都存放于1的名称空间中,运行过程当中global关键字指向的就是该名称空间

3)在当前名称空间拿到一个名字spam,该名字指向1的名称空间

引用spam.py中名字的方式:spam.名字

强调:被导入的模块在执行过程当中使用本身独立的名称空间做为全局名称空间
View Code 

二、起别名:import spam as sm

三、一行导入多个模块:import time,sys,spam

 

2.2 import的使用

#模块能够包含可执行的语句和函数的定义,这些语句的目的是初始化模块,它们只在模块名第一次遇到导入import语句时才执行(import语句是能够在程序中的任意位置使用的,且针对同一个模块很import屡次,为了防止你重复导入,python的优化手段是:第一次导入后就将模块名加载到内存了,后续的import语句仅是对已经加载到内存中的模块对象增长了一次引用,不会从新执行模块内的语句),以下

 

#test.py

import spam #只在第一次导入时才执行spam.py内代码,此处的显式效果是只打印一次'from the spam.py',固然其余的顶级代码也都被执行了,只不过没有显示效果.

import spam

import spam

import spam

 

'''

执行结果:

from the spam.py

'''
import的使用

ps:咱们能够从sys.module中找到当前已经加载的模块,sys.module是一个字典,内部包含模块名与模块对象的映射,该字典决定了导入模块时是否须要从新导入。

 

2.3 在第一次导入模块时会作三件事,重复导入会直接引用内存中已经加载好的结果

#1.为源文件(spam模块)建立新的名称空间,在spam中定义的函数和方法如果使用到了global时访问的就是这个名称空间。

#2.在新建立的命名空间中执行模块中包含的代码,见初始导入import spam

    提示:导入模块时到底执行了什么?

    In fact function definitions are also ‘statements’ that are

    ‘executed’; the execution of a module-level function definition

    enters the function name in the module’s global symbol table.

    事实上函数定义也是“被执行”的语句,模块级别函数定义的执行将函数名放

    入模块全局名称空间表,用globals()能够查看

#3.建立名字spam来引用该命名空间

    这个名字和变量名没什么区别,都是‘第一类的’,且使用spam.名字的方式

    能够访问spam.py文件中定义的名字,spam.名字与test.py中的名字来自

    两个彻底不一样的地方。
View Code 

2.4 被导入模块有独立的名称空间

每一个模块都是一个独立的名称空间,定义在这个模块中的函数,把这个模块的名称空间当作全局名称空间,这样咱们在编写本身的模块时,就不用担忧咱们定义在本身模块中全局变量会在被导入时,与使用者的全局变量冲突。

 

测试一:money与spam.money不冲突

#test.py

import spam

money=10

print(spam.money)

 

'''

执行结果:

from the spam.py

1000

'''
测试一:money与spam.money不冲突
测试二:read1与spam.read1不冲突

#test.py

import spam

def read1():

    print('========')

spam.read1()

 

'''

执行结果:

from the spam.py

spam->read1->money 1000

'''
测试二:read1与spam.read1不冲突 
测试三:执行spam.change()操做的全局变量money仍然是spam中的

#test.py

import spam

money=1

spam.change()

print(money)

 

'''

执行结果:

from the spam.py

1

'''
测试三:执行spam.change()操做的全局变量money仍然是spam中的

2.5 为模块名起别名

为已经导入的模块起别名的方式对编写可扩展的代码颇有用

import spam as sm

print(sm.money)

 

有两中sql模块mysql和oracle,根据用户的输入,选择不一样的sql功能

#mysql.py

def sqlparse():

    print('from mysql sqlparse')

#oracle.py

def sqlparse():

    print('from oracle sqlparse')

 

#test.py

db_type=input('>>: ')

if db_type == 'mysql':

    import mysql as db

elif db_type == 'oracle':

    import oracle as db

 

db.sqlparse()
View Code

假设有两个模块xmlreader.py和csvreader.py,它们都定义了函数read_data(filename):用来从文件中读取一些数据,但采用不一样的输入格式。能够编写代码来选择性地挑选读取模块。

if file_format == 'xml':

    import xmlreader as reader

elif file_format == 'csv':

    import csvreader as reader

data=reader.read_date(filename)

 

2.6 在一行导入多个模块

import sys,os,re

第3章 使用模块之from ... import...

3.1 from...import...的使用

from spam import read1,read2

3.2 from...import 与import的对比

#惟一的区别就是:使用from...import...则是将spam中的名字直接导入到当前的名称空间中,因此在当前名称空间中,直接使用名字就能够了、无需加前缀:spam.

 

#from...import...的方式有好处也有坏处

    好处:使用起来方便了

    坏处:容易与当前执行文件中的名字冲突
View Code

3.2.1 验证一:

当前位置直接使用read1和read2就行了,执行时,仍然以spam.py文件全局名称空间

#测试一:导入的函数read1,执行时仍然回到spam.py中寻找全局变量money

#test.py

from spam import read1

money=1000

read1()

'''

执行结果:

from the spam.py

spam->read1->money 1000

'''

 

#测试二:导入的函数read2,执行时须要调用read1(),仍然回到spam.py中找read1()

#test.py

from spam import read2

def read1():

    print('==========')

read2()

 

'''

执行结果:

from the spam.py

spam->read2 calling read

spam->read1->money 1000

'''
View Code

3.2.2 验证二:

若是当前有重名read1或者read2,那么会有覆盖效果。

#测试三:导入的函数read1,被当前位置定义的read1覆盖掉了

#test.py

from spam import read1

def read1():

    print('==========')

read1()

'''

执行结果:

from the spam.py

==========

'''

 
View Code

3.2.3 验证三:

导入的方法在执行时,始终是以源文件为准的

from spam import money,read1

money=100 #将当前位置的名字money绑定到了100

print(money) #打印当前的名字

read1() #读取spam.py中的名字money,仍然为1000

 

'''

from the spam.py

100

spam->read1->money 1000

'''

 
View Code

3.3 也支持as

from spam import read1 as read

3.4 一行导入多个名字

from spam import read1,read2,money

3.5 from...import *

#from spam import * 把spam中全部的不是如下划线(_)开头的名字都导入到当前位置

#大部分状况下咱们的python程序不该该使用这种导入方式,由于*你不知道你导入什么名字,颇有可能会覆盖掉你以前已经定义的名字。并且可读性极其的差,在交互式环境中导入时没有问题。

from spam import * #将模块spam中全部的名字都导入到当前名称空间

print(money)

print(read1)

print(read2)

print(change)

 

'''

执行结果:

from the spam.py

1000

<function read1 at 0x1012e8158>

<function read2 at 0x1012e81e0>

<function change at 0x1012e8268>

'''

 
from spam import *

可使用__all__来控制*(用来发布新版本),在spam.py中新增一行

__all__=['money','read1'] #这样在另一个文件中用from spam import *就这能导入列表中规定的两个名字。

第4章 模块的重载 (了解)

考虑到性能的缘由,每一个模块只被导入一次,放入字典sys.module中,若是你改变了模块的内容,你必须重启程序,python不支持从新加载或卸载以前导入的模块,有的同窗可能会想到直接从sys.module中删除一个模块不就能够卸载了吗,注意了,你删了sys.module中的模块对象仍然可能被其余程序的组件所引用,于是不会被清楚。

特别的对于咱们引用了这个模块中的一个类,用这个类产生了不少对象,于是这些对象都有关于这个模块的引用。

若是只是你想交互测试的一个模块,使用 importlib.reload(), e.g. import importlib; importlib.reload(modulename),这只能用于测试环境。

 

aa.py的初始内容

def func1():

    print('func1')
执行test.py

import time,importlib

import aa

 

time.sleep(20)

# importlib.reload(aa)

aa.func1()
执行test.py

在20秒的等待时间里,修改aa.py中func1的内容,等待test.py的结果。

打开importlib注释,从新测试

第5章 py文件区分两种用途:模块与脚本

5.1 当作脚本执行:__name__ == '__main__'

5.2 当作模块被导入使用:__name__ == '模块名'

if __name__ == '__main__':

pass 

 

#编写好的一个python文件能够有两种用途:

    一:脚本,一个文件就是整个程序,用来被执行

    二:模块,文件中存放着一堆功能,用来被导入使用

 

 

#python为咱们内置了全局变量__name__,

    当文件被当作脚本执行时:__name__ 等于'__main__'

    当文件被当作模块导入时:__name__等于模块名

 

#做用:用来控制.py文件在不一样的应用场景下执行不一样的逻辑

    if __name__ == '__main__':
介绍
#fib.py

 

def fib(n):    # write Fibonacci series up to n

    a, b = 0, 1

    while b < n:

        print(b, end=' ')

        a, b = b, a+b

    print()

 

def fib2(n):   # return Fibonacci series up to n

    result = []

    a, b = 0, 1

    while b < n:

        result.append(b)

        a, b = b, a+b

    return result

 

if __name__ == "__main__":

    import sys

    fib(int(sys.argv[1]))

 

 

#执行:python fib.py <arguments>

python fib.py 50 #在命令行

 
fib.py

第6章 模块搜索路径

6.1 简单说明

模块的查找顺序是:内存中已经加载的模块->内置模块->sys.path路径中包含的模块

 

6.2 详细的说明

#模块的查找顺序

1、在第一次导入某个模块时(好比spam),会先检查该模块是否已经被加载到内存中(当前执行文件的名称空间对应的内存),若是有则直接引用

    ps:python解释器在启动时会自动加载一些模块到内存中,可使用sys.modules查看

2、若是没有,解释器则会查找同名的内建模块

3、若是尚未找到就从sys.path给出的目录列表中依次寻找spam.py文件。

 

 

#sys.path的初始化的值来自于:

The directory containing the input script (or the current directory when no file is specified).

PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).

The installation-dependent default.

 

#须要特别注意的是:咱们自定义的模块名不该该与系统内置模块重名。虽然每次都说,可是仍然会有人不停的犯错。

 

#在初始化后,python程序能够修改sys.path,路径放到前面的优先于标准库被加载。

1 >>> import sys

2 >>> sys.path.append('/a/b/c/d')

3 >>> sys.path.insert(0,'/x/y/z') #排在前的目录,优先被搜索

注意:搜索时按照sys.path中从左到右的顺序查找,位于前的优先被查找,sys.path中还可能包含.zip归档文件和.egg文件,python会把.zip归档文件当成一个目录去处理,

 

#首先制做归档文件:zip module.zip foo.py bar.py

import sys

sys.path.append('module.zip')

import foo,bar

 

#也可使用zip中目录结构的具体位置

sys.path.append('module.zip/lib/python')

 

 

#windows下的路径不加r开头,会语法错误

sys.path.insert(0,r'C:\Users\Administrator\PycharmProjects\a')

 

 

#至于.egg文件是由setuptools建立的包,这是按照第三方python库和扩展时使用的一种常见格式,.egg文件实际上只是添加了额外元数据(如版本号,依赖项等)的.zip文件。

 

#须要强调的一点是:只能从.zip文件中导入.py,.pyc等文件。使用C编写的共享库和扩展块没法直接从.zip文件中加载(此时setuptools等打包系统有时能提供一种规避方法),且从.zip中加载文件不会建立.pyc或者.pyo文件,所以必定要事先建立他们,来避免加载模块是性能降低。
详细的介绍

6.3 官网解释:

#官网连接:https://docs.python.org/3/tutorial/modules.html#the-module-search-path

搜索路径:

当一个命名为spam的模块被导入时

    解释器首先会从内建模块中寻找该名字

    找不到,则去sys.path中找该名字

 

sys.path从如下位置初始化

    1 执行文件所在的当前目录

    2 PTYHONPATH(包含一系列目录名,与shell变量PATH语法同样)

    3 依赖安装时默认指定的

 

注意:在支持软链接的文件系统中,执行脚本所在的目录是在软链接以后被计算的,换句话说,包含软链接的目录不会被添加到模块的搜索路径中

 

在初始化后,咱们也能够在python程序中修改sys.path,执行文件所在的路径默认是sys.path的第一个目录,在全部标准库路径的前面。这意味着,当前目录是优先于标准库目录的,须要强调的是:咱们自定义的模块名不要跟python标准库的模块名重复,除非你是故意的,傻叉。

 

 
官网解释

第7章 编译python文件(了解)

7.1 简单的解释

为了提升加载模块的速度,强调强调强调:提升的是加载速度而绝非运行速度。python解释器会在__pycache__目录中下缓存每一个模块编译后的版本,格式为:module.version.pyc。一般会包含python的版本号。例如,在CPython3.3版本下,spam.py模块会被缓存成__pycache__/spam.cpython-33.pyc。这种命名规范保证了编译后的结果多版本共存。

 

Python检查源文件的修改时间与编译的版本进行对比,若是过时就须要从新编译。这是彻底自动的过程。而且编译的模块是平台独立的,因此相同的库能够在不一样的架构的系统之间共享,即pyc使一种跨平台的字节码,相似于JAVA火.NET,是由python虚拟机来执行的,可是pyc的内容跟python的版本相关,不一样的版本编译后的pyc文件不一样,2.5编译的pyc文件不能到3.5上执行,而且pyc文件是能够反编译的,于是它的出现仅仅是用来提高模块的加载速度的,不是用来加密的。

7.2 详细的解释

#python解释器在如下两种状况下不检测缓存

#1 若是是在命令行中被直接导入模块,则按照这种方式,每次导入都会从新编译,而且不会存储编译后的结果(python3.3之前的版本应该是这样)

    python -m spam.py

 

#2 若是源文件不存在,那么缓存的结果也不会被使用,若是想在没有源文件的状况下来使用编译后的结果,则编译后的结果必须在源目录下

sh-3.2# ls

__pycache__ spam.py

sh-3.2# rm -rf spam.py

sh-3.2# mv __pycache__/spam.cpython-36.pyc ./spam.pyc

sh-3.2# python3 spam.pyc

spam

 

 

#提示:

1.模块名区分大小写,foo.py与FOO.py表明的是两个模块

2.你可使用-O或者-OO转换python命令来减小编译模块的大小

    -O转换会帮你去掉assert语句

    -OO转换会帮你去掉assert语句和__doc__文档字符串

    因为一些程序可能依赖于assert语句或文档字符串,你应该在在确认须要

    的状况下使用这些选项。

3.在速度上从.pyc文件中读指令来执行不会比从.py文件中读指令执行更快,只有在模块被加载时,.pyc文件才是更快的

 

4.只有使用import语句是才将文件自动编译为.pyc文件,在命令行或标准输入中指定运行脚本则不会生成这类文件,于是咱们可使用compieall模块为一个目录中的全部模块建立.pyc文件

 

模块能够做为一个脚本(使用python -m compileall)编译Python源 

python -m compileall /module_directory 递归着编译

若是使用python -O -m compileall /module_directory -l则只一层

 

命令行里使用compile()函数时,自动使用python -O -m compileall

 

详见:https://docs.python.org/3/library/compileall.html#module-compileall

 

 
详细的解释

 

第8章 包介绍

8.1 什么是包?

#官网解释

Packages are a way of structuring Python’s module namespace by using “dotted module names”

包是一种经过使用‘.模块名’来组织python模块名称空间的方式。

#具体的:包就是一个包含有__init__.py文件的文件夹,因此其实咱们建立包的目的就是为了用文件夹将文件/模块组织起来

#须要强调的是:

  1. 在python3中,即便包下没有__init__.py文件,import 包仍然不会报错,而在python2中,包下必定要有该文件,不然import 包报错

  2. 建立包的目的不是为了运行,而是被导入使用,记住,包只是模块的一种形式而已,包的本质就是一种模块
官网解释

8.2 为什么要使用包

包的本质就是一个文件夹,那么文件夹惟一的功能就是将文件组织起来

随着功能越写越多,咱们没法将因此功能都放到一个文件中,因而咱们使用模块去组织功能,而随着模块愈来愈多,咱们就须要用文件夹将模块文件组织起来,以此来提升程序的结构性和可维护性。

 

8.3 注意事项

#1.关于包相关的导入语句也分为import和from ... import ...两种,可是不管哪一种,不管在什么位置,在导入时都必须遵循一个原则:凡是在导入时带点的,点的左边都必须是一个包,不然非法。能够带有一连串的点,如item.subitem.subsubitem,但都必须遵循这个原则。但对于导入后,在使用时就没有这种限制了,点的左边能够是包,模块,函数,类(它们均可以用点的方式调用本身的属性)。

#二、import导入文件时,产生名称空间中的名字来源于文件,import 包,产生的名称空间的名字一样来源于文件,即包下的__init__.py,导入包本质就是在导入该文件

#三、包A和包B下有同名模块也不会冲突,如A.a与B.a来自俩个命名空间
注意事项

8.4 上课流程

1 实验一

    准备:

        执行文件为test.py,内容

        #test.py

        import aaa

        同级目录下建立目录aaa,而后自建空__init__.py(或者干脆建包)

 

    需求:验证导入包就是在导入包下的__init__.py

 

    解决:

        先执行看结果

        再在__init__.py添加打印信息后,从新执行

 

2、实验二

    准备:基于上面的结果

 

    需求:

        aaa.x

        aaa.y

    解决:在__init__.py中定义名字x和y

 

3、实验三

    准备:在aaa下创建m1.py和m2.py

        #m1.py

        def f1():

            print('from 1')

        #m2.py

        def f2():

            print('from 2')

    需求:

        aaa.m1 #进而aaa.m1.func1()

        aaa.m2 #进而aaa.m2.func2()

 

    解决:在__init__.py中定义名字m1和m2,先定义一个普通变量,再引出如何导入模块名,强调:环境变量是以执行文件为准

   

 

4、实验四

    准备:在aaa下新建包bbb

 

    需求:

        aaa.bbb

 

    解决:在aaa的__init__.py内导入名字bbb

 

5、实验五

    准备:

        在bbb下创建模块m3.py

        #m3.py

        def f3():

            print('from 3')

    需求:

        aaa.bbb.m3 #进而aaa.bbb.m3.f3()

 

    解决:是bbb下的名字m3,于是要在bbb的__init__.py文件中导入名字m3,from aaa.bbb import m3

 

6、实验六

    准备:基于上面的结果

 

    需求:

        aaa.m1()

        aaa.m2()

        aaa.m3()

        进而实现

        aaa.f1()

        aaa.f2()

        aaa.f3()

        先用绝对导入,再用相对导入

       

    解决:在aaa的__init__.py中拿到名字m一、m二、m3

    包内模块直接的相对导入,强调包的本质:包内的模块是用来被导入的,而不是被执行的

    用户没法区分模块是文件仍是一个包,咱们定义包是为了方便开发者维护

 

7、实验七

    将包整理当作一个模块,移动到别的目录下,操做sys.path
View Code

第9章 包的使用

9.1 示范文件

glance/                   #Top-level package

 

├── __init__.py      #Initialize the glance package

 

├── api                  #Subpackage for api

 

│   ├── __init__.py

 

│   ├── policy.py

 

│   └── versions.py

 

├── cmd                #Subpackage for cmd

 

│   ├── __init__.py

 

│   └── manage.py

 

└── db                  #Subpackage for db

 

    ├── __init__.py

 

    └── models.py
包的示范文件结构
#包所包含的文件内容

 

#policy.py

def get():

    print('from policy.py')

 

#versions.py

def create_resource(conf):

    print('from version.py: ',conf)

 

#manage.py

def main():

    print('from manage.py')

 

#models.py

def register_models(engine):

    print('from models.py: ',engine)
文件内容

执行文件与示范文件在同级目录下

 

9.2 包的使用之import

import glance.db.models

glance.db.models.register_models('mysql')

单独导入包名称时不会导入包中全部包含的全部子模块,如

 

#在与glance同级的test.py中

import glance

glance.cmd.manage.main()

 

'''

执行结果:

AttributeError: module 'glance' has no attribute 'cmd'

'''

解决方法:

#glance/__init__.py

from . import cmd

 

#glance/cmd/__init__.py

from . import manage

执行:

#在于glance同级的test.py中

import glance

glance.cmd.manage.main()

9.3 包的使用之from ... import ...

须要注意的是fromimport导入的模块,必须是明确的一个不能带点,不然会有语法错误,如:from a import b.c是错误语法。

from glance.db import models

models.register_models('mysql')

 

from glance.db.models import register_models

register_models('mysql')
View Code

9.4 from glance.api import *

在讲模块时,咱们已经讨论过了从一个模块内导入全部*,此处咱们研究从一个包导入全部*。

此处是想从包api中导入全部,实际上该语句只会导入包api下__init__.py文件中定义的名字,咱们能够在这个文件中定义__all___:

#在__init__.py中定义

x=10

 

def func():

    print('from api.__init.py')

 

__all__=['x','func','policy']
在__init__.py中定义

此时咱们在于glance同级的文件中执行from glance.api import *就导入__all__中的内容(versions仍然不能导入)。

练习:

#执行文件中的使用效果以下,请处理好包的导入

from glance import *

 

get()

create_resource('a.conf')

main()

register_models('mysql')

 

 

#在glance.__init__.py中

from .api.policy import get

from .api.versions import create_resource

 

from .cmd.manage import main

from .db.models import  register_models

 

__all__=['get','create_resource','main','register_models']
执行文件中的使用效果以下,请处理好包的导入

9.5 绝对导入和相对导入

咱们的最顶级包glance是写给别人用的,而后在glance包内部也会有彼此之间互相导入的需求,这时候就有绝对导入和相对导入两种方式:

绝对导入:以glance做为起始

相对导入:用.或者..的方式最为起始(只能在一个包中使用,不能用于不一样目录内)

例如:咱们在glance/api/version.py中想要导入glance/cmd/manage.py

在glance/api/version.py

 

#绝对导入

from glance.cmd import manage

manage.main()

 

#相对导入

from ..cmd import manage

manage.main()

 

测试结果:注意必定要在于glance同级的文件中测试

from glance.api import versions
View Code

9.6 包以及包所包含的模块都是用来被导入的,而不是被直接执行的。而环境变量都是以执行文件为准的

好比咱们想在glance/api/versions.py中导入glance/api/policy.py,有的同窗一抽这俩模块是在同一个目录下,十分开心的就去作了,它直接这么作

#在version.py中

 

import policy

policy.get()

没错,咱们单独运行version.py是一点问题没有的,运行version.py的路径搜索就是从当前路径开始的,因而在导入policy时能在当前目录下找到

 可是你想啊,你子包中的模块version.py极有多是被一个glance包同一级别的其余文件导入,好比咱们在于glance同级下的一个test.py文件中导入version.py,以下

from glance.api import versions

 

 '''

 执行结果:

 ImportError: No module named 'policy'

 '''

 

 '''

 分析:

 此时咱们导入versions在versions.py中执行

 import policy须要找从sys.path也就是从当前目录找policy.py,

 这必然是找不到的

 '''

 
View Code

9.7 包的分发(了解)

https://packaging.python.org/distributing/

 

第10章 软件开发目录规范

10.1 实例一

 

 

#===============>star.py

import sys,os

BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

sys.path.append(BASE_DIR)

 

from core import src

 

if __name__ == '__main__':

    src.run()

#===============>settings.py

import os

 

BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DB_PATH=os.path.join(BASE_DIR,'db','db.json')

LOG_PATH=os.path.join(BASE_DIR,'log','access.log')

LOGIN_TIMEOUT=5

 

"""

logging配置

"""

# 定义三种日志输出格式

standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \

                  '[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字

simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'

id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'

 

# log配置字典

LOGGING_DIC = {

    'version': 1,

    'disable_existing_loggers': False,

    'formatters': {

        'standard': {

            'format': standard_format

        },

        'simple': {

            'format': simple_format

        },

    },

    'filters': {},

    'handlers': {

        #打印到终端的日志

        'console': {

            'level': 'DEBUG',

            'class': 'logging.StreamHandler',  # 打印到屏幕

            'formatter': 'simple'

        },

        #打印到文件的日志,收集info及以上的日志

        'default': {

            'level': 'DEBUG',

            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件

            'formatter': 'standard',

            'filename': LOG_PATH,  # 日志文件

            'maxBytes': 1024*1024*5,  # 日志大小 5M

            'backupCount': 5,

            'encoding': 'utf-8',  # 日志文件的编码,不再用担忧中文log乱码了

        },

    },

    'loggers': {

        #logging.getLogger(__name__)拿到的logger配置

        '': {

            'handlers': ['default', 'console'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕

            'level': 'DEBUG',

            'propagate': True,  # 向上(更高level的logger)传递

        },

    },

}

 

 

#===============>src.py

from conf import settings

from lib import common

import time

 

logger=common.get_logger(__name__)

 

current_user={'user':None,'login_time':None,'timeout':int(settings.LOGIN_TIMEOUT)}

def auth(func):

    def wrapper(*args,**kwargs):

        if current_user['user']:

            interval=time.time()-current_user['login_time']

            if interval < current_user['timeout']:

                return func(*args,**kwargs)

        name = input('name>>: ')

        password = input('password>>: ')

        db=common.conn_db()

        if db.get(name):

            if password == db.get(name).get('password'):

                logger.info('登陆成功')

                current_user['user']=name

                current_user['login_time']=time.time()

                return func(*args,**kwargs)

        else:

            logger.error('用户名不存在')

 

    return wrapper

 

@auth

def buy():

    print('buy...')

 

@auth

def run():

 

    print('''

    1 购物

    2 查看余额

    3 转帐

    ''')

    while True:

        choice = input('>>: ').strip()

        if not choice:continue

        if choice == '1':

            buy()

 

 

 

#===============>db.json

{"egon": {"password": "123", "money": 3000}, "alex": {"password": "alex3714", "money": 30000}, "wsb": {"password": "3714", "money": 20000}}

 

#===============>common.py

from conf import settings

import logging

import logging.config

import json

 

def get_logger(name):

    logging.config.dictConfig(settings.LOGGING_DIC)  # 导入上面定义的logging配置

    logger = logging.getLogger(name)  # 生成一个log实例

    return logger

 

 

def conn_db():

    db_path=settings.DB_PATH

    dic=json.load(open(db_path,'r',encoding='utf-8'))

    return dic

 

 

#===============>access.log

[2017-10-21 19:08:20,285][MainThread:10900][task_id:core.src][src.py:19][INFO][登陆成功]

[2017-10-21 19:08:32,206][MainThread:10900][task_id:core.src][src.py:19][INFO][登陆成功]

[2017-10-21 19:08:37,166][MainThread:10900][task_id:core.src][src.py:24][ERROR][用户名不存在]

[2017-10-21 19:08:39,535][MainThread:10900][task_id:core.src][src.py:24][ERROR][用户名不存在]

[2017-10-21 19:08:40,797][MainThread:10900][task_id:core.src][src.py:24][ERROR][用户名不存在]

[2017-10-21 19:08:47,093][MainThread:10900][task_id:core.src][src.py:24][ERROR][用户名不存在]

[2017-10-21 19:09:01,997][MainThread:10900][task_id:core.src][src.py:19][INFO][登陆成功]

[2017-10-21 19:09:05,781][MainThread:10900][task_id:core.src][src.py:24][ERROR][用户名不存在]

[2017-10-21 19:09:29,878][MainThread:8812][task_id:core.src][src.py:19][INFO][登陆成功]

[2017-10-21 19:09:54,117][MainThread:9884][task_id:core.src][src.py:19][INFO][登陆成功]

 
实例一代码

10.2 实例二

 

####bin目录为ATM执行文件目录,start.py文件为ATM执行程序文件,文件内容以下:
import sys,os

BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

from core import src

if __name__ == '__main__':
src.run()


######conf目录为ATM配置目录,settings.py文件为ATM配置文件,文件内容以下:
import os
import logging.config

BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
LOG_PATH=os.path.join(BASE_DIR,'log','access.log')
COLLECT_PATH=os.path.join(BASE_DIR,'log','collect.log')
DB_PATH=os.path.join(BASE_DIR,'db','user')


# 定义三种日志输出格式 开始
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                  '[%(levelname)s][%(message)s]'

simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'

id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'

# log配置字典
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
        'id_simple' : {
            'format' : id_simple_format
        },
    },
    'filters': {},
    'handlers': {
        #打印到终端的日志
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'simple'
        },
        #打印到文件的日志,收集info及以上的日志
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'formatter': 'standard',
            'filename': LOG_PATH,  # 日志文件
            'maxBytes': 1024*1024*5,  # 日志大小 5M
            'backupCount': 5,
            'encoding': 'utf-8',  # 日志文件的编码,不再用担忧中文log乱码了
        },
        'collect': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'formatter': 'simple',
            'filename': COLLECT_PATH,  # 日志文件
            'maxBytes': 1024*1024*5,  # 日志大小 5M
            'backupCount': 5,
            'encoding': 'utf-8',  # 日志文件的编码,不再用担忧中文log乱码了
        },
    },
    'loggers': {
        '': {
            'handlers': ['default', 'console','collect'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'level': 'DEBUG',
            'propagate': False,  # 向上(更高level的logger)传递
        },
    },
}

###########core目录为ATM主要核心逻辑程序目录,src.py文件为主逻辑程序,文件内容以下:
from lib import common
from lib import sql

def shop():
    print('购物......')

def check_balance():
    print('查看余额......')
    res=sql.execute('select balance from user where id=3')
    print(res)

def transfer_accounts():
    print('转帐......')
    #记录日志
    log_msg='egon给alex转了1毛钱'
    # 调用日志功能记录日志
    # common.logger(log_msg)
    logger=common.logger_handle('转帐')
    logger.debug(log_msg)

def run():
    msg='''
    1 购物
    2 查看余额
    3 转帐
    '''
    while True:
        print(msg)
        choice=input('>>: ').strip()
        if not choice:continue
        if choice == '1':
            shop()
        elif choice == '2':
            check_balance()
        elif choice == '3':
            transfer_accounts()

#######db目录为用户数据存储目录,user文件为一个普通用户帐户文件,内容以下:
alex,18,male,100000
egon,18,male,100000

#########lib目录为其余人的或本身的模块和包存放的位置,common.py内容以下:
from conf import settings
import logging.config

# def logger(msg):
#     with open(settings.LOG_PATH,'a',encoding='utf-8') as f:
#         f.write('%s\n' %msg)

def logger_handle(log_name):
    logging.config.dictConfig(settings.LOGGING_DIC)  # 导入上面定义的logging配置
    logger = logging.getLogger(log_name)  # 生成一个log实例
    return logger

#############lib目录下sql.py内容以下:
def execute(sql):
    print('解析')
    print('执行sql')
#################log目录为日志存放目录,access.log内容以下:
egon给alex转了1毛钱
[2018-01-06 16:36:52,892][MainThread:5204][task_id:转帐][src.py:19][DEBUG][egon给alex转了1毛钱]

#################log目录下collect.log内容以下:
[DEBUG][2018-01-06 16:36:52,892][src.py:19]egon给alex转了1毛钱

################Readme文件为介绍软件功能及使用方法,内容以下:(目前为空)
实例二

第11章 经常使用模块

11.1 日志模块logging

11.1.1 日志级别

CRITICAL = 50 #FATAL = CRITICAL

ERROR = 40

WARNING = 30 #WARN = WARNING

INFO = 20

DEBUG = 10

NOTSET = 0 #不设置

11.1.2 默认级别为warning,默认打印到终端

import logging

 

logging.debug('调试debug')

logging.info('消息info')

logging.warning('警告warn')

logging.error('错误error')

logging.critical('严重critical')

 

'''

WARNING:root:警告warn

ERROR:root:错误error

CRITICAL:root:严重critical

'''

 
View Code

11.1.3 为logging模块指定全局配置,针对全部logger有效,控制打印到文件中

logging.basicConfig()

 

可在logging.basicConfig()函数中经过具体参数来更改logging模块默认行为,可用参数有

filename:用指定的文件名建立FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。

filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。

format:指定handler使用的日志显示格式。

datefmt:指定日期时间格式。

level:设置rootlogger(后边会讲解具体概念)的日志级别

stream:用指定的stream建立StreamHandler。能够指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。

 

 

 

#格式

%(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:用户输出的消息

 
logging.basicConfig()
#======介绍

可在logging.basicConfig()函数中可经过具体参数来更改logging模块默认行为,可用参数有

filename:用指定的文件名建立FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。

filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。

format:指定handler使用的日志显示格式。

datefmt:指定日期时间格式。

level:设置rootlogger(后边会讲解具体概念)的日志级别

stream:用指定的stream建立StreamHandler。能够指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。

 

 

format参数中可能用到的格式化串:

%(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用户输出的消息

 

 

 

 

#========使用

import logging

logging.basicConfig(filename='access.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('警告warn')

logging.error('错误error')

logging.critical('严重critical')

 

 

 

 

 

#========结果

access.log内容:

2017-07-28 20:32:17 PM - root - DEBUG -test:  调试debug

2017-07-28 20:32:17 PM - root - INFO -test:  消息info

2017-07-28 20:32:17 PM - root - WARNING -test:  警告warn

2017-07-28 20:32:17 PM - root - ERROR -test:  错误error

2017-07-28 20:32:17 PM - root - CRITICAL -test:  严重critical

 

part2: 能够为logging模块指定模块级的配置,即全部logger的配置
logging模块介绍

11.1.4 logging模块的Formatter,Handler,Logger,Filter对象

原理图:https://pan.baidu.com/s/1skWyTT7

#logger:产生日志的对象
#Filter:过滤日志的对象
#Handler:接收日志而后控制打印到不一样的地方,FileHandler用来打印到文件中,StreamHandler用来打印到终端
#Formatter对象:能够定制不一样的日志格式对象,而后绑定给不一样的Handler对象使用,以此来控制不一样的Handler的日志格式
'''

critical=50

error =40

warning =30

info = 20

debug =10

'''

 

 

import logging

 

#一、logger对象:负责产生日志,而后交给Filter过滤,而后交给不一样的Handler输出

logger=logging.getLogger(__file__)

 

#二、Filter对象:不经常使用,略

 

#三、Handler对象:接收logger传来的日志,而后控制输出

h1=logging.FileHandler('t1.log') #打印到文件

h2=logging.FileHandler('t2.log') #打印到文件

h3=logging.StreamHandler() #打印到终端

 

#四、Formatter对象:日志格式

formmater1=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',

                    datefmt='%Y-%m-%d %H:%M:%S %p',)

 

formmater2=logging.Formatter('%(asctime)s :  %(message)s',

                    datefmt='%Y-%m-%d %H:%M:%S %p',)

 

formmater3=logging.Formatter('%(name)s %(message)s',)

 

 

#五、为Handler对象绑定格式

h1.setFormatter(formmater1)

h2.setFormatter(formmater2)

h3.setFormatter(formmater3)

 

#六、将Handler添加给logger并设置日志级别

logger.addHandler(h1)

logger.addHandler(h2)

logger.addHandler(h3)

logger.setLevel(10)

 

#七、测试

logger.debug('debug')

logger.info('info')

logger.warning('warning')

logger.error('error')

logger.critical('critical')
实例

11.1.5 Logger与Handler的级别

logger是第一级过滤,而后才能到handler,咱们能够给logger和handler同时设置level,可是须要注意的是

 

###重要,重要,重要!!!

Logger is also the first to filter the message based on a level — if you set the logger to INFO, and all handlers to DEBUG, you still won't receive DEBUG messages on handlers — they'll be rejected by the logger itself. If you set logger to DEBUG, but all handlers to INFO, you won't receive any DEBUG messages either — because while the logger says "ok, process this", the handlers reject it (DEBUG < INFO).

 

 

 

#验证

import logging

 

 

form=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',

                    datefmt='%Y-%m-%d %H:%M:%S %p',)

 

ch=logging.StreamHandler()

 

ch.setFormatter(form)

# ch.setLevel(10)

ch.setLevel(20)

 

l1=logging.getLogger('root')

# l1.setLevel(20)

l1.setLevel(10)

l1.addHandler(ch)

 

l1.debug('l1 debug')
View Code

11.1.6 Logger的继承(了解)

import logging

 

formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',

                    datefmt='%Y-%m-%d %H:%M:%S %p',)

 

ch=logging.StreamHandler()

ch.setFormatter(formatter)

 

 

logger1=logging.getLogger('root')

logger2=logging.getLogger('root.child1')

logger3=logging.getLogger('root.child1.child2')

 

 

logger1.addHandler(ch)

logger2.addHandler(ch)

logger3.addHandler(ch)

logger1.setLevel(10)

logger2.setLevel(10)

logger3.setLevel(10)

 

logger1.debug('log1 debug')

logger2.debug('log2 debug')

logger3.debug('log3 debug')

'''

2017-07-28 22:22:05 PM - root - DEBUG -test:  log1 debug

2017-07-28 22:22:05 PM - root.child1 - DEBUG -test:  log2 debug

2017-07-28 22:22:05 PM - root.child1 - DEBUG -test:  log2 debug

2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test:  log3 debug

2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test:  log3 debug

2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test:  log3 debug

'''

 

 
View Code

11.1.7 应用

##### logging配置文件

"""

logging配置

"""

 

import os

import logging.config

 

# 定义三种日志输出格式 开始

 

standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \

                  '[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字

 

simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'

 

id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'

 

# 定义日志输出格式 结束

 

logfile_dir = os.path.dirname(os.path.abspath(__file__))  # log文件的目录

 

logfile_name = 'all2.log'  # log文件名

 

# 若是不存在定义的日志目录就建立一个

if not os.path.isdir(logfile_dir):

    os.mkdir(logfile_dir)

 

# log文件的全路径

logfile_path = os.path.join(logfile_dir, logfile_name)

 

# log配置字典

LOGGING_DIC = {

    'version': 1,

    'disable_existing_loggers': False,

    'formatters': {

        'standard': {

            'format': standard_format

        },

        'simple': {

            'format': simple_format

        },

    },

    'filters': {},

    'handlers': {

        #打印到终端的日志

        'console': {

            'level': 'DEBUG',

            'class': 'logging.StreamHandler',  # 打印到屏幕

            'formatter': 'simple'

        },

        #打印到文件的日志,收集info及以上的日志

        'default': {

            'level': 'DEBUG',

            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件

            'formatter': 'standard',

            'filename': logfile_path,  # 日志文件

            'maxBytes': 1024*1024*5,  # 日志大小 5M

            'backupCount': 5,

            'encoding': 'utf-8',  # 日志文件的编码,不再用担忧中文log乱码了

        },

    },

    'loggers': {

        #logging.getLogger(__name__)拿到的logger配置

        '': {

            'handlers': ['default', 'console'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕

            'level': 'DEBUG',

            'propagate': True,  # 向上(更高level的logger)传递

        },

    },

}

 

 

def load_my_logging_cfg():

    logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置

    logger = logging.getLogger(__name__)  # 生成一个log实例

    logger.info('It works!')  # 记录该文件的运行状态

 

if __name__ == '__main__':

    load_my_logging_cfg()

 
logging配置文件
#######使用

"""

MyLogging Test

"""

 

import time

import logging

import my_logging  # 导入自定义的logging配置

 

logger = logging.getLogger(__name__)  # 生成logger实例

 

 

def demo():

    logger.debug("start range... time:{}".format(time.time()))

    logger.info("中文测试开始。。。")

    for i in range(10):

        logger.debug("i:{}".format(i))

        time.sleep(0.2)

    else:

        logger.debug("over range... time:{}".format(time.time()))

    logger.info("中文测试结束。。。")

 

if __name__ == "__main__":

    my_logging.load_my_logging_cfg()  # 在你程序文件的入口加载自定义logging配置

    demo()

 
使用
###### !!!关于如何拿到logger对象的详细解释!!!

注意注意注意:

 

 

#一、有了上述方式咱们的好处是:全部与logging模块有关的配置都写到字典中就能够了,更加清晰,方便管理

 

 

#二、咱们须要解决的问题是:

    1、从字典加载配置:logging.config.dictConfig(settings.LOGGING_DIC)

 

    2、拿到logger对象来产生日志

    logger对象都是配置到字典的loggers 键对应的子字典中的

    按照咱们对logging模块的理解,要想获取某个东西都是经过名字,也就是key来获取的

    因而咱们要获取不一样的logger对象就是

    logger=logging.getLogger('loggers子字典的key名')

 

   

    但问题是:若是咱们想要不一样logger名的logger对象都共用一段配置,那么确定不能在loggers子字典中定义n个key  

 'loggers': {   

        'l1': {

            'handlers': ['default', 'console'],  #

            'level': 'DEBUG',

            'propagate': True,  # 向上(更高level的logger)传递

        },

        'l2: {

            'handlers': ['default', 'console' ],

            'level': 'DEBUG',

            'propagate': False,  # 向上(更高level的logger)传递

        },

        'l3': {

            'handlers': ['default', 'console'],  #

            'level': 'DEBUG',

            'propagate': True,  # 向上(更高level的logger)传递

        },

 

}

 

   

#咱们的解决方式是,定义一个空的key

    'loggers': {

        '': {

            'handlers': ['default', 'console'],

            'level': 'DEBUG',

            'propagate': True,

        },

 

}

 

这样咱们再取logger对象时

logging.getLogger(__name__),不一样的文件__name__不一样,这保证了打印日志时标识信息不一样,可是拿着该名字去loggers里找key名时却发现找不到,因而默认使用key=''的配置

 
关于如何拿到logger对象的详细解释!!!

另一个django的配置,瞄一眼就能够,跟上面的同样

#logging_config.py

LOGGING = {

    'version': 1,

    'disable_existing_loggers': False,

    'formatters': {

        'standard': {

            'format': '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]'

                      '[%(levelname)s][%(message)s]'

        },

        'simple': {

            'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'

        },

        'collect': {

            'format': '%(message)s'

        }

    },

    'filters': {

        'require_debug_true': {

            '()': 'django.utils.log.RequireDebugTrue',

        },

    },

    'handlers': {

        #打印到终端的日志

        'console': {

            'level': 'DEBUG',

            'filters': ['require_debug_true'],

            'class': 'logging.StreamHandler',

            'formatter': 'simple'

        },

        #打印到文件的日志,收集info及以上的日志

        'default': {

            'level': 'INFO',

            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,自动切

            'filename': os.path.join(BASE_LOG_DIR, "xxx_info.log"),  # 日志文件

            'maxBytes': 1024 * 1024 * 5,  # 日志大小 5M

            'backupCount': 3,

            'formatter': 'standard',

            'encoding': 'utf-8',

        },

        #打印到文件的日志:收集错误及以上的日志

        'error': {

            'level': 'ERROR',

            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,自动切

            'filename': os.path.join(BASE_LOG_DIR, "xxx_err.log"),  # 日志文件

            'maxBytes': 1024 * 1024 * 5,  # 日志大小 5M

            'backupCount': 5,

            'formatter': 'standard',

            'encoding': 'utf-8',

        },

        #打印到文件的日志

        'collect': {

            'level': 'INFO',

            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,自动切

            'filename': os.path.join(BASE_LOG_DIR, "xxx_collect.log"),

            'maxBytes': 1024 * 1024 * 5,  # 日志大小 5M

            'backupCount': 5,

            'formatter': 'collect',

            'encoding': "utf-8"

        }

    },

    'loggers': {

        #logging.getLogger(__name__)拿到的logger配置

        '': {

            'handlers': ['default', 'console', 'error'],

            'level': 'DEBUG',

            'propagate': True,

        },

        #logging.getLogger('collect')拿到的logger配置

        'collect': {

            'handlers': ['console', 'collect'],

            'level': 'INFO',

        }

    },

}

 

 

# -----------

# 用法:拿到俩个logger

 

logger = logging.getLogger(__name__) #线上正常的日志

collect_logger = logging.getLogger("collect") #领导说,须要为领导们单独定制领导们看的日志

 

 
logging_config.py

11.2 正则模块re

11.2.1 什么是正则?

 正则就是用一些具备特殊含义的符号组合到一块儿(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在Python中)它内嵌在Python中,并经过 re 模块实现。正则表达式模式被编译成一系列的字节码,而后由用 C 编写的匹配引擎执行。

生活中到处都是正则:

    好比咱们描述:4条腿

      你可能会想到的是四条腿的动物或者桌子,椅子等

    继续描述:4条腿,活的

          就只剩下四条腿的动物这一类了

 

11.2.2 经常使用匹配模式(元字符)

http://blog.csdn.net/yufenghyc/article/details/51078107

 

 

 

11.2.3 匹配模式

# =================================匹配模式=================================

#一对一的匹配

# 'hello'.replace(old,new)

# 'hello'.find('pattern')

 

#正则匹配

import re

#\w与\W

print(re.findall('\w','hello egon 123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']

print(re.findall('\W','hello egon 123')) #[' ', ' ']

 

#\s与\S

print(re.findall('\s','hello  egon  123')) #[' ', ' ', ' ', ' ']

print(re.findall('\S','hello  egon  123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']

 

#\n \t都是空,均可以被\s匹配

print(re.findall('\s','hello \n egon \t 123')) #[' ', '\n', ' ', ' ', '\t', ' ']

 

#\n与\t

print(re.findall(r'\n','hello egon \n123')) #['\n']

print(re.findall(r'\t','hello egon\t123')) #['\n']

 

#\d与\D

print(re.findall('\d','hello egon 123')) #['1', '2', '3']

print(re.findall('\D','hello egon 123')) #['h', 'e', 'l', 'l', 'o', ' ', 'e', 'g', 'o', 'n', ' ']

 

#\A与\Z

print(re.findall('\Ahe','hello egon 123')) #['he'],\A==>^

print(re.findall('123\Z','hello egon 123')) #['he'],\Z==>$

 

#^与$

print(re.findall('^h','hello egon 123')) #['h']

print(re.findall('3$','hello egon 123')) #['3']

 

# 重复匹配:| . | * | ? | .* | .*? | + | {n,m} |

#.

print(re.findall('a.b','a1b')) #['a1b']

print(re.findall('a.b','a1b a*b a b aaab')) #['a1b', 'a*b', 'a b', 'aab']

print(re.findall('a.b','a\nb')) #[]

print(re.findall('a.b','a\nb',re.S)) #['a\nb']

print(re.findall('a.b','a\nb',re.DOTALL)) #['a\nb']同上一条意思同样

 

#*

print(re.findall('ab*','bbbbbbb')) #[]

print(re.findall('ab*','a')) #['a']

print(re.findall('ab*','abbbb')) #['abbbb']

 

#?

print(re.findall('ab?','a')) #['a']

print(re.findall('ab?','abbb')) #['ab']

#匹配全部包含小数在内的数字

print(re.findall('\d+\.?\d*',"asdfasdf123as1.13dfa12adsf1asdf3")) #['123', '1.13', '12', '1', '3']

 

#.*默认为贪婪匹配

print(re.findall('a.*b','a1b22222222b')) #['a1b22222222b']

 

#.*?为非贪婪匹配:推荐使用

print(re.findall('a.*?b','a1b22222222b')) #['a1b']

 

#+

print(re.findall('ab+','a')) #[]

print(re.findall('ab+','abbb')) #['abbb']

 

#{n,m}

print(re.findall('ab{2}','abbb')) #['abb']

print(re.findall('ab{2,4}','abbb')) #['abb']

print(re.findall('ab{1,}','abbb')) #'ab{1,}' ===> 'ab+'

print(re.findall('ab{0,}','abbb')) #'ab{0,}' ===> 'ab*'

 

#[]

print(re.findall('a[1*-]b','a1b a*b a-b')) #[]内的都为普通字符了,且若是-没有被转意的话,应该放到[]的开头或结尾

print(re.findall('a[^1*-]b','a1b a*b a-b a=b')) #[]内的^表明的意思是取反,因此结果为['a=b']

print(re.findall('a[0-9]b','a1b a*b a-b a=b')) #[]内的^表明的意思是取反,因此结果为['a=b']

print(re.findall('a[a-z]b','a1b a*b a-b a=b aeb')) #[]内的^表明的意思是取反,因此结果为['a=b']

print(re.findall('a[a-zA-Z]b','a1b a*b a-b a=b aeb aEb')) #[]内的^表明的意思是取反,因此结果为['a=b']

 

#\# print(re.findall('a\\c','a\c')) #对于正则来讲a\\c确实能够匹配到a\c,可是在python解释器读取a\\c时,会发生转义,而后交给re去执行,因此抛出异常

print(re.findall(r'a\\c','a\c')) #r表明告诉解释器使用rawstring,即原生字符串,把咱们正则内的全部符号都当普通字符处理,不要转义

print(re.findall('a\\\\c','a\c')) #同上面的意思同样,和上面的结果同样都是['a\\c']

 

#():分组

print(re.findall('ab+','ababab123')) #['ab', 'ab', 'ab']

print(re.findall('(ab)+123','ababab123')) #['ab'],匹配到末尾的ab123中的ab

print(re.findall('(?:ab)+123','ababab123')) #findall的结果不是匹配的所有内容,而是组内的内容,?:可让结果为匹配的所有内容

print(re.findall('href="(.*?)"','<a href="http://www.baidu.com">点击</a>'))#['http://www.baidu.com']

print(re.findall('href="(?:.*?)"','<a href="http://www.baidu.com">点击</a>'))#['href="http://www.baidu.com"']

 

#|

print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))
匹配模式

11.2.4 re模块提供的方法介绍

# ===========================re模块提供的方法介绍===========================

import re

#1

print(re.findall('e','alex make love') )   #['e', 'e', 'e'],返回全部知足匹配条件的结果,放在列表里

#2

print(re.search('e','alex make love').group()) #e,只到找到第一个匹配而后返回一个包含匹配信息的对象,该对象能够经过调用group()方法获得匹配的字符串,若是字符串没有匹配,则返回None。

 

#3

print(re.match('e','alex make love'))    #None,同search,不过在字符串开始处进行匹配,彻底能够用search+^代替match

 

#4

print(re.split('[ab]','abcd'))     #['', '', 'cd'],先按'a'分割获得''和'bcd',再对''和'bcd'分别按'b'分割

 

#5

print('===>',re.sub('a','A','alex make love')) #===> Alex mAke love,不指定n,默认替换全部

print('===>',re.sub('a','A','alex make love',1)) #===> Alex make love

print('===>',re.sub('a','A','alex make love',2)) #===> Alex mAke love

print('===>',re.sub('^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$',r'\5\2\3\4\1','alex make love')) #===> love make alex

 

print('===>',re.subn('a','A','alex make love')) #===> ('Alex mAke love', 2),结果带有总共替换的个数

 

 

#6

obj=re.compile('\d{2}')

 

print(obj.search('abc123eeee').group()) #12

print(obj.findall('abc123eeee')) #['12'],重用了obj
re模块提供的方法介绍

11.2.5 补充一

#####补充一

import re

print(re.findall("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")) #['h1']

print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>").group()) #<h1>hello</h1>

print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>").groupdict()) #<h1>hello</h1>

 

print(re.search(r"<(\w+)>\w+</(\w+)>","<h1>hello</h1>").group())

print(re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>").group())
补充一

11.2.6 补充二

#####补充二

import re

 

print(re.findall(r'-?\d+\.?\d*',"1-12*(60+(-40.35/5)-(-4*3))")) #找出全部数字['1', '-12', '60', '-40.35', '5', '-4', '3']

 

 

#使用|,先匹配的先生效,|左边是匹配小数,而findall最终结果是查看分组,全部即便匹配成功小数也不会存入结果

#而不是小数时,就去匹配(-?\d+),匹配到的天然就是,非小数的数,在此处即整数

print(re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")) #找出全部整数['1', '-2', '60', '', '5', '-4', '3']
补充二

11.2.7 计算器做业参考

#计算器做业参考:http://www.cnblogs.com/wupeiqi/articles/4949995.html

expression='1-2*((60+2*(-3-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'

 

content=re.search('\(([\-\+\*\/]*\d+\.?\d*)+\)',expression).group() #(-3-40.0/5)

11.2.8 search与findall

#为什么一样的表达式search与findall却有不一样结果:

print(re.search('\(([\+\-\*\/]*\d+\.?\d*)+\)',"1-12*(60+(-40.35/5)-(-4*3))").group()) #(-40.35/5)

print(re.findall('\(([\+\-\*\/]*\d+\.?\d*)+\)',"1-12*(60+(-40.35/5)-(-4*3))")) #['/5', '*3']

 

#看这个例子:(\d)+至关于(\d)(\d)(\d)(\d)...,是一系列分组

print(re.search('(\d)+','123').group()) #group的做用是将全部组拼接到一块儿显示出来

print(re.findall('(\d)+','123')) #findall结果是组内的结果,且是最后一个组的结果
为什么一样的表达式search与findall却有不一样结果
#_*_coding:utf-8_*_

__author__ = 'Linhaifeng'

#在线调试工具:tool.oschina.net/regex/#

import re

 

s='''

http://www.baidu.com

egon@oldboyedu.com

你好

010-3141

'''

 

#最常规匹配

# content='Hello 123 456 World_This is a Regex Demo'

# res=re.match('Hello\s\d\d\d\s\d{3}\s\w{10}.*Demo',content)

# print(res)

# print(res.group())

# print(res.span())

 

#泛匹配

# content='Hello 123 456 World_This is a Regex Demo'

# res=re.match('^Hello.*Demo',content)

# print(res.group())

 

 

#匹配目标,得到指定数据

 

# content='Hello 123 456 World_This is a Regex Demo'

# res=re.match('^Hello\s(\d+)\s(\d+)\s.*Demo',content)

# print(res.group()) #取全部匹配的内容

# print(res.group(1)) #取匹配的第一个括号内的内容

# print(res.group(2)) #去陪陪的第二个括号内的内容

 

 

 

#贪婪匹配:.*表明匹配尽量多的字符

# import re

# content='Hello 123 456 World_This is a Regex Demo'

#

# res=re.match('^He.*(\d+).*Demo$',content)

# print(res.group(1)) #只打印6,由于.*会尽量多的匹配,而后后面跟至少一个数字

 

 

#非贪婪匹配:?匹配尽量少的字符

# import re

# content='Hello 123 456 World_This is a Regex Demo'

#

# res=re.match('^He.*?(\d+).*Demo$',content)

# print(res.group(1)) #只打印6,由于.*会尽量多的匹配,而后后面跟至少一个数字

 

 

#匹配模式:.不能匹配换行符

content='''Hello 123456 World_This

is a Regex Demo

'''

# res=re.match('He.*?(\d+).*?Demo$',content)

# print(res) #输出None

 

# res=re.match('He.*?(\d+).*?Demo$',content,re.S) #re.S让.能够匹配换行符

# print(res)

# print(res.group(1))

 

 

#转义:\

 

# content='price is $5.00'

# res=re.match('price is $5.00',content)

# print(res)

#

# res=re.match('price is \$5\.00',content)

# print(res)

 

 

#总结:尽可能精简,详细的以下

    # 尽可能使用泛匹配模式.*

    # 尽可能使用非贪婪模式:.*?

    # 使用括号获得匹配目标:用group(n)去取得结果

    # 有换行符就用re.S:修改模式

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

#re.search:会扫描整个字符串,不会从头开始,找到第一个匹配的结果就会返回

 

# import re

# content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'

#

# res=re.match('Hello.*?(\d+).*?Demo',content)

# print(res) #输出结果为None

 

#

# import re

# content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'

#

# res=re.search('Hello.*?(\d+).*?Demo',content) #

# print(res.group(1)) #输出结果为

 

 

 

#re.search:只要一个结果,匹配演练,

import re

content='''

<tbody>

<tr id="4766303201494371851675" class="even "><td><div class="hd"><span class="num">1</span><div class="rk"><span class="u-icn u-icn-75"></span></div></div></td><td class="rank"><div class="f-cb"><div class="tt"><a href="/song?id=476630320"><img class="rpic" src="http://p1.music.126.net/Wl7T1LBRhZFg0O26nnR2iQ==/19217264230385030.jpg?param=50y50&amp;quality=100"></a><span data-res-id="476630320" "

# res=re.search('<a\shref=.*?<b\stitle="(.*?)".*?b>',content)

# print(res.group(1))

 

 

#re.findall:找到符合条件的全部结果

# res=re.findall('<a\shref=.*?<b\stitle="(.*?)".*?b>',content)

# for i in res:

#     print(i)

 

 

 

#re.sub:字符串替换

import re

content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'

 

# content=re.sub('\d+','',content)

# print(content)

 

 

#用\1取得第一个括号的内容

#用法:将123与456换位置

# import re

# content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'

#

# # content=re.sub('(Extra.*?)(\d+)(\s)(\d+)(.*?strings)',r'\1\4\3\2\5',content)

# content=re.sub('(\d+)(\s)(\d+)',r'\3\2\1',content)

# print(content)

 

 

 

 

# import re

# content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'

#

# res=re.search('Extra.*?(\d+).*strings',content)

# print(res.group(1))

 

 

# import requests,re

# respone=requests.get('https://book.douban.com/').text

 

# print(respone)

# print('======'*1000)

# print('======'*1000)

# print('======'*1000)

# print('======'*1000)

# res=re.findall('<li.*?cover.*?href="(.*?)".*?title="(.*?)">.*?more-meta.*?author">(.*?)</span.*?year">(.*?)</span.*?publisher">(.*?)</span.*?</li>',respone,re.S)

# # res=re.findall('<li.*?cover.*?href="(.*?)".*?more-meta.*?author">(.*?)</span.*?year">(.*?)</span.*?publisher">(.*?)</span>.*?</li>',respone,re.S)

#

#

# for i in res:

#     print('%s    %s    %s   %s' %(i[0].strip(),i[1].strip(),i[2].strip(),i[3].strip()))

 

 
search与findall的使用

11.3 时间模块time与datetime

11.3.1 时间模块介绍

在Python中,一般有这几种方式来表示时间:

l  时间戳(timestamp):一般来讲,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。咱们运行“type(time.time())”,返回的是float类型。

l  格式化的时间字符串(Format String)

l  结构化的时间(struct_time):struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时)

 

11.3.2 时间模块相关示例

import time

#--------------------------咱们先以当前时间为准,让你们快速认识三种形式的时间

print(time.time()) # 时间戳:1487130156.419527

print(time.strftime("%Y-%m-%d %X")) #格式化的时间字符串:'2017-02-15 11:40:53'

 

print(time.localtime()) #本地时区的struct_time

print(time.gmtime())    #UTC时区的struct_time

 
时间模块示例

11.3.3 格式化字符串的时间格式

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

%d    Day of the month as a decimal number [01,31].    

%H    Hour (24-hour clock) as a decimal number [00,23].    

%I    Hour (12-hour clock) as a decimal number [01,12].    

%j    Day of the year as a decimal number [001,366].    

%m    Month as a decimal number [01,12].    

%M    Minute as a decimal number [00,59].    

%p    Locale’s equivalent of either AM or PM.    (1)

%S    Second as a decimal number [00,61].    (2)

%U    Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.    (3)

%w    Weekday as a decimal number [0(Sunday),6].    

%W    Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.    (3)

%x    Locale’s appropriate date representation.    

%X    Locale’s appropriate time representation.     

%y    Year without century as a decimal number [00,99].    

%Y    Year with century as a decimal number.    

%z    Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].    

%Z    Time zone name (no characters if no time zone exists).    

%%    A literal '%' character.

 
格式化字符串的时间格式

11.3.4 时间戳转换关系

其中计算机认识的时间只能是'时间戳'格式,而程序员可处理的或者说人类能看懂的时间有: '格式化的时间字符串','结构化的时间' ,因而有了下图的转换关系。

 

1 #--------------------------按图1转换时间

 2 # localtime([secs])

 3 # 将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。

 4 time.localtime()

 5 time.localtime(1473525444.037215)

 6

 7 # gmtime([secs]) 和localtime()方法相似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。

 8

 9 # mktime(t) : 将一个struct_time转化为时间戳。

10 print(time.mktime(time.localtime()))#1473525749.0

11

12

13 # strftime(format[, t]) : 把一个表明时间的元组或者struct_time(如由time.localtime()和

14 # time.gmtime()返回)转化为格式化的时间字符串。若是t未指定,将传入time.localtime()。若是元组中任何一个

15 # 元素越界,ValueError的错误将会被抛出。

16 print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56

17

18 # time.strptime(string[, format])

19 # 把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操做。

20 print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X'))

21 #time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6,

22 #  tm_wday=3, tm_yday=125, tm_isdst=-1)

23 #在这个函数中,format默认为:"%a %b %d %H:%M:%S %Y"。
按图1转换时间

 

 

 

1 #--------------------------按图2转换时间

2 # asctime([t]) : 把一个表示时间的元组或者struct_time表示为这种形式:'Sun Jun 20 23:21:05 1993'。

3 # 若是没有参数,将会将time.localtime()做为参数传入。

4 print(time.asctime())#Sun Sep 11 00:43:43 2016

5

6 # ctime([secs]) : 把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。若是参数未给或者为

7 # None的时候,将会默认time.time()为参数。它的做用至关于time.asctime(time.localtime(secs))。

8 print(time.ctime())  # Sun Sep 11 00:46:38 2016

9 print(time.ctime(time.time()))  # Sun Sep 11 00:46:38 2016

1 #--------------------------其余用法

2 # sleep(secs)

3 # 线程推迟指定的时间运行,单位为秒。
按图2转换时间

11.3.5 datetime模块

#时间加减

import datetime

 

# print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925

#print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19

# print(datetime.datetime.now() )

# print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天

# print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天

# print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时

# print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分

 

 

#

# c_time  = datetime.datetime.now()

# print(c_time.replace(minute=3,hour=2)) #时间替换

 
时间加减

第12章 做业:ATM+购物商城程序

做业需求:

模拟实现一个ATM + 购物商城程序

  1. 额度 15000或自定义
  2. 实现购物商城,买东西加入 购物车,调用信用卡接口结帐
  3. 能够提现,手续费5%
  4. 每个月22号出帐单,每个月10号为还款日,过时未还,按欠款总额 万分之5 每日计息
  5. 支持多帐户登陆
  6. 支持帐户间转帐
  7. 记录每个月平常消费流水
  8. 提供还款接口
  9. ATM记录操做日志
  10. 提供管理接口,包括添加帐户、用户额度,冻结帐户等。。。
  11. 用户认证用装饰器

示例代码 https://github.com/triaquae/py3_training/tree/master/atm 

简易流程图:https://www.processon.com/view/link/589eb841e4b0999184934329 

相关文章
相关标签/搜索