jas*_*son 6 python error-handling
所以,当我运行这个...错误是在这一行,bomb=pd.DataFrame(here,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()
Run Code Online (Sandbox Code Playgroud)
如何抑制所有这些并使错误看起来像这样:
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
Run Code Online (Sandbox Code Playgroud)
我只想知道与我相关的内容以及我编写的最后一行代码,这些代码很糟糕.
这是原作:
Traceback (most recent call last):
File "C:\Users\Jason\Google Drive\python\error_handling.py", line 35, in testing
bomb=pd.DataFrame(here,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
Run Code Online (Sandbox Code Playgroud)
我强烈建议您不要限制回溯输出,因为这是不好的做法。你感觉信息太多;但这只是因为您已经看过它并且知道要查找什么错误。
在大多数情况下,问题可能隐藏在其他地方。因此,必须有一种更好的方法来实现您所寻求的目标。
为什么不将函数调用包装在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)
Run Code Online (Sandbox Code Playgroud)
调用时,输出如下:
this is higher level
this is another func
caught the exception: ZeroDivisionError-integer division or modulo by zero
Run Code Online (Sandbox Code Playgroud)
这仅打印代码中的相关异常,隐藏有关回溯的任何信息,但回溯仍然可用,您也可以打印它(只需从 except 块中引发异常)。
与此相比,如果我删除该try except块:
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
Run Code Online (Sandbox Code Playgroud)
您最好使用此技术来捕获相关异常,而不是限制回溯。如果您希望程序停止,只需添加sys.exit(1)该except块即可。
| 归档时间: |
|
| 查看次数: |
170 次 |
| 最近记录: |