如何在Python中只打印错误信息而不打印回溯的选项

438 阅读2分钟

在这个简短的指南中,我将向你展示几种在Python中只打印错误信息而不打印回溯的选项。

这对于演示或当你有不需要的极长的信息时非常有用。

选项1:用SystemExit(err)打印没有回溯的错误信息

我们将使用的第一个选项是:SystemExit(err)

我们将捕获任何异常并处理它。然后我们将只打印出错误信息。

要想只显示错误信息,请使用下面的语法:

try:
    
    pd.to_datetime(df['date'])
    
except Exception as err:
    raise SystemExit(err)

result:

An exception has occurred, use %tb to see the full traceback.

SystemExit: Out of bounds nanosecond timestamp: 1-06-13 00:00:00

默认情况下,下面的代码

import pandas as pd
pd.to_datetime(df['date'])

会产生很长的错误信息:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/myuser/Software/Tensorflow/environments/venv36/lib/python3.6/site-packages/pandas/core/arrays/datetimes.py in objects_to_datetime64ns(data, dayfirst, yearfirst, utc, errors, require_iso8601, allow_object)
   2058         try:
-> 2059             values, tz_parsed = conversion.datetime_to_datetime64(data)
   2060             # If tzaware, these values represent unix timestamps, so we

pandas/_libs/tslibs/conversion.pyx in pandas._libs.tslibs.conversion.datetime_to_datetime64()

TypeError: Unrecognized value type: <class 'str'>

During handling of the above exception, another exception occurred:

OutOfBoundsDatetime                       Traceback (most recent call last)
<ipython-input-20-6dea9b57a428> in <module>()
----> 1 pd.to_datetime(df['date'])

/home/myuser/Software/Tensorflow/environments/venv36/lib/python3.6/site-packages/pandas/core/tools/datetimes.py in to_datetime(arg, errors, dayfirst, yearfirst, utc, format, exact, unit, infer_datetime_format, origin, cache)
    801             result = arg.map(cache_array)
    802         else:
--> 803             values = convert_listlike(arg._values, format)
    804             result = arg._constructor(values, index=arg.index, name=arg.name)
    805     elif isinstance(arg, (ABCDataFrame, abc.MutableMapping)):

/home/myuser/Software/Tensorflow/environments/venv36/lib/python3.6/site-packages/pandas/core/tools/datetimes.py in _convert_listlike_datetimes(arg, format, name, tz, unit, errors, infer_datetime_format, dayfirst, yearfirst, exact)
    464             errors=errors,
    465             require_iso8601=require_iso8601,
--> 466             allow_object=True,
    467         )
    468

/home/myuser/Software/Tensorflow/environments/venv36/lib/python3.6/site-packages/pandas/core/arrays/datetimes.py in objects_to_datetime64ns(data, dayfirst, yearfirst, utc, errors, require_iso8601, allow_object)
   2062             return values.view("i8"), tz_parsed
   2063         except (ValueError, TypeError):
-> 2064             raise e
   2065
   2066     if tz_parsed is not None:

/home/myuser/Software/Tensorflow/environments/venv36/lib/python3.6/site-packages/pandas/core/arrays/datetimes.py in objects_to_datetime64ns(data, dayfirst, yearfirst, utc, errors, require_iso8601, allow_object)
   2053             dayfirst=dayfirst,
   2054             yearfirst=yearfirst,
-> 2055             require_iso8601=require_iso8601,
   2056         )
   2057     except ValueError as e:

pandas/_libs/tslib.pyx in pandas._libs.tslib.array_to_datetime()

pandas/_libs/tslib.pyx in pandas._libs.tslib.array_to_datetime()

pandas/_libs/tslib.pyx in pandas._libs.tslib.array_to_datetime()

pandas/_libs/tslib.pyx in pandas._libs.tslib.array_to_datetime()

pandas/_libs/tslibs/conversion.pyx in pandas._libs.tslibs.conversion.convert_datetime_to_tsobject()

pandas/_libs/tslibs/np_datetime.pyx in pandas._libs.tslibs.np_datetime.check_dts_bounds()

OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1-06-13 00:00:00

选项2:用traceback.print_exc(limit=1)打印没有跟踪的错误信息

还有一个替代方案是使用traceback.print_exc(limit=1) ,其用法如下:

import pandas as pd
import traceback

try:
    
    pd.to_datetime('Jun 1, 1111')

except Exception as e:
    traceback.print_exc(limit=1)
    exit(1)

结果错误将是:

Traceback (most recent call last):
  File "/home/vanx/Software/Tensorflow/environments/venv36/lib/python3.6/site-packages/pandas/core/arrays/datetimes.py", line 2059, in objects_to_datetime64ns
    values, tz_parsed = conversion.datetime_to_datetime64(data)
TypeError: Unrecognized value type: <class 'str'>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<ipython-input-22-ee6c6bd48a55>", line 5, in <module>
    pd.to_datetime('Jun 1, 1111')
pandas._libs.tslibs.np_datetime.OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1111-06-01 00:00:00

选项3:用sys.trackbacklimit打印没有回溯的错误信息

最后,你可以通过以下方式减少回溯的限制。sys.tracebacklimit.

要设置回溯的最低水平,请使用:

import sys

sys.tracebacklimit = 0