(四)4-5 Python的logging、os和sys

logging
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

注:程序中写了三句话,但是屏幕中只输出一个warning级别的日志
默认情况下,logging讲日志打印到屏幕,日志级别大小关系为:CRITICAL>ERROR>WARNING>INFO>DEBUG>NOTSET
DEBUG:详细的信息,通常只出现在诊断问题上
INFO:确认一切按预期运行
WARNING:警告,可能有一些意想不到的事情发生了,但是软件还能按照预期工作
ERROR: 更严重的问题,软件没能执行一些功能
CRITICAL:一个严重的错误,程序可能无法继续运行
logging默认日志级别是info。

import logging
logging.basicConfig(level=__debug__,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%Y/%m/%d %H:%M:%S',
                    # datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='myapp.log',
                    filemode='w')
logger = logging.getLogger(__name__)
logger.debug("this is debug message")
logger.info("this is info message")
logger.warning("this is warning message")

运行结果:

myapp.log
2017/11/08 23:45:31 10_4.py[line:18] DEBUG this is debug message
2017/11/08 23:45:31 10_4.py[line:19] INFO this is info message
2017/11/08 23:45:31 10_4.py[line:20] WARNING this is warning message

os模块
os模块的使用
通过os模块调用系统命令,获得路径,获取操作系统的类型等都是使用该模块。

1、通过os获取系统类型
import os
print(os.name)
如果是Windows系统os.name='nt',
如果是linux系统os.name='posix'.
2、执行系统命令
很多时候我们通过python代用系统命令
import os
os.system('ipconfig')
content = os.popen('ipconfig').read()
print(content)
注:
os.system('ipconfig')指挥调用系统命令
os.popen()返回一个file对象,通过file.read()获取最后系统命令执行的结果
3、目录和文件操作

import os 
print(os.getcwd())
# 获得路径
os.chdir("d:")
print(os.getcwd())
os.chdir(r'E:CNTV')
#切换目录
print(os.listdir(os.getcwd()))
#列出当前目录的文件
print(os.listdir('C:Python27'))
#列出指定目录的文件
print(os.getcwd())
# os.mkdir("text")
print(os.linesep)
# 打印操作系统的分隔符,linux是
,win是

if not os.path.exists("test") :
    os.makedirs("test")
else:
    print("test us exists")
a = os.path.join('.',"a","b","c")
print(a)
#只是拼接当前目录
print(os.path.dirname(os.getcwd()))
print(os.path.dirname(os.getcwd()))
#获得文件的目录
注:
1,os.getcwd()    获得目录的当前系统程序工作路劲
2,os. chdir(‘目标目录’)    切换到目标目录
3,os.listdir(‘字符串目录’)    列出字符串目录下的所有文件
4,os.mkdir('目录')    创建目录
5,os.remove('1.txt')    删除文件,文件不存在时会报错
6,os.linesep    打印操作系统的分隔符,linux系统的分隔符
,windows系统的分隔符
,mac系统的分隔符
7,os.path.join(os.getcwd(), 'aaa', ‘bbb’, ‘ccc’)    拼接出来多级目录:E:	estaaabbccc
8,os.path.exists(‘目录’)    判断目录是否存在
9,os.path.split(‘文件或者目录’)    把最后的一个目录或者文件和前面的目录分开,返回一个tuple
10,os.path.splitext(‘文件’)    把文件的后缀名和前面分开,返回一个tuple
os.fork()

commands模块

commands模块只使用linux与shell模式下
我们经常调用系统脚本或者系统命令解决很多问题,通过python调用系统命令有三种方式:cmd代表系统命令
a、commands.getoutput(cmd)
只返回执行shell命令的结果

commands.getoutput的返回值只有返回结果
import commands
cmd = "ls /home/"
result = commands.getoutput(cmd)
print(type(result))
print(result)


commands.getstatusoutput的返回值是一个tuple类型
第一个值接受状态码,返回结果是一个int类型
第二个值接受返回结果,返回结果是一个str类型
import commands
cmd = "ps -ef"
status,result = commands.getstatusoutput(cmd)
print(type(status))
print(status)
print(type(result))
print(result)

sys模块

1、通过sys模块获取程序参数
import sys
if __name__ =="__main__":
print("sys.argv[0]={0}".format(sys.argv[0]))
print("sys.argv[1]={1}".format(sys.argv[1]))
2、sys.stdoutstdinstderr
stdout,stdin以及stderr变量包含与I/O流对应的流对象
3、sys.stdout 与print
当我们在python中打印对象调用print obj时候,事实上调用了sys.stdout.write(obj + " "),print讲需要的内容打印到控制台,然后追加一个换行符,print会调用sys.stdout的write方法
下面两行是等价的
import sys
sys.stdout.write("hello" + " ")
print("hello")
4、从控制台重定向到文件
import sys
t_handle = open('out.log','w')
sys.stdout = t_handle

原文地址:https://www.cnblogs.com/pythonlx/p/7817338.html