py打的日志文件是什么格式的|大神们当文件扩展名是“py”的时候应该用什么应用程序打开呢

py打的日志文件是什么格式的|大神们当文件扩展名是“py”的时候应该用什么应用程序打开呢的第1张示图

Ⅰ python处理日志的包有哪些

#coding:utf-8 #file: FileSplit.pyimport os,os.path,timedef FileSplit(sourceFile, targetFolder):sFile = open(sourceFile, 'r')number = 100000#每个小文件中保存100000条数据dataLine = sFile.readline()tempData = []#缓存列表fileNum = 1if not os.path.isdir(targetFolder): #如果目标目录不存在,则创建os.mkdir(targetFolder)while dataLine:#有数据for row in range(number): tempData.append(dataLine)#将一行数据添加到列表中dataLine = sFile.readline()if not dataLine :breaktFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + str(fileNum) + ".txt")tFile = open(tFilename, 'a+')#创建小文件tFile.writelines(tempData)#将列表保存到文件中tFile.close() tempData = []#清空缓存列表print(tFilename + " 创建于: " + str(time.ctime()))fileNum += 1#文件编号sFile.close()if __name__ == "__main__" :FileSplit("access.log","access")#coding:utf-8 #file: Map.pyimport os,os.path,redef Map(sourceFile, targetFolder):sFile = open(sourceFile, 'r')dataLine = sFile.readline()tempData = {}#缓存列表if not os.path.isdir(targetFolder): #如果目标目录不存在,则创建os.mkdir(targetFolder)while dataLine:#有数据p_re = re.compile(r'(GET|POST)\s(.*?)\sHTTP/1.[01]',re.IGNORECASE) #用正则表达式解析数据match = p_re.findall(dataLine)if match:visitUrl = match[0][1]if visitUrl in tempData:tempData[visitUrl] += 1else:tempData[visitUrl] = 1dataLine = sFile.readline()#读入下一行数据sFile.close()tList = []for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):tList.append(key + " " + str(value) + '\n')tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + "_map.txt")tFile = open(tFilename, 'a+')#创建小文件tFile.writelines(tList)#将列表保存到文件中tFile.close()if __name__ == "__main__" :Map("access\\access.log1.txt","access")Map("access\\access.log2.txt","access")Map("access\\access.log3.txt","access")#coding:utf-8 #file: Rece.pyimport os,os.path,redef Rece(sourceFolder, targetFile):tempData = {}#缓存列表p_re = re.compile(r'(.*?)(\d{1,}$)',re.IGNORECASE) #用正则表达式解析数据for root,dirs,files in os.walk(sourceFolder):for fil in files:if fil.endswith('_map.txt'):#是rece文件sFile = open(os.path.abspath(os.path.join(root,fil)), 'r')dataLine = sFile.readline()while dataLine:#有数据subdata = p_re.findall(dataLine) #用空格分割数据#print(subdata[0][0]," ",subdata[0][1])if subdata[0][0] in tempData:tempData[subdata[0][0]] += int(subdata[0][1])else:tempData[subdata[0][0]] = int(subdata[0][1])dataLine = sFile.readline()#读入下一行数据sFile.close()tList = []for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):tList.append(key + " " + str(value) + '\n')tFilename = os.path.join(sourceFolder,targetFile + "_rece.txt")tFile = open(tFilename, 'a+')#创建小文件tFile.writelines(tList)#将列表保存到文件中tFile.close()if __name__ == "__main__" :Rece("access","access")

Ⅱ python的文件格式有两种,"*.py"和"*.pyw",它们有什么不同

它们之间的不同就只有一个:视窗运行它们的时候调用不同的执行档案。

视窗用 python.exe 运行 .py ,用 pythonw.exe 运行 .pyw 。

这纯粹是因为安装视窗版 Python 时,扩展名 .py 自动被登记为用 python.exe 运行的文件,而 .pyw 则被登记为用 pythonw.exe 运行。

