簡體   English   中英

如何在調用它的 bash 腳本中捕獲 python 腳本引發的錯誤?

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

我想編寫一個 bash 腳本,根據它調用的 python 腳本是成功運行還是拋出錯誤來發送消息。

如果它引發錯誤,我想將錯誤消息添加到發送的文本中。

目前,我有這個:

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

如何捕獲this_should_fail.py拋出的錯誤消息並將其作為字符串包含在發送的 JSON 中?

我正在尋找類似的東西

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

我要捕獲的錯誤消息是,例如:

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

您可能可以根據您的 webhook 期望數據的方式執行此類操作

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM