Python | os.closerange() method
Last Updated :
18 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.closerange()
method in Python is used to close all file descriptors in the range fd_low (inclusive) to fd_high (exclusive). Any error occurred while closing any of the file descriptor in the given range is ignored.
A file descriptor is small integer value that corresponds to a file or other input/output resource, such as a pipe or network socket. A File descriptor is an abstract indicator of a resource and act as handle to perform various lower level I/O operations like read, write, send etc.
For Example: Standard input is usually file descriptor with value 0, standard output is usually file descriptor with value 1 and standard error is usually file descriptor with value 2.
Further files opened by the current process will get the value 3, 4, 5 an so on.
Syntax: os.closerange(fd_low, fd_high)
Parameters:
fd_low: The Lowest file descriptor to be closed.
fd_high: The highest file descriptor to be closed.
Return Type: This method does not return any value
Code: Use of os.closerange()
method to close file descriptors in the given range
import os
path1 = "/home/ihritik/Desktop/file1.txt"
path2 = "/home/ihritik/Desktop/file2.txt"
path3 = "/home/ihritik/Desktop/file3.txt"
path4 = "/home/ihritik/Desktop/file4.txt"
fd1 = os. open (path1, os.O_WRONLY | os.O_CREAT)
fd2 = os. open (path2, os.O_WRONLY | os.O_CREAT)
fd3 = os. open (path3, os.O_WRONLY | os.O_CREAT)
fd4 = os. open (path4, os.O_WRONLY | os.O_CREAT)
s = "GeeksForGeeks: A computer science portal for geeks"
line = str .encode(s)
os.write(fd1, line)
os.write(fd2, line)
os.write(fd3, line)
os.write(fd4, line)
fd_low = min (fd1, fd2, fd3, fd4)
fd_high = max (fd1, fd2, fd3, fd4)
os.closerange(fd_low, fd_high + 1 )
print ( "All file descriptor closed successfully" )
|
Output:
All file descriptor closed successfully
Note: os.closerange()
method is equivalent to following python code:
for fd in range (fd_low, fd_high):
try :
os.close(fd)
except OSError:
pass
|
However os.closerange()
method works faster than above code.
Share your thoughts in the comments
Please Login to comment...