python:如何在我的代码发出最后一个错误之前起床

python:如何在我的代码发出最后一个错误之前起床,第1张

概述所以当我运行这个…错误就在这行炸d= pd.DataFrame(这里,0)但是跟踪显示了一堆来自pandas库的代码来获取错误. import traceback,sysimport pandas as pd def error_handle(err_var,instance_name=None): #err_var list of variables, instance_na 所以当我运行这个…错误就在这行炸d= pd.DataFrame(这里,0)但是跟踪显示了一堆来自pandas库的代码来获取错误.
import traceback,sysimport pandas as pd        def error_handle(err_var,instance_name=None): #err_var List of variables,instance_name    print(traceback.format_exc())    a= sys._getframe(1).f_locals    for i in err_var: # selected var for instance        t= a[instance_name]        print i,"--->",getattr(t,i.split(".")[1])here=['foo']err_var = ['self.needthisone','self.constant2']class test:    def __init__(self):        self.constant1 = 'hi1'        #self.constant2 = 'hi2'        #self.needthisone = ':)'        for i in err_var:            setattr(self,i.split('.')[1],None)    def other_function(self):        self.other_var=5    def testing(self):        self.other_function()        vars=[self.constant1,self.constant2]        try:            for i in vars:                 bomb=pd.DataFrame(here,0)        except:            error_handle(err_var,'self')t=test()t.testing()

如何抑制所有这些并使错误看起来像这样:

Traceback (most recent call last):  file "C:\Users\Jason\Google Drive\python\error_handling.py",line 34,in testing    bomb=pd.DataFrame(here,0)TypeError: Index(...) must be called with a collection of some kind,0 was passed

我只想知道与我相关的内容以及我编写的最后一行代码,这些代码很糟糕.

这是原作:

Traceback (most recent call last):  file "C:\Users\Jason\Google Drive\python\error_handling.py",line 35,0)  file "C:\Python27\lib\site-packages\pandas\core\frame.py",line 330,in __init__    copy=copy)  file "C:\Python27\lib\site-packages\pandas\core\frame.py",line 474,in _init_ndarray    index,columns = _get_axes(*values.shape)  file "C:\Python27\lib\site-packages\pandas\core\frame.py",line 436,in _get_axes    index = _ensure_index(index)  file "C:\Python27\lib\site-packages\pandas\core\indexes\base.py",line 3978,in _ensure_index    return Index(index_like)  file "C:\Python27\lib\site-packages\pandas\core\indexes\base.py",line 326,in __new__    cls._scalar_data_error(data)  file "C:\Python27\lib\site-packages\pandas\core\indexes\base.py",line 678,in _scalar_data_error    repr(data)))TypeError: Index(...) must be called with a collection of some kind,0 was passedself.needthisone ---> Noneself.constant2 ---> None
解决方法 我强烈建议你不要限制你的追溯输出,因为这是不好的做法.你觉得有太多的信息;但这只是因为你已经看过它而且你知道要查找什么错误.

在大多数情况下,问题可能隐藏在其他地方.因此,必须有更好的方法来实现您的目标.

为什么不在try except子句中包装函数调用并打印异常消息?以此方案为例:

def f():    a = 0    i = 1    print i/adef another_func():    print 'this is another func'    return f()def higher_level_func():    print 'this is higher level'    return another_func()if __name__ == '__main__':    try:        higher_level_func()    except Exception as e:        print 'caught the exception: {}-{}'.format(type(e)__name__,e.message)

调用时,这是输出:

this is higher levelthis is another funccaught the exception: ZerodivisionError-integer division or modulo by zero

这会在代码中仅打印相关的异常,隐藏有关回溯的任何信息,但回溯仍然可用,您也可以打印它(只需从except块中引发异常).

与此相比,如果我删除try除块:

this is higher levelthis is another funccaught the exception: integer division or modulo by zeroTraceback (most recent call last):  file "test.py",line 17,in <module>    higher_level_func()  file "test.py",line 12,in higher_level_func    return another_func()  file "test.py",line 8,in another_func    return f()  file "test.py",line 4,in f    print i/aZerodivisionError: integer division or modulo by zero

您最好使用此技术捕获相关异常,而不是限制回溯.如果希望程序停止,只需在except块中添加sys.exit(1)即可.

总结

以上是内存溢出为你收集整理的python:如何在我的代码发出最后一个错误之前起床全部内容,希望文章能够帮你解决python:如何在我的代码发出最后一个错误之前起床所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1206689.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存