Python try 块中的所有内容

发布于 2024-12-02 12:44:18 字数 151 浏览 2 评论 0原文

我正在用Python编写一个大型批处理类型的脚本,无论是否发生异常,最后都需要进行一些清理。为此,我只需将主程序放在 try 块中,并将清理放在 finally 块中。

这似乎运行良好,但我的问题是如何打印可能发生的任何异常。目前它只是忽略它们并跳转到finally 块。

I am writing a large batch-type script in Python, and need to do some cleanup in the end, regardless of whether an exception occurred. To do this I'm simply putting the main program in a try block and the cleanup in a finally block.

This seems to work well, but my question is how to print any exceptions that might occur. Currently it just ignores them and jumps to the finally block.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猫弦 2024-12-09 12:44:18

您应该能够使用没有异常处理程序的 try/finally 块。它不会捕获异常或抑制回溯,只是确保无论是否存在异常都会运行清理代码。这就是finally 的全部要点。

这是一个例子:

Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> try:
...     print 'begin try'
...     assert False
...     print 'end try'
... finally:
...     print 'finally'
... 
begin try
finally
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
AssertionError

You should just be able to use a try/finally block with no exception handler. It won't catch the exception or suppress the traceback, just ensure your cleanup code is run whether or not there is an exception. That's the entire point of finally.

Here's an example:

Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> try:
...     print 'begin try'
...     assert False
...     print 'end try'
... finally:
...     print 'finally'
... 
begin try
finally
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
AssertionError
若有似无的小暗淡 2024-12-09 12:44:18

你可以使用回溯。

像这样的东西:

import traceback
try:
    foo
except:
    print(traceback.format_exc())
finally:
     cleanup

you can use traceback.

something like:

import traceback
try:
    foo
except:
    print(traceback.format_exc())
finally:
     cleanup
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文