'''
logging模块:
logging的日志可以分为
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
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.
5个级别
'''
import logging
# 输出到屏幕,不输出info跟debug
logging.info("info.......")
logging.debug("debug>>>>>")
logging.warning("warning!")
logging.error("error!")
logging.critical("critical!")

输出到屏幕

import logging
# 写到文件,>=INFO级别的写入到文件中,追加写入
# 打印到屏幕和写入文件进行一个
logging.basicConfig(filename="test.log", level=logging.INFO)
logging.debug("msg_debug")
logging.info("msg_info")
logging.warning("msg_warning")
logging.error("msg_error")
logging.critical("msg_critical")

写入到文件

'''
日志格式:
%(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
# 按一定格式写到文件,>=INFO级别的写入到文件中,追加写入
# 打印到屏幕和写入文件进行一个
logging.basicConfig(filename="test.log",
level=logging.INFO,
format="%(levelname)s|%(asctime)s |%(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p")
logging.debug("msg_debug")
logging.info("msg_info")
logging.warning("msg_warning")
logging.error("msg_error")
logging.critical("msg_critical")
'''
INFO|08/04/2018 10:33:19 PM |msg_info
WARNING|08/04/2018 10:33:19 PM |msg_warning
ERROR|08/04/2018 10:33:19 PM |msg_error
CRITICAL|08/04/2018 10:33:19 PM |msg_critical
'''

日志加时间输出到文件

'''
logger提供了应用程序可以直接使用的接口;
handler将(logger创建的)日志记录发送到合适的目的输出(文件/屏幕/远程等);
filter提供了细度设备来决定输出哪条日志记录(包含某字段之类);
formatter决定日志记录的最终输出格式。
'''
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)
logger.addHandler(fh) # 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

屏幕和文件都输出

'''
logger
每个程序在输出信息之前都要获得一个Logger。Logger通常对应了程序的模块名,比如聊天工具的图形界面模块可以这样获得它的Logger:
LOG=logging.getLogger(”chat.gui”)
而核心模块可以这样:
LOG=logging.getLogger(”chat.kernel”) Logger.setLevel(lel):指定最低的日志级别,低于lel的级别将被忽略。debug是最低的内置级别,critical为最高
Logger.addFilter(filt)、Logger.removeFilter(filt):添加或删除指定的filter
Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或删除指定的handler
Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():可以设置的日志级别 handler handler对象负责发送相关的信息到指定目的地。Python的日志系统有多种Handler可以使用。有些Handler可以把信息输出到控制台,有些Logger可以把信息输出到文件,还有些 Handler可以把信息发送到网络上。如果觉得不够用,还可以编写自己的Handler。可以通过addHandler()方法添加多个多handler
Handler.setLevel(lel):指定被处理的信息级别,低于lel级别的信息将被忽略
Handler.setFormatter():给这个handler选择一个格式
Handler.addFilter(filt)、Handler.removeFilter(filt):新增或删除一个filter对象 每个Logger可以附加多个Handler。接下来我们就来介绍一些常用的Handler:
1) logging.StreamHandler
使用这个Handler可以向类似与sys.stdout或者sys.stderr的任何文件对象(file object)输出信息。它的构造函数是:
StreamHandler([strm])
其中strm参数是一个文件对象。默认是sys.stderr 2) logging.FileHandler
和StreamHandler类似,用于向一个文件输出日志信息。不过FileHandler会帮你打开这个文件。它的构造函数是:
FileHandler(filename[,mode])
filename是文件名,必须指定一个文件名。
mode是文件的打开方式。参见Python内置函数open()的用法。默认是’a',即添加到文件末尾。 3) logging.handlers.RotatingFileHandler
这个Handler类似于上面的FileHandler,但是它可以管理文件大小。当文件达到一定大小之后,它会自动将当前日志文件改名,然后创建 一个新的同名日志文件继续输出。比如日志文件是chat.log。当chat.log达到指定的大小之后,RotatingFileHandler自动把 文件改名为chat.log.1。不过,如果chat.log.1已经存在,会先把chat.log.1重命名为chat.log.2。。。最后重新创建 chat.log,继续输出日志信息。它的构造函数是:
RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
其中filename和mode两个参数和FileHandler一样。
maxBytes用于指定日志文件的最大文件大小。如果maxBytes为0,意味着日志文件可以无限大,这时上面描述的重命名过程就不会发生。
backupCount用于指定保留的备份文件的个数。比如,如果指定为2,当上面描述的重命名过程发生时,原有的chat.log.2并不会被更名,而是被删除。 4) logging.handlers.TimedRotatingFileHandler
这个Handler和RotatingFileHandler类似,不过,它没有通过判断文件大小来决定何时重新创建日志文件,而是间隔一定时间就 自动创建新的日志文件。重命名的过程与RotatingFileHandler类似,不过新的文件不是附加数字,而是当前时间。它的构造函数是:
TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
其中filename参数和backupCount参数和RotatingFileHandler具有相同的意义。
interval是时间间隔。
when参数是一个字符串。表示时间间隔的单位,不区分大小写。它有以下取值:
S 秒
M 分
H 小时
D 天
W 每星期(interval==0时代表星期一)
midnight 每天凌晨
'''

logger,filter,handler,formatter说明

import logging
from logging import handlers logger = logging.getLogger(__name__)
log_file = "timelog.log"
#最大10自己,保留3个
#fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=3)
#每隔5秒,保留3个
fh = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3) formatter = logging.Formatter('%(asctime)s %(module)s:%(lineno)d %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) logger.warning("test1")
logger.warning("test12")
logger.warning("test13")
logger.warning("test14")

日志过大自动截断

正则表达式模块:

'.'     默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
'^' 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)

[\s]    匹配任何空白字符:,等价于[ \f\n\r\t\v]


[^\s]   匹配任何非空白字符:,^用于"[]"外表示从开头匹配,用于"[]"内表示"非",即不包括

'$'     匹配字符结尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以
'*' 匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac") 结果为['abb', 'ab', 'a']
'+' 匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab', 'abb']
'?' 匹配前一个字符1次或0次
'{m}' 匹配前一个字符m次
'{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb', 'ab', 'abb']
'|' 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC'
'(...)' 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abcabca456c '\A' 只从字符开头匹配,re.search("\Aabc","alexabc") 是匹配不到的
'\Z' 匹配字符结尾,同$
'\d' 匹配数字0-9
'\D' 匹配非数字
'\w' 匹配[A-Za-z0-9]
'\W' 匹配非[A-Za-z0-9]
's' 匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 结果 '\t' '(?P<name>...)' 分组匹配 re.search(
"(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})",
"").groupdict("city") 结果{'province': '', 'city': '', 'birthday': ''}
import re
a = re.match("\w+","inet 地址:192.168.1.2") # 从头开始匹配
print(a.group()) # inet
a = re.search("(\d{2})(\d{2})(\d{4})","371481198812112233 name:alex").groups()
print(a) # ('37', '14', '8119')
a = re.search("(\d{2})(\d{2})(\d{4})","FF371481198812112233 name:alex").group()
print(a) #
a = re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})",
"").groupdict("city")
print(a) # {'province': '3714', 'city': '81', 'birthday': '1993'}
a = re.findall("\d+","rr232rs34reg454fd555")
print(a) # ['232', '34', '454', '555']
a = re.split("\d+","rr232rs34reg454fd555")
print(a) # ['rr', 'rs', 'reg', 'fd', '']
a = re.sub("\d+","|","rr232rs34reg454fd555")
print(a) # rr|rs|reg|fd|

re模块方法

def merge_plus_sub(expression):
'''
将连续的加减号合并,奇数个减号为- 偶数个为+
:param expression:
:return:
'''
def merge(m):
if m:
count_sub = m.group().count('-')
if count_sub % 2 == 1:
return '-'
else:
return '+'
expression = re.sub("[\+\-]{2,}", merge, expression)
return expression

合并加减号

m = re.match("^[\+\-]{0,1}\d+\.{0,1}\d*([\+\-\*\/]{1}[\+\-]{0,1}\d+\.{0,1}\d*)*$","-9.5")
match = re.match("^[\+\-]{0,1}\d+\.{0,1}\d*([\+\-\*\/]{1}[\+\-]{0,1}\d+\.{0,1}\d*)*$",
'+9 - 2 * 5 / 3 + 7 / 3 * 99 / 4 * 2998 + 10 * 568 / 14')
_match = re.search('\([^\(|\)]+\)', "(4+2)+(33*(9-2)")
match = re.match('^(delete){1}\s+(from){1}\s+.*[^ ].*\s+(where){1}\s+.*[^ ].*$',
"delete from xx where id=2")
match = re.match('^(insert){1}\s+(into){1}\s+.*[^ ].*\s+(values){1}\s*\({1}.*[^ ].*\){1}$',
'insert into xx values(1,2,3)')

应用实例

subprocess模块

'''
subprocess.run("dir",shell=True)
#执行命令,返回命令执行状态 , 0 or 非0
>>> retcode = subprocess.call(["ls", "-l"]) #执行命令,如果命令结果为0,就正常返回,否则抛异常
>>> subprocess.check_call(["ls", "-l"])
0 #接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果
>>> subprocess.getstatusoutput('ls /bin/ls')
(0, '/bin/ls') #接收字符串格式命令,并返回结果
>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls' #执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res
>>> res=subprocess.check_output(['ls','-l'])
>>> res
b'total 0\ndrwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM\n' #上面那些方法,底层都是封装的subprocess.Popen
poll()
Check if child process has terminated. Returns returncode wait()
Wait for child process to terminate. Returns returncode attribute. terminate() 杀掉所启动进程
communicate() 等待任务结束 stdin 标准输入 stdout 标准输出 stderr 标准错误 pid
The process ID of the child process.
subprocess.PIPE是管道,保存结果的地方,因为屏幕没有存储功能
为什么要管道,Python和shell是两个程序,不能直接通信,必须通过操作系统提供的管道来通信
#例子
>>> p = subprocess.Popen("df -h|grep disk",stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
>>> p.stdout.read() #p.poll() 为0的时候可以得到结果
b'/dev/disk1 465Gi 64Gi 400Gi 14% 16901472 104938142 14% /\n'
'''

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

模块简介:(logging)(re)(subprocess)的更多相关文章

  1. python模块基础之json,requeste,xml,configparser,logging,subprocess,shutil。

    1.json模块 json     用于[字符串]和 [python基本数据类型] 间进行转换(可用于不同语言之前转换),json.loads,将字符串转成python的基本数据类型,json.dum ...

  2. Python中模块之logging & subprocess的讲解

    subprocess & logging模块的介绍 1. subprocess 该模块替代了os.system & os.pawn*所实现的功能. 2. logging 1. 日志五大 ...

  3. Python logging 模块简介

    Table of Contents 1. Logging 模块 1.1. 简介 1.2. 简单输出日志 1.3. 输入日志到文件 1.4. 几个基本概念 1.4.1. loggers 1.4.2. h ...

  4. subprocess, re模块,logging, 包等使用方法

    subprocess, re模块,logging, 包等使用方法 subprocess ''' subprocess: sub: 子 process: 进程 可以通过python代码给操作系统终端发送 ...

  5. Python常用模块(logging&re&时间&random&os&sys&shutil&序列化&configparser&&hashlib)

    一. logging(日志模块) 二 .re模块 三. 时间模块 四. random模块 五. os模块 六. sys模块 七. shutil模块 八. 序列化模块(json&pickle&a ...

  6. 【Pytyon模块】logging模块-日志处理

    一.日志相关概念 1.日志的作用 通过log的分析,可以方便用户了解系统或软件.应用的运行情况:如果你的应用log足够丰富,也可以分析以往用户的操作行为.类型喜好.地域分布或其他更多信息:如果一个应用 ...

  7. Python::OS 模块 -- 简介

    OS 模块简介 OS模块是Python标准库中的一个用于访问操作系统功能的模块,OS模块提供了一种可移植的方法使用操作系统的功能.使用OS模块中提供的接口,可以实现跨平台访问.但是在OS模块中的接口并 ...

  8. python学习之路-7 模块configparser/xml/shutil/subprocess以及面向对象初级入门

    本篇记录内容 模块 configparser xml shutil subprocess 面向对象 面向对象基础 面向对象编程和函数式编程对比 面向对象中对象和类的关系 面向对象之构造方法 面向对象之 ...

  9. Qt5模块简介

        原文链接:Qt5 模块简介 无意中看到这篇文章,虽然讲的不是经常用的东西,但是看了这篇文章之后,可以对qt有个大致的了解,能够清晰的知道自己想要什么,应该关注那一部分,学习了,相信以后会又很大 ...

随机推荐

  1. JDK1.8源码(三)——java.util.HashMap

      什么是哈希表? 在讨论哈希表之前,我们先大概了解下其他数据结构在新增,查找等基础操作执行性能 数组:采用一段连续的存储单元来存储数据.对于指定下标的查找,时间复杂度为O(1):通过给定值进行查找, ...

  2. Python爬虫入门教程 6-100 蜂鸟网图片爬取之一

    1. 蜂鸟网图片--简介 国庆假日结束了,新的工作又开始了,今天我们继续爬取一个网站,这个网站为 http://image.fengniao.com/ ,蜂鸟一个摄影大牛聚集的地方,本教程请用来学习, ...

  3. 详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(下)

    在上一篇(详解intellij idea 搭建SSM框架(spring+maven+mybatis+mysql+junit)(上))博文中已经介绍了关于SSM框架的各种基础配置,(对于SSM配置不熟悉 ...

  4. EF架构~让mysql支持DbFunctions扩展函数

    回到目录 对于在Linq To Entity里使用日期函数需要DbFunctions里的扩展方法,而不能使用.net里的日期函数,因为linq的代码会被翻译成SQL发到数据库端,如你的.net方法对于 ...

  5. 全文检索-Elasticsearch (二) CURD

    ElasticSearch6.0以上版本的增删改查基本操作基于JSON的REST API与ElasticSearch进行通信.可以使用任何HTTP客户端来通信.当然ElasticSearch自己的文档 ...

  6. Asp.net Core 使用Jenkins + Dockor 实现持续集成、自动化部署(一):Jenkins安装

    2019/1/31更新,经过我一段时间的使用 建议大家的jenkins还是不要使用docker方式安装 建议大家的jenkins还是不要使用docker方式安装 建议大家的jenkins还是不要使用d ...

  7. Thread之九:stop

    搞过Java线程的人都知道,stop这个方法是臭名昭著了,早就被弃用了,但是现在任然有很多钟情与他的人,永远都放不下他,因为从他的字面意思上我们可以知道他貌似可以停止一个线程,这个需求是每个搞线程开发 ...

  8. [十五]java.math包简介,RoundingMode与MathContext

    java.math包提供了java中的数学类 包括基本的浮点库.复杂运算以及任意精度的数据运算   '可以看得到,主要包括三个类一个枚举 BigDecimal和BigInteger接下来会详细介绍 先 ...

  9. 服务注册中心之ZooKeeper系列(一)

    一.服务注册中心介绍 分布式服务框架部署在多台不同的机器上.例如服务A是订单相关的处理服务,服务B是订单的客户的相关信息服务.此时有个需求需要在服务A中获取订单客户的信息.如下图: 此时就面临以下几个 ...

  10. MySQL递归查询_函数语法检查_GROUP_CONCAT组合结果集的使用

    1-前言: 在Mysql使用递归查询是很不方便的,不像Sqlserver可以直接使用声明变量,使用虚拟表等等.如:DECLARE,BEGIN ...  END   ,WHILE ,IF 等等. 在My ...