This post was updated 772 days ago and some of the ideas may be out of date.

用traceback模块打印

try:
    socket.setdefaulttimeout(10)
    obj = socket.socket()
    obj.connect(('***', 80))
    obj.close()
    return {'open': True}
except Exception as e:
    traceback.print_exc()
    return {'open': False}

以上代码结果为:

Traceback (most recent call last):
  File "F:\Projects\PythonProjects\xxx\main.py", line 84, in ping
    obj.connect(('***', 80))
ConnectionRefusedError: [WinError 10061] 由于目标计算机积极拒绝,无法连接。

PS:上述traceback.print_exc()是直接打印错误

还可以用traceback.format_exc()返回字符串,可将错误信息保存在文档日志中

可以说traceback.print_exc()等同于print(traceback.format_exc())