Python异常控制/流问题

时间:2011-11-15 18:52:53

标签: python exception-handling try-except

我一直在使用Python并遇到了一些必须经常发生的事情。 我有五个陈述都属于提高的常见陷阱 FooException和BarException。我想运行它们,防范它们 这些异常但即使在之后引发异常也会继续处理 一些处理完成。现在,我可以这样做:

try:
    foo()
except (FooException, BarException):
    pass
try:
    bar()
except (FooException, BarException):
    pass
try:
    baz()
except (FooException, BarException):
    pass
try:
    spam()
except (FooException, BarException):
    pass
try:
    eggs()
except (FooException, BarException):
    pass

但这确实很冗长且极端违反DRY。相当蛮力 显而易见的解决方案是这样的:

def wish_i_had_macros_for_this(statements, exceptions, gd, ld):                
    """ execute statements inside try/except handling exceptions with gd and ld
    as global dictionary and local dictionary

    statements is a list of strings to be executed as statements
    exceptions is a list of strings that resolve to Exceptions
    gd is a globals() context dictionary
    ld is a locals() context dictionary

    a list containing None or an Exception if an exception that wasn't 
    guarded against was raised during execution of the statement for each
    statement is returned
    """
    s = """ 
try:    
    $STATEMENT
except (%s):
    pass
""" % ','.join(exceptions)                                                     
    t = string.Template(s)
    code = [t.substitute({'STATEMENT': s}) for s in statements]                   
    elist = list() 
    for c in code:
        try:
            exec c in gd, ld
            elist.append(None)
        except Exception, e:
            elist.append(e)
    return elist

使用顺序:

>>> results = wish_i_had_macros_for_this(
                ['foo()','bar()','baz','spam()','eggs()'],
                ['FooException','BarException'],
                globals(),
                locals())
[None,None,None,SpamException,None]

有更好的方法吗?

3 个答案:

答案 0 :(得分:3)

这个怎么样?

 #!/usr/bin/env python

 def foo():
     print "foo"

 def bar():
     print "bar"

 def baz():
     print "baz"

 for f in [foo, bar, baz]:
     try:
         f()
     except (FooException, BarException):
         pass 

答案 1 :(得分:3)

def execute_silently(fn, exceptions = (FooException, BarException)):
    try:
        fn()
    except Exception as e:
        if not isinstance(e, exceptions):
            raise

execute_silently(foo)
execute_silently(bar)
# ...
# or even:
for fn in (foo, bar, ...):
    execute_silently(fn)

答案 2 :(得分:0)

此版本也允许语句执行:

from contextlib import contextmanager
from functools import partial

@contextmanager
def exec_silent(exc=(StandardError,)):
    try:
        yield
    except exc:
        pass

silent_foobar = partial(exec_silent, (FooException, BarException))

with silent_foobar():
    print 'foo'
    foo()
with silent_foobar():
    print 'bar'
    bar()