logging模块
- 简单的将日志打印到屏幕
import logging
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
屏幕上打印:
WARNING:root:This is warning message
默认情况下,logging将日志打印到屏幕,日志级别为WARNING;
日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,当然也可以自己定义日志级别。
- 通过logging.basicConfig函数对日志的输出格式及方式做相关配置
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='myapp.log',
filemode='w')
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
./myapp.log文件中内容为:
Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message
logging.basicConfig函数各参数:
filename: 指定日志文件名
filemode: 和file函数意义相同,指定日志文件的打开模式,’w’或’a’
format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:
%(levelno)s: 打印日志级别的数值
%(levelname)s: 打印日志级别名称
%(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
%(filename)s: 打印当前执行程序名
%(funcName)s: 打印日志的当前函数
%(lineno)d: 打印日志的当前行号
%(asctime)s: 打印日志的时间
%(thread)d: 打印线程ID
%(threadName)s: 打印线程名称
%(process)d: 打印进程ID
%(message)s: 打印日志信息
datefmt: 指定时间格式,同time.strftime()
level: 设置日志级别,默认为logging.WARNING
stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略
- 简单范例:
import logging
loging.basicConfig(level=logging.INFO,filename=mylog.log)
logging.info(‘start program’)
logging.info(‘trying to divide 1 by 0’)
print 1/0
logging.info(‘succeesd’)
logging.info(‘end program’)
- 按照级别输出到不同日志:
http://blog.youkuaiyun.com/ivnetware/article/details/51468708
常规用法:可以将不同级别的日志分开记录。、
import logging
// 创建一个logger
logger = logging.getLogger(‘mylogger’)
logger.setLevel(logging.DEBUG)
// 创建一个handler,用于写入日志文件
fh = logging.FileHandler(‘test.log’)
fh.setLevel(logging.DEBUG)
// 再创建一个handler,用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
// 定义handler的输出格式
formatter = logging.Formatter(‘%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s’)
fh.setFormatter(formatter)
ch.setFormatter(formatter)
// 给logger添加handler
logger.addHandler(fh)
logger.addHandler(ch)
// 记录一条日志
logger.info(‘foorbar’)
关于logging模块详解:
http://python.jobbole.com/87300/
http://blog.youkuaiyun.com/zyz511919766/article/details/25136485/
http://blog.youkuaiyun.com/energysober/article/details/53263295
os模块
–OS模块:
引用系统命令: os.system(‘ls’)
获取绝对路径:os.path.abspath(‘./’)
获取当前工作路径:os.getcwd()
表示当前目录:os.curdir
表示上层目录:os.pardir
进入某个目录:os.chdir()
路径分割符:os.sep
列出某个路径的子目录并返回一个列表:os.listdir(‘/home’)
判断文件属性-目录并返回布尔值:os.path.isdir(‘/home’)
判断文件属性-文件并返回布尔值:os.path.isfile(“/home”)
判断文件是否存在:os.path.exists(‘/root’)
去除路径,返回文件名:os.path.basename(path)
返回路径,去除文件名:os.path.dirname(path)
链接路径和文件返回新的路径:os.path.join(‘path’,’file’)
递归某个目录下的所有文件返回三个参数的对象:os.walk(‘/etc’) 分别为:parenet
分割路径获取最后文件或目录名:os.path.split(‘/etc/abc’) -> (‘/etc’,’abc’)
获取文件扩展名:os.path.splitext(‘/path/to/file.txt’)->(‘/path/to/file’,’.txt’)
获取文件大小,单位是字节:os.path.getsize(file)
返回文件访问时间,创建实际,修改时间,属性,单位为绝对秒数:os.path.atime|ctime|mtime(file)
获取当前脚本所在目录:os.path.split(os.path.realpath(file))[0]+’/’
文件重命名:os.rename(‘1.txt’,’2.txt’)
创建目录:os.mkdir(‘aa’)
创建多层目录:os.makedirs(‘aa/bb/cc’)
删除文件:os.remove(‘2.txt’)
删除多层目录:os.removedirs(path)
删除目录:os.rmdir(‘aa’)
举例子:列出当前目录下所有.sh结尾的文件:
[x for x in os.listdir(‘./’) if os.path.isfile(x) and os.path.splitext(x)[1]==’.sh’ ]
os模块中没有copy文件的方法,我们可以试用用shutil模块:
import shutil
shutil.copyfile('a.txt','b.txt')
关于py中调用shell命令的几个方法
- os模块:适合简单的shell命令。不需要存储结果和状态,直接输出
import os
os.system("ls")
也可以使用变量:
path='/etc'
os.system("ls %s" % path) 只能获取命令的执行结果 为0则正常
os.popen("ls").read() 可以获取命令的输出
- commands模块:只有python2支持
#!/usr/bin/env python
import commands
cmd = 'ls /home/'
commands.getoutput(cmd)
status, output = commands.getstatusoutput(cmd)
commands.getstatus(cmd)
.getoutput()返回命令的输出
getstatus()返回命令的执行结果
getstatusoutput(cmd)返回一个元组(status,output)
status代表的shell命令的返回状态,如果成功的话是0;output是shell的返回的结果
-subprocess 模块:支持 使用复杂的shell命令启动进程,可以用列表和字符串格式,返回一个进程对象。
from subprocess import Popen,PIPE
//列表形式:
cmd=['ls',path]
Popen(cmd,stdout=PIPE)
//字符串格式:
str="ls /etc"
p=Popen(str,stdout=PIPE,shell=True)
data=p.stdout 此时data为该命令输出的文件对象。
//函数形式:
def get_ifconfig2():
p=Popen(["ifconfig"],stdout=PIPE,stderr=PIPE)
stdout,stderr=p.communicate()
print stdout,stderr 此时stdout即为该命令输出的文件对象。stderr则为错误信息