with os.open? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: with os.open? (/thread-18719.html) |
with os.open? - Skaperen - May-28-2019 i have many cases where i need to call os.open, do something with that file descriptor, then close it. is there a way to do that using a with statement? what about using with with an object of my own creation? is there a specific method to implement? RE: with os.open? - heiner55 - May-29-2019 https://docs.python.org/3/reference/compound_stmts.html#the-with-statement or https://stackoverflow.com/questions/1984325/explaining-pythons-enter-and-exit Or PEP: https://www.python.org/dev/peps/pep-0343/ RE: with os.open? - Gribouillis - May-29-2019 See also contextlib.contextmanager for a simplified interface and also contextlib.closing and the like import contextlib @contextlib.contextmanager def my_open(*args, **kwargs): fd = os.open(*args, **kwargs) try: yield fd finally: os.close(fd) with my_open(my_thing) as desc: ... RE: with os.open? - heiner55 - May-30-2019 Thanks, I didn't know that. |