主要体现在win平台上开发桌面程序,linux木有哦 python.exe 运行 .py ,用 pythonw.exe 运行 .pyw,不出现dos窗口, 住:纯图形界面程序的用户不需要看到dos窗口。

(2)py打的日志文件是什么格式的扩展阅读

Python open() 方法用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OSError。

注意:使用 open() 方法一定要保证关闭文件对象,即调用 close() 方法。

open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)。

完整的语法格式为:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Ⅲ .py是什么类型的文件

py:Python 的缩写,具有脚本语言中最丰富和强大的类库,足以支持绝大多数日常应用。在Symbina智能手机上支持C++和JAVA开发的两类程序, 装上Python后,也就可以支持众多以Python开发的各种程序了。以 .sh 为后缀的文件是Linux/Unix操作系统下的一种脚本文件。更多信息可以去看网络…

Ⅳ .py文件是什么

.py文件是python的脚本文件。

Python在执行时,首先会将.py文件中的源代码编译成Python的byte code(字节码),然后再由Python Virtual Machine(Python虚拟机)来执行这些编译好的byte code。这种机制的基本思想跟Java,.NET是一致的。

然而,Python Virtual Machine与Java或.NET的Virtual Machine不同的是,Python的Virtual Machine是一种更高级的Virtual Machine。

这里的高级并不是通常意义上的高级,不是说Python的Virtual Machine比Java或.NET的功能更强大,而是说和Java 或.NET相比,Python的Virtual Machine距离真实机器的距离更远。

或者可以这么说,Python的Virtual Machine是一种抽象层次更高的Virtual Machine。基于C的Python编译出的字节码文件,通常是.pyc格式。

(4)py打的日志文件是什么格式的扩展阅读:

python的优点:

1、简单:Python是一种代表简单主义思想的语言。阅读一个良好的Python程序就感觉像是在读英语一样。它使你能够专注于解决问题而不是去搞明白语言本身。

2、易学:Python极其容易上手,因为Python有极其简单的说明文档。

3、速度快:Python 的底层是用 C 语言写的,很多标准库和第三方库也都是用 C 写的,运行速度非常快。

4、免费、开源:Python是FLOSS(自由/开放源码软件)之一。使用者可以自由地发布这个软件的拷贝、阅读它的源代码、对它做改动、把它的一部分用于新的自由软件中。FLOSS是基于一个团体分享知识的概念。

5、高层语言:用Python语言编写程序的时候无需考虑诸如如何管理你的程序使用的内存一类的底层细节。

6、可移植性:由于它的开源本质,Python已经被移植在许多平台上(经过改动使它能够工作在不同平台上)。

7、解释性:一个用编译性语言比如C或C++写的程序可以从源文件(即C或C++语言)转换到一个你的计算机使用的语言(二进制代码,即0和1)。这个过程通过编译器和不同的标记、选项完成。

运行程序的时候,连接/转载器软件把你的程序从硬盘复制到内存中并且运行。而Python语言写的程序不需要编译成二进制代码。你可以直接从源代码运行 程序。

在计算机内部,Python解释器把源代码转换成称为字节码的中间形式,然后再把它翻译成计算机使用的机器语言并运行。这使得使用Python更加简单。也使得Python程序更加易于移植。

8、面向对象:Python既支持面向过程的编程也支持面向对象的编程。在“面向过程”的语言中,程序是由过程或仅仅是可重用代码的函数构建起来的。在“面向对象”的语言中,程序是由数据和功能组合而成的对象构建起来的。

9、可扩展性:如果需要一段关键代码运行得更快或者希望某些算法不公开,可以部分程序用C或C++编写,然后在Python程序中使用它们。

10、可嵌入性:可以把Python嵌入C/C++程序,从而向程序用户提供脚本功能。

11、丰富的库:Python标准库确实很庞大。它可以帮助处理各种工作,包括正则表达式、文档生成、单元测试、线程、数据库、网页浏览器、CGI、FTP、电子邮件、XML、XML-RPC、HTML、WAV文件、密码系统、GUI(图形用户界面)、Tk和其他与系统有关的操作。

