NO.20loging os sys command

来源:互联网 发布:php获取跳转前的url 编辑:程序博客网 时间:2024/06/16 09:13
#!/usr/bin/env python# -*- coding:utf-8 -*-# @Time  : 2017/11/3 11:27# @author : hezefan# @file  : 10.4.py'''logging'''import logging##从上往下,依次是日志的五个级别,默认从warning级别开始打印,低于warning级别默认的不打印# logging.debug('this is debug message')# logging.info('this is debug message')# logging.warning('this is debug message')# logging.error('this is debug message')# logging.critical('this is debug message')#以上为输出到屏幕,我们一般不用,怎么输出到log文件呢from datetime import datetimenow_time=datetime.now()_time=now_time.strftime('%Y-%m-%d')logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt=' %Y/%m/%d %H:%M:%S', filename='{0}.log'.format(_time), filemode='w')loger=logging.getLogger()logging.debug('this is a debug message')logging.info('this is a debug message')logging.warning('this is a debug message')logging.error('this is a  debug message')logging.critical('this is a debug message')# 主要是通过logging.basicConfig函数进行操作,现在我们来介绍一下该函数参数的用法:# level: 设置日志级别,默认为logging.WARNING# filename: 指定日志文件名。# filemode: 和file函数意义相同,指定日志文件的打开模式,'w'或'a'# format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:# %(levelname)s: 打印日志级别名称#   %(filename)s: 打印当前执行程序名#  %(funcName)s: 打印日志的当前函数#  %(lineno)d: 打印日志的当前行号#  %(asctime)s: 打印日志的时间#  %(thread)d: 打印线程ID#   %(process)d: 打印进程ID#  %(message)s: 打印日志信息# datefmt: 指定时间格式,同time.strftime()# stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略# logging.getLogger([name]):创建一个日志对象:## 返回一个logger实例,如果没有指定name,返回root logger。只要name相同,返回的logger实例都是同一个而且只有一个,即name和logger实例是一一对应的。这意味着,无需把logger实例在各个模块中传递。只要知道name,就能得到同一个logger实例。# logging.getLogger(__name__) 在上述实例中__name__就指的是__main__。
#!/usr/bin/env python# -*- coding:utf-8 -*-# @Time  : 2017/11/3 13:00# @author : hezefan# @file  : 10.5.py'''os模块'''##1、查看不通的操作系统import osprint(os.name)  ##打印出当前系统类型:windows输出nt,linux输出posix##2、执行系统命令#print(os.system('ipconfig')) ##将返回值输出到屏幕,一般不用#context=os.popen('ipconfig').read()#print(context)#print(context.decode("gbk").encode("utf-8"))  ##括号内为文件编码方式转换#print(context.find('192.16.16.1'))   ##在输出内容中查找内容,输出位置号,后续我们会用正则来查找##3、文件和目录的操作print(os.listdir('.'))   ##查看当前目录下的文件,  ‘。’为当前目录print(os.getcwd())   ##查看当前文件的目录print(os.listdir(os.getcwd()))   ##两者结合,查看当前目录的文件#os.chdir(r'E:\centos')  ##跳转到E盘下,r表示之中的内容不会zhuanyi了#print(os.getcwd())#os.mkdir('test')  #创建一个目录#os.remove('2017-11-03.log')#删除一个文件print(os.linesep)  #查看系统的分隔符nux系统的分隔符\n,windows系统的分隔符\r\n,mac系统的分隔符\rif not os.path.exists('test'):  ##如果没有test,创建,否则打印    os.makedirs('test')else:    print('test is ok!')a=os.path.join('.','aaa','bbb','ccc') #拼接一个目录输出.\aaa\bbb\cccprint(a)print(os.path.dirname((r'E:\centos\vmware.log')))  查看文件的上一级目录
#!/usr/bin/env python# -*- coding:utf-8 -*-# @Time  : 2017/11/6 18:29# @author : hezefan# @file  : 10.6.py'''commands模块,Linux独有'''#!/usr/bin/env python#-*-coding:utf-8 -*-import commandscmd = 'ls /home/'result = commands.getoutput(cmd)print(type(result))print(result)#commands.getoutput(cmd)只返回一个结果#commands.getstatusoutput(cmd)返回一个元组cmd = 'ps -ef'status, result = commands.getstatusoutput(cmd)print(result)#返回的是执行的结果,返回是一个str类型print(status)#返回的是init,返回为0,表示成功,返回其他表示失败
#!/usr/bin/env python# -*- coding:utf-8 -*-# @Time  : 2017/11/6 18:56# @author : hezefan# @file  : 10.7.py'''sys模块'''##传参import sysif __name__ =='__main__':    print('sys.argv[0] = {0}'.format(sys.argv[0]))    print('sys.argv[1] = {0}'.format(sys.argv[1]))    print('sys.argv[2] = {0}'.format(sys.argv[2]))##一下为了解部分# 2,   sys.stdin\stdout\stderr# 功能:stdin , stdout , 以及stderr 变量包含与标准I/O 流对应的流对象. 如果需要更好地控制输出,而print 不能满足你的要求, 它们就是你所需要的. 你也可以替换它们, 这时候你就可以重定向输出和输入到其它设备( device ), 或者以非标准的方式处理它们# 2..1 sys.stdout 与 print# 当我们在 Python 中打印对象调用 print obj 时候,事实上是调用了sys.stdout.write(obj+'\n'),print 将你需要的内容打印到了控制台,然后追加了一个换行符,print 会调用 sys.stdout 的 write 方法# 以下两行在事实上等价:# import sys# sys.stdout.write('hello'+'\n')# print 'hello'# 2.2 sys.stdin 与 raw_input# import sys# a = raw_input('raw_input_name: ')# print(a)# print 'stdin_name: ', #comma to stay in the same line# b = sys.stdin.readline()[:-1] # -1 to discard the '\n' in input stream# print(b)# 2.3  从控制台重定向到文件# Import sys# f_handler=open('out.log', 'w')# sys.stdout=f_handler# print 'hello'# 在当前文件下新生成一个文件out.log,文件内容为hello,## 3,   捕获sys.exit(n)调用# 功能:执行到主程序末尾,解释器自动退出,但是如果需要中途退出程序,可以调用sys.exit函数,带有一个可选的整数参数返回给调用它的程序,表示你可以在主程序中捕获对sys.exit的调用。(0是正常退出,其他为异常)# def exitfunc():#     print "hello world"# sys.exitfunc = exitfunc  # 设置捕获时调用的函数# print "aaaaaaaa"# sys.exit(1)     # 退出自动调用exitfunc()后,程序依然退出了# print "there"  # 不会被 print# 结果:# aaaaaaaa# hello world# 解释:# 1,   设置sys.exitfunc函数,及当执行sys.exit(1)的时候,调用exitfunc函数# 2,   sys.exit(1)后面的内容就不会执行了,因为程序已经退出。
原创粉丝点击