|
| 1 | +from pathlib import Path |
| 2 | +import pdb |
| 3 | +import sys |
| 4 | + |
| 5 | +from IPython.core import ultratb |
| 6 | +import click |
| 7 | +import cloudpickle as cp |
| 8 | + |
| 9 | +CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"]) |
| 10 | +ExistingFilePath = click.Path(exists=True, dir_okay=False, resolve_path=True) |
| 11 | + |
| 12 | + |
| 13 | +@click.group(context_settings=CONTEXT_SETTINGS) |
| 14 | +def cli(): |
| 15 | + pass |
| 16 | + |
| 17 | + |
| 18 | +@cli.command(context_settings=CONTEXT_SETTINGS) |
| 19 | +@click.argument("crashfile", type=ExistingFilePath) |
| 20 | +@click.option( |
| 21 | + "-r", "--rerun", is_flag=True, flag_value=True, help="Rerun crashed code." |
| 22 | +) |
| 23 | +@click.option( |
| 24 | + "-d", |
| 25 | + "--debugger", |
| 26 | + type=click.Choice([None, "ipython", "pdb"]), |
| 27 | + help="Debugger to use when rerunning", |
| 28 | +) |
| 29 | +def crash(crashfile, rerun, debugger=None): |
| 30 | + """Display a crash file and rerun if required.""" |
| 31 | + if crashfile.endswith(("pkl", "pklz")): |
| 32 | + with open(crashfile, "rb") as f: |
| 33 | + crash_content = cp.load(f) |
| 34 | + print("".join(crash_content["error message"])) |
| 35 | + |
| 36 | + if rerun: |
| 37 | + jobfile = Path(crashfile).parent / "_job.pklz" |
| 38 | + if jobfile.exists(): |
| 39 | + with open(jobfile, "rb") as f: |
| 40 | + job_obj = cp.load(f) |
| 41 | + |
| 42 | + if debugger == "ipython": |
| 43 | + sys.excepthook = ultratb.FormattedTB( |
| 44 | + mode="Verbose", theme_name="Linux", call_pdb=True |
| 45 | + ) |
| 46 | + |
| 47 | + try: |
| 48 | + job_obj.run(rerun=True) |
| 49 | + except Exception: # noqa: E722 |
| 50 | + if debugger == "pdb": |
| 51 | + pdb.post_mortem() |
| 52 | + elif debugger == "ipython": |
| 53 | + raise |
| 54 | + else: |
| 55 | + raise FileNotFoundError(f"Job file {jobfile} not found") |
| 56 | + else: |
| 57 | + raise ValueError("Only pickled crashfiles are supported") |
0 commit comments