Bottom Page

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?
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Quote
#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/
Quote
#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:
    ...
Skaperen likes this post
Quote
#4
Thanks, I didn't know that.
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)