How can I capture the error thrown by a python script in the bash script calling it?

67
January 27, 2022, at 10:10 AM

I want to write a bash script that sends a message depending on whether a python script it called ran successfully or threw an error.

In the case that it throws an error, I want to add the error message to the sent text.

Currently, I have this:

if python3 this_should_fail.py; then
    curl \
        -H 'Content-Type: application/json' \
        -d '{"text": "Your script finished running ✅"}' \
        $WEBHOOK_URL
else
    curl \
        -H 'Content-Type: application/json' \
        -d '{"text": "Your script failed with an error ❌"}' \
        $WEBHOOK_URL
fi

How do I capture the error message thrown by this_should_fail.py and include it in the sent JSON as a string?

I am looking for something like

curl \
        -H 'Content-Type: application/json' \
        -d '{"text": "Your script failed with an error ❌",
             "error_message": '$ESCAPED_ERROR_MESSAGE_STRING_HERE'}' \
        $WEBHOOK_URL

The error message I want to capture is, for example:

Traceback (most recent call last):
  File "this_should_fail.py", line 5, in <module>
    a = 100 / 0
ZeroDivisionError: division by zero
Answer 1

You can probably do something like this depending on how your webhook is expecting the data

err=$(mktemp)
if python3 this_should_fail.py 2>"$err"; then
    curl \
        -H 'Content-Type: application/json' \
        -d '{"text": "Your script finished running ✅"}' \
        $WEBHOOK_URL
else
    curl \
        -H 'Content-Type: application/json' \
        -d '{"text": "Your script failed with an error ❌"}' \
        --data-binary "@$err" \
        $WEBHOOK_URL
fi
READ ALSO
Can I get original page be different than the AMP?

Can I get original page be different than the AMP?

So I am using IFRAME on my pagesThe code usually goes like this

73
Where PWA store photos?

Where PWA store photos?

I've the PWA app, launched on Android deviceThe app allow to take pictures and upload them to server

105
CSS Progress Circle

CSS Progress Circle

I have searched this website to find progress bars, but the ones I have been able to found show animated circles that go to the full 100%

113
Simple templating system with {{field}} in PHP

Simple templating system with {{field}} in PHP

I'm designing a simple templating system for a CMS in PHP which internally currently uses something like:

78