Python:多次尝试除了一个块? [英] Python: Multiple try except blocks in one?

查看:31
本文介绍了Python:多次尝试除了一个块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种巧妙的方法可以在 try 块中使用乘法命令,以便它基本上尝试每一行而不会在一个命令产生错误时立即停止?

Is there a neat way to have multiply commands in the try block so that it basically tries every single line without stopping as soon as one command yields an error?

基本上我想替换这个:

try:
   command1
except:
   pass
try:
   command2
except:
   pass
try:
   command3
except:
   pass

这样:

try all lines:
  command1
  command2
  command3
except:
  pass

定义一个列表以便我可以遍历命令似乎是一个糟糕的解决方案

Defining a list so I could loop through the commands seems to be a bad solution

推荐答案

我会说这是一种设计味道.消除错误通常是一个坏主意,特别是如果您要消除很多错误.但我会给你带来怀疑的好处.

I'd say this is a design smell. Silencing errors is usually a bad idea, especially if you're silencing a lot of them. But I'll give you the benefit of the doubt.

您可以定义一个包含 try/except 块的简单函数:

You can define a simple function that contains the try/except block:

def silence_errors(func, *args, **kwargs):
    try:
        func(*args, **kwargs)
    except:
        pass # I recommend that you at least log the error however


silence_errors(command1) # Note: you want to pass in the function here,
silence_errors(command2) # not its results, so just use the name.
silence_errors(command3)

这有效并且看起来相当干净,但是您需要不断地在任何地方重复silence_errors.

This works and looks fairly clean, but you need to constantly repeat silence_errors everywhere.

list 解决方案没有任何重复,但看起来有点糟糕,并且无法轻松传入参数.但是,您可以从程序中的其他位置读取命令列表,这可能会有所帮助,具体取决于您在做什么.

The list solution doesn't have any repetition, but looks a bit worse and you can't pass in parameters easily. However, you can read the command list from other places in the program, which may be beneficial depending on what you're doing.

COMMANDS = [
    command1,
    command2,
    command3,
]

for cmd in COMMANDS:
    try:
        cmd()
    except:
        pass

这篇关于Python:多次尝试除了一个块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