python - 类格式问题

标签 python class formatting python-2.7

我是一个Python新手程序员。我目前正在构建一个解析日志文件的类,并已完成该类的所有元素。尽管如此,由于 python 中的大多数内容对我来说都已经过去了,所以我要么错误地格式化了我的类,要么搞砸了我的语义。我想知道是否存在构建类的明确格式以及我编写的格式是否遵循所述格式。

以下是日志中的一些行:

2012-06-12 14:02:21,813 [main]  INFO  ConnectionManager.java (line 238) Initializing the ConnectionManager.
2012-06-12 14:02:21,844 [main]  INFO  CimListener.java (line 142) Starting listener at http://127.0.0.1:7012
2012-06-12 14:02:21,974 [main]  INFO  CimListener.java (line 158) Listening at http://127.0.0.1:7012
2012-06-12 14:02:23,209 [main]  INFO  RmiServiceExporter.java (line 393) Looking for RMI registry at port '10099'
2012-06-12 14:02:23,232 [main]  INFO  RmiServiceExporter.java (line 404) Could not detect RMI registry - creating new one

这是类(class):

import re
import time
import calendar
from datetime import datetime

f = open("C:\Users\-----\Desktop\Real Logs\controllersvc.log", "r")
while True:
    line = f.readline()
    if not line:
        break

class LogLine:

    SEVERITIES = ['EMERG','ALERT','CRIT','ERR','WARNING','NOTICE','INFO','DEBUG']
    severity = 1


    def __init__(self, line):
        try:
            timestr, msstr, sevstr, self.filename, linestr, self.message = re.match(r"^(\d\d\d\d-\d\d-\d\d[ \t]\d\d:\d\d:\d\d),(\d\d\d),(?i[a-z]+),([A-Za-z]{1,.}),([(]\[lL]ine\>\s+\d+[)]),^(?<=\)\s?\w+$)", line).groups()
            self.line = int(linestr)
            self.sev = self.SEVERITIES.index(sevstr)
            self.time = float(calendar.timegm(time.strptime(timestr, "%Y-%m-%d %H:%M:%S,%f"))) + float(msstr)/1000.0
            dt = datetime.strptime(t, "%Y-%m-%d %H:%M:%S,%f")
        except Exception:
            print 'error',self.filename

    def get_time(self):
        return self.time
    def get_severity(self):
        return self.sev
    def get_message(self):
        return message
    def get_filename(self):
        return filename
    def get_line(self):
        return line

最佳答案

您的代码有几个问题:

  • self.filename 属性在 init 中使用之前不一定要定义
  • 您应该尝试更具体地说明您希望捕获哪些异常(您想禁止 KeyboardInterruptException 吗?)
  • 您的正则表达式很复杂且难以维护(我认为是错误的)
  • 您将“getter”暴露给对象的公共(public)属性,但这是不必要的。
  • 一些“getters”返回全局变量(消息、行和文件名),这些变量可能是为了返回实例属性
  • 新编写的类最好应该对某些内容进行子类化(在本例中为object)

我希望这份 list 有帮助,并被视为建设性的批评。

为了帮助您查看更多 Python 代码,我为您的数据编写了一个日志阅读器,它没有复杂的正则表达式,也没有任何“getters”(如果您确实愿意,可以添加)。人们还可以进行进一步的简化(例如使用namedtuple),但为了清晰起见和教育目的,我保留了普通内容:

import datetime


class LogEntry(object):
    @staticmethod
    def from_str(line):
        """Converts a log line in a string, into a LogEntry."""
        # split the line by one or more spaces
        date, time, _, severity, filename, _, line, message = re.split('\s+', line, 7)

        # strip the trailing bracket on the line and cast to an int
        line = int(line[:-1])

        # combine the date and time strings and turn them into a datetime
        dt = datetime.datetime.strptime(date + time, "%Y-%m-%d%H:%M:%S,%f")

        return LogEntry(dt, severity, filename, line, message)

    def __init__(self, dt, severity, filename, line_num, message):
        self.datetime = dt
        self.severity = severity
        self.filename = filename
        self.line_num = line_num
        self.message = message

    def __str__(self):
        return '%s %s %s L%s: %s' % (self.datetime, self.severity, self.filename, self.line_num, self.message)


if __name__ == '__main__':

    log_contents = """2012-06-12 14:02:21,813 [main]  INFO  ConnectionManager.java (line 238) Initializing the ConnectionManager.
    2012-06-12 14:02:21,844 [main]  INFO  CimListener.java (line 142) Starting listener at http://127.0.0.1:7012
    2012-06-12 14:02:21,974 [main]  INFO  CimListener.java (line 158) Listening at http://127.0.0.1:7012
    2012-06-12 14:02:23,209 [main]  INFO  RmiServiceExporter.java (line 393) Looking for RMI registry at port '10099'
    2012-06-12 14:02:23,232 [main]  INFO  RmiServiceExporter.java (line 404) Could not detect RMI registry - creating new one"""

    # uncomment for real log reading
    #fh = file(filename, 'r')

    # emulate a log file by providing an iterable of lines (just like fh will do)
    fh = log_contents.split('\n')

    for line in fh:
        print LogEntry.from_str(line.strip())

产生输出:

2012-06-12 14:02:21.813000 INFO ConnectionManager.java L238: Initializing the ConnectionManager.
2012-06-12 14:02:21.844000 INFO CimListener.java L142: Starting listener at http://127.0.0.1:7012
2012-06-12 14:02:21.974000 INFO CimListener.java L158: Listening at http://127.0.0.1:7012
2012-06-12 14:02:23.209000 INFO RmiServiceExporter.java L393: Looking for RMI registry at port '10099'
2012-06-12 14:02:23.232000 INFO RmiServiceExporter.java L404: Could not detect RMI registry - creating new one

我真的希望这能帮助您发现 Python 的乐趣!

关于python - 类格式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11635602/

相关文章:

php - 从 PHP 类中的数据库中获取数据

python - 如何在 Python 中检查字符串是否具有格式参数?

python - 检查文件系统是否支持硬链接(hard link)

python - 条目小部件内容不随函数调用而改变

Python - 为什么 __str__ 在调用时想要返回一些东西?我在 __str__ 中有打印函数

Python类实例化: What does it mean when a class is called without accompanying arguments?

python - 从 conda 环境导出顶级依赖项,包括 pip 安装

python - 使用 Python 多处理管理器 (BaseManager/SyncManager) 与远程机器共享队列时管道损坏

c - 如何将整数转换为 uint8_t 指针?

ruby-on-rails - number_with_precision 带连字符的格式化数字