12、规范的代码:Python采用强制缩进的方式使得代码具有较好可读性。而Python语言写的程序不需要编译成二进制代码。

Ⅳ Python语言扫描日志并统计

修复了一些小的拼写错误修复了出现无效数据行会出现错误的BUG修复了最小值统计方法的错误===================下面开始咯log.py========# -*- coding: cp936 -*-#上一句不可以删!表示中文路径是GBK编码importdatetime#处理时间的模块defsparse(target='log.txt') :tgfile = file(target,"r")event={}#event是一个字典,key是事件的编号,value是数据(可以利用嵌套来扩展数据)linelog = "Not Empty"whilelinelog: linelog = tgfile.readline()data = linelog.split('')#按空格将一行数据分为列表# printdata #testingiflen(data) > 4 : #有效的数据行time1 = data[2][1:] + '' + data[3][:-1]#将时间处理为(字符串):年-月-日 小时:分钟:秒time2 = datetime.datetime.strptime(time1,'%Y-%m-%d %H:%M:%S')#将时间识别为datetime类if data[5] == "begin:" and data[6][:2] == "OK" : #我不知道有没有 requestbegin: fail 这个东西,没有就把后半删掉吧!ifnotevent.has_key(data[0]) :#第一次发生某id的事件时初始化数据event[data[0]]=[[1,time2,0]]#我设置的value是一个列表,每个元素是一次记录,包括[是否没结束,开始时间,结束时间]。else :event[data[0]].append([1,time2,0])#已经有过记录了就在记录后加一条新记录ifdata[5] == "end:"anddata[6][:2] == "OK" :#我想应该没有不出现begin就直接end的事件吧……event[data[0]][-1][0]=0 #最后一条记录中写入:事件已经结束event[data[0]][-1][2]=time2 #最后一条记录写入:记录结束时间#如果还要处理其他的什么情形在这里添加if的判断tgfile.close()returneventdefanalysis(target='log.txt') :event = sparse(target) #调用上面定于的sparse方法。其实简单的处理用不着这么做的……单纯为了扩展性static = {}#用于统计结果的字典(其key和event中的key相同)foroneeventinevent :#每个事件的记录static[oneevent]=[0,0,0,0,-1]#初始化每个事件的统计:[成功发生次数,总发生次数,总发生时间,最大发生时间,最小发生时间]foronerecordinevent[oneevent] :#每个事件的一次记录static[oneevent][0] += 1 #总发生次数加一if onerecord[0] == 0 : #成功事件static[oneevent][1] += 1time_delta = onerecord[2] – onerecord[1]#计算结果是一个timedelta类型inttimedelta = time_delta.days *24*60*60 + time_delta.seconds#将时间差转化为以秒计算的整数if inttimedelta > static[oneevent][3] : static[oneevent][3] = inttimedelta #统计最大值if inttimedelta < static[oneevent][4] or static[oneevent][4] < 0 :static[oneevent][4] = inttimedelta #统计最小值static[oneevent][2] += inttimedeltareturn static ===================下面是log.txt===========#10.0.0.0[2007-06-1223:27:08]requestbegin:OK#30.0.0.0[2007-06-1223:28:08]requestbegin:fail#10.0.0.0[2007-06-1223:37:08]requestbegin:OK#10.0.0.0[2007-06-1223:37:18]requestforadata:OK#10.0.0.0[2007-06-1223:37:19]receivedsomedata:OK#10.0.0.0[2007-06-1300:27:08]requestend:OK#20.0.0.0[2007-06-1300:37:08]requestbegin:OK#20.0.0.0[2007-06-1300:47:08]requestend:OKsystemERROR:rebootAnother Invalid Line#10.0.0.0[2007-06-1323:28:18]requestbegin:OK#70.0.0.0[2007-06-1323:29:08]requestbegin:OK#70.0.0.0[2007-06-1323:30:18]requestend:OK#40.0.0.0[2007-06-1323:33:08]requestbegin:OK#40.0.0.0[2007-06-1323:35:23]requestend:OK#40.0.0.0[2007-06-1323:37:08]requestbegin:OK#40.0.0.0[2007-06-1323:43:38]requestend:OK#50.0.0.0[2007-06-1323:47:08]requestbegin:OK#10.0.0.0[2007-06-1323:57:48]requestbegin:OK#50.0.0.0[2007-06-1323:59:08]requestend:OK===================下面是使用和输出========importlogoutput = log.analysis()#或者直接log.analysis()=============输出============{'#2': [1, 1, 600, 600, 600], '#1': [4, 1, 3000, 3000, 3000], '#7': [1, 1, 70, 70, 70], '#5': [1, 1, 720, 720, 720], '#4': [2, 2, 525, 390, 135]}比如#1事件,总次数output['#1'][0]==4次成功次output['#1'][1]==1次失败次output['#1'][0]-output['#1'][1]==3次总时间output['#1'][2]==3000秒平均时间output['#1'][2]/output['#1'][1]==3000/1==3000秒最大时间output['#1'][3]==3000秒最小时间output['#1'][4]==3000秒共有len(output)==5种ID事件

