Reputation: 5945
I have a script which I would like to wrap with an error handler that send an email if the script fails.
The straight-forward way to do it is:
try:
<script imports>
<script argument parse>
<script contents>
except Exception as e:
send_email(e)
raise
However I feel this solution is cumbersome. What are more elegant ways of doing it, while keeping the same commandline API of the original script?
EDIT: it would be great to have a solution with an API like: python email_wrap.py script_to_run.py <arguments>
. However, I am not sure how to manipulate the commandline arguments.
Upvotes: 1
Views: 179
Reputation: 5945
(OP here) I found how to do it:
import runpy
try:
scriptname_to_wrap = sys.argv[1]
sys.argv = [sys.argv[0]] + sys.argv[2:]
runpy.run_path(scriptname_to_wrap, run_name="__main__")
except BaseException as e:
send_email(e)
raise
Upvotes: 2