Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
with os.open?
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
https://docs.python.org/3/reference/comp...-statement
or
https://stackoverflow.com/questions/1984...r-and-exit
Or PEP:
https://www.python.org/dev/peps/pep-0343/
Reply
#3
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:
    ...
Reply
#4
Thanks, I didn't know that.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020