python - linecache.getline() 什么都不返回

标签 python python-2.7

我有一个函数可以放入 tryexcept 部分,我希望它记录错误信息。问题是我无法像以前那样获取产生错误的代码行。看看这段代码:

def func():
    try:
        a = 1
        b = 0
        print a / b
    except:
        Debug.log()

这是日志函数:

def log(cls):
    try:
        exc_type, exc_obj, tb = sys.exc_info()
        f = tb.tb_frame
        line_no = str(tb.tb_lineno)
        filename = f.f_code.co_filename
        linecache.checkcache(filename)
        line = linecache.getline(filename, line_no, f.f_globals)
        current_frame = inspect.currentframe()
        previous_frame = current_frame.f_back
        func_name = previous_frame.f_code.co_name
        msg = str(exc_obj)

        obj = Error()
        obj.filename = filename
        obj.line_no = line_no
        obj.line = line
        obj.msg = msg
        obj.function = func_name
        obj.save()

执行后我可以看到该行是空的:

{
    "_id" : ObjectId("5413d67a65765f16219aa575"),
    "filename" : "E:/Developer Center/DomainServices/DomainServices/test.py",
    "line_no" : "23",
    "line" : "",
    "msg" : "integer division or modulo by zero",
    "function" : "func",
}

怎么了?

最佳答案

代码将 str 对象传递给 linecache.getline

line_no = str(tb.tb_lineno)
          ^^^

根据 linecache.py source code ,传递的行号与 1 和总行数进行比较:

    if 1 <= lineno <= len(lines):
        return lines[lineno-1]
    else:
        return ''

因为 linenostr 对象,谓词在 Python 2.x 中被评估为 False(在 Python 3 中引发异常。 x 因为不允许比较 strint)

>>> 1 < '2' < 3
False

你得到一个空字符串。


您应该传递一个 int 对象。

line = linecache.getline(filename, int(line_no))

line = linecache.getline(filename, tb.tb_lineno)

关于python - linecache.getline() 什么都不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25820217/

相关文章:

python-2.7 - 使用 Python 中的 YouTube Data API v3 将视频上传到 YouTube 并将其添加到播放列表

python - python 在 for 循环中效率低得令人难以置信,还是只是我的代码?

python - 在 Azure Web 应用程序中安装 psycopg2

python - 我正在使用 pypyodbc.connect - 有没有办法给它一个应用程序名称?

django - Python-Django : Streaming video/mp4 file using HttpResponse

python - 如何从版本号字符串中删除 "leading"零?

python - 用于安装 Tensorflow 的虚拟环境 : Why Do I need it for Whiich Purpose?

python - 大写连字符名称

python - 不使用pygrib包读取grib2格式数据

python - 为什么 SO_REUSEADDR 不适用于 multiprocessing.Listener?