【问题标题】:How to return error line in a given file path for python?python - 如何在给定文件路径中为python返回错误行?
【发布时间】:2018-12-20 12:26:22
【问题描述】:

我希望File1.py 返回File2.py 中的错误行

文件1.py:

def find_errors(file_path_of_File2):
    print(f'the error is on line {}')

错误在第 2 行

文件2.py:

print('this is line 1')
print(5/0)

ZeroDivisionError: 整数除以零或取模

这可能吗?

【问题讨论】:

  • 不可能:ZeroDivisionError 是运行时错误,而不是编译时错误。知道它会被引发的唯一方法是执行代码,然后看到它被引发。
  • 如果我通过 File1.py 执行 File2.py 并保存 File2.py 的输出(导致错误),然后在 File1.py 中返回该错误行,会有什么问题?
  • file2和file1是怎么连接的。你能发布完整的例子吗
  • @Arseniy 它们是 2 个单独的文件。 File2.py 可以通过 File1.py 访问,如下所示:stackoverflow.com/questions/1186789/…

标签: python


【解决方案1】:

你可以用traceback module 做一些丑陋的事情。

File1.py

print('this is line 1')
print(5/0)

文件2.py

import sys
import traceback
try:
    import test
except Exception as e:
    (exc_type, exc_value, exc_traceback) = sys.exc_info()
    trace_back = [traceback.extract_tb(sys.exc_info()[2])[-1]][0]
    print("Exception {} is on line {}".format(exc_type, trace_back[1]))

输出

this is line 1
Exception <type 'exceptions.ZeroDivisionError'> is on line 2

在这种情况下,您将捕获在导入文件期间引发的所有异常,然后您将从trace_back 中获取最后一个异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 2019-02-01
    • 2014-02-07
    • 1970-01-01
    相关资源
    最近更新 更多