加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 23:05:08 所属栏目:Python 来源:网络整理
导读:所以当我运行这个…错误就在这行炸弹= 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(tr
所以当我运行这个…错误就在这行炸弹= pd.DataFrame(这里,0)但是跟踪显示了一堆来自pandas库的代码来获取错误.
import traceback,sys
import 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:UsersJasonGoogle Drivepythonerror_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:UsersJasonGoogle Drivepythonerror_handling.py",line 35,0)
  File "C:Python27libsite-packagespandascoreframe.py",line 330,in __init__
    copy=copy)
  File "C:Python27libsite-packagespandascoreframe.py",line 474,in _init_ndarray
    index,columns = _get_axes(*values.shape)
  File "C:Python27libsite-packagespandascoreframe.py",line 436,in _get_axes
    index = _ensure_index(index)
  File "C:Python27libsite-packagespandascoreindexesbase.py",line 3978,in _ensure_index
    return Index(index_like)
  File "C:Python27libsite-packagespandascoreindexesbase.py",line 326,in __new__
    cls._scalar_data_error(data)
  File "C:Python27libsite-packagespandascoreindexesbase.py",line 678,in _scalar_data_error
    repr(data)))
TypeError: Index(...) must be called with a collection of some kind,0 was passed

self.needthisone ---> None
self.constant2 ---> None

解决方法

我强烈建议你不要限制你的追溯输出,因为这是不好的做法.你觉得有太多的信息;但这只是因为你已经看过它而且你知道要查找什么错误.

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

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

def f():
    a = 0
    i = 1
    print i/a

def 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 level
this is another func
caught the exception: ZeroDivisionError-integer division or modulo by zero

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

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

this is higher level
this is another func
caught the exception: integer division or modulo by zero
Traceback (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/a
ZeroDivisionError: integer division or modulo by zero

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读