用法:
contextlib.suppress(*exceptions)
返回一個上下文管理器,如果它們發生在
with
語句的主體中,則抑製任何指定的異常,然後使用with
語句結束後的第一條語句繼續執行。與任何其他完全抑製異常的機製一樣,此上下文管理器應僅用於覆蓋非常具體的錯誤,其中已知靜默繼續執行程序是正確的做法。
例如:
from contextlib import suppress with suppress(FileNotFoundError): os.remove('somefile.tmp') with suppress(FileNotFoundError): os.remove('someotherfile.tmp')
這段代碼相當於:
try: os.remove('somefile.tmp') except FileNotFoundError: pass try: os.remove('someotherfile.tmp') except FileNotFoundError: pass
這個上下文管理器是可重入的。
3.4 版中的新函數。
相關用法
- Python contextlib.AsyncContextDecorator用法及代碼示例
- Python contextlib.AsyncExitStack用法及代碼示例
- Python contextlib.ExitStack.pop_all用法及代碼示例
- Python contextlib.redirect_stdout用法及代碼示例
- Python contextlib.aclosing用法及代碼示例
- Python contextlib.ExitStack用法及代碼示例
- Python contextlib.contextmanager用法及代碼示例
- Python contextlib.closing用法及代碼示例
- Python contextlib.nullcontext用法及代碼示例
- Python contextlib.ContextDecorator用法及代碼示例
- Python contextvars.ContextVar.reset用法及代碼示例
- Python contextvars.Context.run用法及代碼示例
- Python configparser.ConfigParser.readfp用法及代碼示例
- Python configparser.ConfigParser.BOOLEAN_STATES用法及代碼示例
- Python configparser.BasicInterpolation用法及代碼示例
- Python configparser.ExtendedInterpolation用法及代碼示例
- Python configparser.ConfigParser.SECTCRE用法及代碼示例
- Python configparser.ConfigParser.read用法及代碼示例
- Python collections.somenamedtuple._replace用法及代碼示例
- Python collections.somenamedtuple._asdict用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 contextlib.suppress。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。