Ⅵ 什么是日志文件

日志文件就是后缀为.log的文件。是由系统自动记录的关于系统、应用程序、安全等方面的正常或异常事件。属于文本类型的文件,但是,有一些日志文件并不能用记事本打开(打开后是乱码),有些日志文件可以用记事本打开

Ⅶ 大神们,当文件扩展名是“.py”的时候应该用什么应用程序打开呢

这要看这个文件是用什么软件创建的,请用创建这个文件的程序打开。

Ⅷ py文件是什么文件

.py文件是python脚本文件。 Python 是一种面向对象、解释型计算机程序设计语言。常用于各种服务器的维护和自动化运行。它具有丰富和强大的库。

Ⅸ python中log info 是什么文件

a. 利用sys.stdout将print行导向到你定义的日志文件中,例如:

import sys# make a of original stdout routestdout_backup = sys.stdout# define the log file that receives your log infolog_file = open("message.log", "w")# redirect print output to log filesys.stdout = log_fileprint "Now all print info will be written to message.log"# any command line that you will execute…log_file.close()# restore the output to initial patternsys.stdout = stdout_backupprint "Now this will be presented on screen"

b. 利用logging模块(规范化日志输出,推荐!!)由于logging模块的功能比较多,下面就放一些文档里介绍的简单的例子,更详细具体的用法请戳这里

需求

最好的实现方式

故障调查或者状态监测 logging.info()或logging.debug()(后者常用于针对性检测诊断的目的)

特定运行事件发出警告 logging.warning()

报告错误抑制不出发异常(常见于长时间运行的服务器进程的错误处理程序) logging.error(), logging.exception()或者logging.critical()

而以下是根据事件的严重性程度而应采取的logging函数的建议:

程度

使用场景

DEBUG 获得诊断问题是具体的信息

INFO 确认程序是否按正常工作

WARNING 在程序还正常运行时获取发生的意外的信息,这可能会在之后引发异常(例如磁盘空间不足)

ERROR 获取程序某些功能无法正常调用这类严重异常的信息

CRITICAL 获取程序无法继续运行的这类最严重异常信息

默认的等级是WARNING,也就是说logging函数在没有特别配置的前提下只追踪比WARNING程度更严重的异常。

下面就用一些例子来具体说明如何用logging函数记录日志信息:

# this is a simple exampleimport logging# define the log file, file mode and logging levellogging.basicConfig(filename='example.log', filemode="w", level=logging.DEBUG)logging.debug('This message should go to the log file')logging.info('So should this')logging.warning('And this, too')

查看example.log文件可以看到以下信息:

DEBUG:root:This message should go to the log fileINFO:root:So should thisWARNING:root:And this, too

