Python如何有意留下空行?

3
for line in sys.stdin:
    line = line.strip()
    uid, profile = line.split('\t')
    try:
        process(profile)
    except:
        # do nothing and skip this profile

我希望跳过所有引发异常的配置文件,但是Python会给我以下警告:
IndentationError: expected an indented block

在行号 "# do nothing and skip this profile" 上,我该如何告诉 Python 什么都不做呢?
2个回答

4

Python中的“NOP”是pass

...
except:
    pass

话虽如此,但是永远不要使用裸的except子句。它们会捕获一些你(几乎)绝对不想自己处理的东西,例如KeyboardInterrupt。如果你没有特定需要捕获的内容,请使用except Exception


3

使用 pass 关键字:

except:
    pass

pass 基本上是一个无实际作用的占位符。


此外,通常认为像这样裸露使用 except 是一种不良实践。正如此处所解释的那样,它会捕获所有异常,即使与之无关。

相反,应该捕获特定的异常:

except Exception:

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接