alp*_*ric 1 python amazon-web-services docker kubernetes amazon-eks
使用运行 Python 脚本的 Kubernetes 容器:
import time
while True:
try:
for i in range(10):
if i==0:
raise Exception('Exception occurred!')
except:
pass
time.sleep(1)
Run Code Online (Sandbox Code Playgroud)
我想将异常的消息传递'Exception occurred!'给容器,以便可以通过以下方式看到此错误消息:
kubectl describe pod pod_id
可能吗?
您print()将在 中看到的任何内容kubectl logs。(您可能需要PYTHONUNBUFFERED=1在 pod 规范中设置环境变量。)
您编写的代码永远不会打印任何内容。构造
try:
...
except:
pass
Run Code Online (Sandbox Code Playgroud)
默默地忽略块外的任何和所有异常try。bareexcept:甚至捕获一些系统级异常,例如SystemExit或KeyboardInterrupt;这几乎总是错误的。通常,您希望except块的范围尽可能严格,有关用户定义异常的Python 教程是一个有用的模式。
(例外情况是,特别是在 Kubernetes 上下文中,您通常需要一个非常广泛的异常处理程序来执行诸如向网络请求返回 HTTP 500 错误之类的操作,而不是使应用程序崩溃。)
更好的示例可能如下所示:
import time
class OneException(Exception):
pass
def iteration():
for i in range(10):
try:
if i == 1:
raise OneException("it is one")
print(i, math.sqrt(i), math.sqrt(-i))
# will work when i==0 but fail when i==2
except OneException as e:
print(i, repr(e))
# and proceed to the next iteration
if __name__ == '__main__':
while True:
# The top-level loop. We want a very broad catch here.
try:
iteration()
except Exception as e:
print('iteration failed', repr(e))
time.sleep(1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8624 次 |
| 最近记录: |