您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:22:21 python 字数 5519 阅读 534 来源 www.jb51.cc/python

所以当我运行这个…错误就在这行炸弹= 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_na

概述

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:\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 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)即可.

总结

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


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