![](/img/trans.png)
[英]How do I go from a bash script that calls a python script to a python script calling a bash script?
[英]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.