with...as
python 控制流語句,是簡化版的try except finally。
with expression [as variable]:
with-block
with 語句實質是上下文管理。
1、上下文管理協議。包含方法__enter__() 和 __exit__(),支持該協議對象要實現這兩個方法。
2、上下文管理器,定義執行with語句時要建立的運行時上下文,負責執行with語句塊上下文中的進入與退出操作。
3、進入上下文的時候執行__enter__方法,如果設置as var語句,var變量接受__enter__()方法返回值。
4、如果運行時發生了異常,就退出上下文管理器。調用管理器__exit__方法。
應用場景
1、文件操作。
2、進程線程之間互斥對象。
3、支持上下文其他對象
1. 方式1
#?簡單處理
file?=?open("1.txt")
data?=?file.read()
file.close()
2. 方式2
#?增加異常處理
try:
????f?=?open('1.txt')
except:
????print?'fail?to?open'
????exit(-1)
finally
????f.close()
3. 方式3
#?使用with
with?open("/tmp/1.txt")?as?file:
????data?=?file.read()
????
1.?方式1?對異常沒處理
2.?方式2?寫法冗長
3. with 簡潔
with 語句,調用__enter__() 方法并返回值,
這個值賦給as后面的變量
with 后面的代碼執行完成,調用__exit__()方法
class Sample:
def __enter__(self):
print "In __enter__()"
return "Foo"
def __exit__(self, type, value, trace):
print "In __exit__()"
def get_sample():
return Sample()
with get_sample() as sample:
print "sample:", sample
with 可以處理異常
with as 表達式簡化了finally工作,保持代碼的優雅性。
- 前言
- 1.入門篇
- Python介紹
- 安裝與使用
- Python開發利器之VS Code
- 模塊安裝
- 命令行
- 一次Python無法安裝模塊的問題探索與解決之旅
- 命令運行
- Conda
- 下載地址
- 2.基礎篇
- 基礎語法
- 輸入與輸出
- with as的用法
- 注釋
- Python命令行參數
- 編碼
- 變量類型
- 列表遍歷
- 運算符
- 表達式語句
- 條件
- 循環
- 日期和時間
- 函數
- 高級語法
- @符號-裝飾器
- 模塊和包
- name
- init.py
- 錯誤和異常
- 面向對象
- 3.專題篇
- 常用功能
- Python 字符串連接
- python web
- Python CGI編程
- Python OAuth2
- 認證 Flask-HTTPAuth
- 常用命令
- 內置函數
- dir()
- print(f)
- 標準模塊
- sys
- pickle-數據序列化
- os
- IO(輸入輸出)
- 鍵盤輸入
- 文件讀寫
- 測試
- Python測試框架之pytest快速入門
- pytest-bdd快速示例和問題解決
- 基于pytest-bdd的項目目錄結構和命名規范
- python BDD 的相關概念
- Behave介紹和快速示例
- Python BDD之Behave測試報告
- Python BDD 框架比較之 pytest-bdd vs behave
- pytest進階
- Flask + pytest測試
- 參考網址
- pytest-bdd進階
- hehave進階
- 測試路徑
- python + selunium
- HTML 根據多層CSS 查找元素
- 等待執行
- 使用text 查找 span
- pytest如何在控制臺輸出
- 4.問題篇
- pip pip3 及區別
- TypeError: can only concatenate str (not "NoneType") to str
- 5.實戰篇
- matplotlib-繪圖包
- 導入類
- 命名規范
- 模塊查找
- 6.進階篇
- Flask
- Flask介紹
- Flask擴展模塊
- Flask-Login
- 問題
- Jinja2
- Flask-RESTful
- Flask-JWT-Extended
- WSGI
- Flask-SQLAlchemy
- 部署
- Flask VS Django
- Flask Web
- Flask + Vue
- Flask實戰
- Flask 標準目錄結構
- Blueprints
- 參考
- FastAPI 測試
- https 證書 Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate