@contextmanager def myOpen(name, state): try: f = open(name, state) yield f finally: f.close() if __name__ == "__main__": with myOpen("test.txt", "w") as f: f.write("hello world!") 可以看出這里只要定義一個函數(shù),然后在它的頭部加上
在Python 中,我們會經(jīng)常聽到上下文管理器(Context Manager),那我們探討下這是什么,又有什么功能。 在Python 中的上下文管理器中,使用 with 打開文件是使用最多的,其中離開 with 包含的語句后會執(zhí)行一些類似于清理的工作,如關(guān)閉文件,關(guān)閉連接對象等操作。
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244) [spring-test-5.2.5.RELEASE.jar:5.2.5.RELEASE] at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:98) [spring-test-5.2.5.RELEASE.jar:5.2....