一种更简洁的方法来接近尝试,除了在python中

Cri*_*pto 3 python exception try-catch

所以,假设我有3个不同的呼叫something,something1并且something2.

而现在,我称之为

try:
   something
   something1
   something2
except Keyerror as e:
   print e
Run Code Online (Sandbox Code Playgroud)

请注意,在上面的代码中,如果某些内容失败,那么something1和something2将不会被执行,依此类推.

想要的结果是

try:
    something
except KeyError as e:
    print e
try:
    something1
except KeyError as e:
    print e
try:
    something2
except KeyError as e:
    print e
Run Code Online (Sandbox Code Playgroud)

如果没有那么多尝试除了块之外我怎么能实现上面的代码.

编辑:

所以,我选择的答案是正确的.但其他一些人也表现得很好.我选择了它,因为它是简单的,我修改了一点.

以下是基于答案的解决方案.

runs = [something, something1, something2]
for func in runs:
    try:
        func()
    except Keyerror as e:
        print e
Run Code Online (Sandbox Code Playgroud)

orl*_*rlp 8

你可以尝试这个,假设你在函数中包装:

for func in (something, something1, something2):
    try:
        func()
    except Keyerror as e:
        print e
Run Code Online (Sandbox Code Playgroud)


kin*_*all 5

这是我用于类似情况的一个小环境管理器:

from contextlib import contextmanager

@contextmanager
def ignoring(*exceptions):
    try:
        yield
    except exceptions or Exception as e:
        print e

with ignoring(KeyError):
    something()

# you can also put it on the same line if it's just one statement
with ignoring(KeyError): something1()

with ignoring(KeyError): something2()
Run Code Online (Sandbox Code Playgroud)

Python 3版本可以让您参数化发生异常时要执行的操作(此处需要仅限关键字的参数):

from contextlib import contextmanager

@contextmanager
def ignoring(*exceptions, action=print):
    try:
        yield
    except exceptions or Exception as e:
        callable(action) and action(e)
Run Code Online (Sandbox Code Playgroud)

然后,你可以比其他一些功能传递print(如记录器,假设为一个函数命名log),或者如果你不想要的东西,传中None(因为它会检查,看看是否行动是可调用):

with ignoring(KeyError, action=log): something()
Run Code Online (Sandbox Code Playgroud)