在python中获取execption

时间:2016-06-17 17:04:37

标签: python-2.7 exception-handling

我在python中有一个简短的脚本,我需要获取execption,但只有一个valueError而不是完整的内容。我用代码解释:

try:
   r = str(ML_engine.Create_ML_Alg_Python(sc, m))
   ML_engine.updateModel('success',r,m)
   return r
except Exception as inst:
   ML_engine.updateModel(str(inst), -200, m)
   return str(inst)

发生异常时,在python控制台视图中:

File "/home/sm/spark-1.6.1-bin-hadoop2.6/spark-1.6.1-bin hadoop2.6/spark-1.6.1-bin-hadoop2.6/python/lib/pyspark.zip/pyspark/worker.py", line 106, in process
serializer.dump_stream(func(split_index, iterator), outfile)
File "/home/sm/spark-1.6.1-bin-hadoop2.6/spark-1.6.1-bin-hadoop2.6/spark-1.6.1-bin-hadoop2.6/python/lib/pyspark.zip/pyspark/serializers.py", line 263, in dump_stream
vs = list(itertools.islice(iterator, batch))
File "/usr/local/lib/python2.7/dist-packages/spark_sklearn/grid_search.py", line 228, in fun
return_parameters=True, error_score=error_score)
File "/usr/local/lib/python2.7/dist-packages/sklearn/cross_validation.py", line 1524, in _fit_and_score
X_train, y_train = _safe_split(estimator, X, y, train)
File "/usr/local/lib/python2.7/dist-packages/sklearn/cross_validation.py", line 1585, in _safe_split

ValueError: X should be a square kernel matrix

我只需要ValueError

2 个答案:

答案 0 :(得分:0)

我想你要说的是你只需要错误名称。因此,针对该案例的最佳解决方案是使用 sys.exc_info()。 请参阅:https://docs.python.org/2/library/sys.html

答案 1 :(得分:0)

type(inst).__name__将帮助您获取错误类型名称。像这样:

try:
    a = float('a')
except Exception as e:
    print type(e).__name__

将打印ValueError

str(inst)inst.message会告诉您错误消息(总是为我工作。但如果消息未设置,那么您需要找到另一种方法)。