从多个文件记录日志

# myapp.pyimport loggingimport mylibdef main():logging.basicConfig(filename='myapp.log', level=logging.INFO)logging.info('Started')mylib.do_something()logging.info('Finished')if __name__ == '__main__':main()# mylib.pyimport loggingdef do_something():logging.info('Doing something')

输出的信息为

INFO:root:StartedINFO:root:Doing somethingINFO:root:Finished

改变默认输出信息的格式

import logging# output format: output time – logging level – log messageslogging.basicConfig(format='%(asctime)s – %(levelname)s – %(message)s')logging.warning('This message will appear in python console.')

在python console中直接打印以下输出:

2016-8-2 2:59:11, 510 – WARNING – This message will appear in python console

logging高级用法可以通过构建logger或者读取logging config文件对logging函数进行任意配置。

构建logger法

import logging# create loggerlogger = logging.getLogger('simple_example')logger.setLevel(logging.DEBUG)# create console handler and set level to debugch = logging.StreamHandler()ch.setLevel(logging.DEBUG)# create formatterformatter = logging.Formatter('%(asctime)s – %(name)s – %(levelname)s – %(message)s')# add formatter to chch.setFormatter(formatter)# add ch to loggerlogger.addHandler(ch)# 'application' codelogger.debug('debug message')logger.info('info message')logger.warn('warn message')logger.error('error message')logger.critical('critical message')

以上程序结果会输出到python console中:

$ python simple_logging_mole.py2005-03-19 15:10:26,618 – simple_example – DEBUG – debug message2005-03-19 15:10:26,620 – simple_example – INFO – info message2005-03-19 15:10:26,695 – simple_example – WARNING – warn message2005-03-19 15:10:26,697 – simple_example – ERROR – error message2005-03-19 15:10:26,773 – simple_example – CRITICAL – critical message

读取配置文件法

import loggingimport logging.configlogging.config.fileConfig('logging.conf')# create loggerlogger = logging.getLogger('simpleExample')# 'application' codelogger.debug('debug message')logger.info('info message')logger.warn('warn message')logger.error('error message')logger.critical('critical message')

其中logging.conf文件格式为:(其实就是将前一种方法的各项配置参数写到logging.conf文件中)

[loggers]keys=root,simpleExample[handlers]keys=consoleHandler[formatters]keys=simpleFormatter[logger_root]level=DEBUGhandlers=consoleHandler[logger_simpleExample]level=DEBUGhandlers=consoleHandlerqualname=simpleExamplepropagate=0[handler_consoleHandler]class=StreamHandlerlevel=DEBUGformatter=simpleFormatterargs=(sys.stdout,)[formatter_simpleFormatter]format=%(asctime)s – %(name)s – %(levelname)s – %(message)sdatefmt= '%m/%d/%Y %I:%M:%S %p'

与前面一样,上述文件输出结果为:

$ python simple_logging_config.py2005-03-19 15:38:55,977 – simpleExample – DEBUG – debug message2005-03-19 15:38:55,979 – simpleExample – INFO – info message2005-03-19 15:38:56,054 – simpleExample – WARNING – warn message2005-03-19 15:38:56,055 – simpleExample – ERROR – error message2005-03-19 15:38:56,130 – simpleExample – CRITICAL – critical message

Ⅹ python 读取日志文件

#-*-coding:utf-8-*-withopen('log.txt','r')asf:foriinf:ifdt.strftime(dt.now(),'%Y-%m-%d')ini:#判断是否当天时间if'ERROR'iniand'atcom.mytijian'ini:#判断此行中是否含有'ERROR'及'atcom.mytijian'if((dt.now()-dt.strptime(i.split(',')[0],'%Y-%m-%d%H:%M:%S')).seconds)<45*60:#判断时间是为当前45分钟内printi

未经允许不得转载:山九号 » py打的日志文件是什么格式的|大神们当文件扩展名是“py”的时候应该用什么应用程序打开呢

赞 (0)