0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pythonのエラーを見やすくする試み

Last updated at Posted at 2024-01-08

概要

cloudのpythonコードのエラーログが見にくかったので少し見やすくなるかもと思って、一肌脱いでキレイする関数作りました。
そのままのトレースバックでも良かった感が否めないですが一応少しは見やすくなった?ので共有です。

表示例

トレースバックのエラー文をコピペするとこんな感じで、重要なエラークラスと関数などを1行づつに分けたデータフレームにします。
image.png

コード

import re
import pandas as pd

def show_traceback(tb: str):
  tb = re.sub(r"Traceback.*:\n", "", tb)
  error_msg = [t for t in tb.split("\n") if t][-1]
  error_res_tb = tb.replace(error_msg, "")
  simple_tb = [re.sub(r"^ +", "", t) for t in error_res_tb.split("\n") if t]

  tb_evens = [t for idx, t in enumerate(simple_tb) if idx % 2 == 0]
  tb_odds = [t for idx, t in enumerate(simple_tb) if idx % 2 == 1]

  tb_list = []
  for e, o in zip(tb_evens, tb_odds):
    e_splits = e.split(",")
    tb_list.append({
      "file": e_splits[0].replace("File ", ""),
      "line": e_splits[1].replace(" line ", ""),
      "func": e_splits[2].replace(" in ", ""),
      "syntax": o,
    })
  df = pd.DataFrame(tb_list)
  df.to_csv("./check_traceback/tb.csv", index=False)
  print("-"*20)
  print(error_msg)
  print("-"*20)
  display(df)

関数呼び出し例

空白とかは何行でも入っても大丈夫ですが、トレースバックの内容をいじるとsplitする所とかでズレてバグるかもしれないですw

tb = """

Traceback (most recent call last):
  File "/code/./main.py", line 99, in accepted
    redirect_url = class_obj(state=state, code=code).main()
  File "/code/./processor/socket_connected_response.py", line 84, in main
    self.save_firebase(token_dict)
  File "/code/./processor/socket_connected_response.py", line 49, in save_firebase
    accounts_ref.set(accounts_fields["elp_id"], merge=True)
  File "/usr/local/lib/python3.8/site-packages/google/cloud/firestore_v1/document.py", line 166, in set
    batch, kwargs = self._prep_set(document_data, merge, retry, timeout)
  File "/usr/local/lib/python3.8/site-packages/google/cloud/firestore_v1/base_document.py", line 217, in _prep_set
    batch.set(self, document_data, merge=merge)
  File "/usr/local/lib/python3.8/site-packages/google/cloud/firestore_v1/base_batch.py", line 107, in set
    write_pbs = _helpers.pbs_for_set_with_merge(
  File "/usr/local/lib/python3.8/site-packages/google/cloud/firestore_v1/_helpers.py", line 858, in pbs_for_set_with_merge
    extractor = DocumentExtractorForMerge(document_data)
  File "/usr/local/lib/python3.8/site-packages/google/cloud/firestore_v1/_helpers.py", line 723, in __init__
    super(DocumentExtractorForMerge, self).__init__(document_data)
  File "/usr/local/lib/python3.8/site-packages/google/cloud/firestore_v1/_helpers.py", line 504, in __init__
    for field_path, value in iterator:
  File "/usr/local/lib/python3.8/site-packages/google/cloud/firestore_v1/_helpers.py", line 442, in extract_fields
    for key, value in sorted(document_data.items()):
AttributeError: 'str' object has no attribute 'items'

""".strip()

show_traceback(tb)

同じファイルを上書きするようになっているので、vscodeでjupyter使ってる人は、拡張機能の「Edit csv」を入れるとcsvファイルとして表示して確認することもできます

image.png

肝心なデータフレームのアウトプットがちょっと見づらくて残念なので見やすいデータフレームのアウトプット方法をご存知の方いらっしゃれば共有していただきたいです^^

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?