with open("test/test.txt","w") as f_obj:
f_obj.write("hello")
f_obj = open("test/test.txt","w")
f_obj.write("hello")
f_obj.close()
import sqlite3
class DataConn:
def __init__(self,db_name):
self.db_name = db_name
def __enter__(self):
self.conn = sqlite3.connect(self.db_name)
return self.conn
def __exit__(self,exc_type,exc_val,exc_tb):
self.conn.close()
if exc_val:
raise
if __name__ == "__main__":
db = "test/test.db"
with DataConn(db) as conn:
cursor = conn.cursor()
from contextlib import contextmanager
@contextmanager
def file_open(path):
try:
f_obj = open(path,"w")
yield f_obj
except OSError:
print("We had an error!")
finally:
print("Closing file")
f_obj.close()
if __name__ == "__main__":
with file_open("test/test.txt") as fobj:
fobj.write("Testing context managers")
>>> from contextlib import contextmanager >>> @contextmanager ... def closing(db): ... try: ... yield db.conn() ... finally: ... db.close()
>>> from contextlib import closing
>>> from urllib.request import urlopen
>>> with closing(urlopen("http://www.google.com")) as webpage:
... for line in webpage:
... pass
>>> with open("1.txt") as fobj:
... for line in fobj:
... print(line)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '1.txt'
>>> from contextlib import suppress
>>> with suppress(FileNotFoundError):
... with open("1.txt") as fobj:
... for line in fobj:
... print(line)
import sys path = "test/test.txt" with open(path,"w") as fobj: sys.stdout = fobj help(sum)
from contextlib import redirect_stdout
path = "test/test.txt"
with open(path,"w") as fobj:
with redirect_stdout(fobj):
help(redirect_stdout)
>>> from contextlib import ExitStack >>> filenames = ["1.txt","2.txt"] >>> with ExitStack as stack: ... file_objects = [stack.enter_context(open(filename)) for filename in filenames]
>>> from contextlib import contextmanager
>>> @contextmanager
... def single():
... print("Yielding")
... yield
... print("Exiting context manager")
...
>>> context = single()
>>> with context:
... pass
...
Yielding
Exiting context manager
>>> with context:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/contextlib.py", line 61, in __enter__
raise RuntimeError("generator didn't yield") from None
RuntimeError: generator didn't yield
>>> from contextlib import redirect_stdout
>>> from io import StringIO
>>> stream = StringIO()
>>> write_to_stream = redirect_stdout(stream)
>>> with write_to_stream:
... print("Write something to the stream")
... with write_to_stream:
... print("Write something else to stream")
...
>>> print(stream.getvalue())
Write something to the stream
Write something else to stream
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有