Skip to content

Commit

Permalink
Simplify re-raise logic
Browse files Browse the repository at this point in the history
  • Loading branch information
mexanick committed Jul 19, 2024
1 parent 570a4bb commit 45a0fd4
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
8 changes: 4 additions & 4 deletions src/ctapipe/core/tests/test_traits.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,11 +351,11 @@ class MyTool(Tool):
run_tool(tool, ["--MyTool.energy=5 m"], raises=True)

captured = capsys.readouterr()
assert (
captured.err.split(":")[-1]
== f" Given quantity is of physical type {u.get_physical_type(5 * u.m)}."
+ f" Expected {u.physical.energy}.\n"
expected = (
f" Given quantity is of physical type {u.get_physical_type(5 * u.m)}."
f" Expected {u.physical.energy}.\n"
)
assert expected in captured.err


def test_quantity_none():
Expand Down
12 changes: 6 additions & 6 deletions src/ctapipe/core/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,7 @@ def run(self, argv=None, raises=False):
# https://tldp.org/LDP/abs/html/exitcodes.html

exit_status = 0
current_exception = None

with self._exit_stack:
try:
Expand All @@ -429,21 +430,21 @@ def run(self, argv=None, raises=False):
self.log.info("Finished: %s", self.name)
Provenance().finish_activity(activity_name=self.name)
except (ToolConfigurationError, TraitError) as err:
current_exception = err
self.log.error("%s", err)
self.log.error("Use --help for more info")
exit_status = 2 # wrong cmd line parameter
Provenance().finish_activity(
activity_name=self.name, status="error", exit_code=exit_status
)
if raises:
raise
except KeyboardInterrupt:
self.log.warning("WAS INTERRUPTED BY CTRL-C")
exit_status = 130 # Script terminated by Control-C
Provenance().finish_activity(
activity_name=self.name, status="interrupted", exit_code=exit_status
)
except Exception as err:
current_exception = err
exit_status = getattr(err, "exit_code", 1)
if exit_status == 1:
self.log.exception("Caught unexpected exception: %s", err)
Expand All @@ -452,17 +453,14 @@ def run(self, argv=None, raises=False):
Provenance().finish_activity(
activity_name=self.name, status="error", exit_code=exit_status
)
if raises:
raise
except SystemExit as err:
exit_status = err.code
if exit_status == 0:
# Finish normally
Provenance().finish_activity(activity_name=self.name)
else:
if raises:
raise
# Finish with error
current_exception = err
self.log.critical(
"Caught SystemExit with exit code %s", exit_status
)
Expand All @@ -474,6 +472,8 @@ def run(self, argv=None, raises=False):
finally:
if not {"-h", "--help", "--help-all"}.intersection(self.argv):
self.write_provenance()
if raises and current_exception:
raise current_exception

self.exit(exit_status)

Expand Down

0 comments on commit 45a0fd4

Please sign in to comment.