Python os.closerange() 方法



Python os.closerange() 方法關閉從 fd_lowfd_high 的所有檔案描述符。其中,fd_low 是要關閉的檔案描述符的下邊界範圍,而 fd_high 是要關閉的檔案描述符的上邊界範圍。請注意,fd_low 是包含的,而 fd_high 是不包含的。

Python 中,檔案描述符是識別符號,表示作業系統核心中開啟的檔案,並儲存在檔案表中。通常,檔案描述符具有非負值。負結果表示錯誤或“無值”條件。它們主要用於訪問檔案和其他輸入/輸出裝置,例如網路套接字或管道。

os.closerange() 方法比 os.close() 方法更有效,因為它允許在檔案描述符範圍內靈活操作。

注意:如果在給定範圍內關閉檔案描述符時發生任何錯誤,則會忽略該錯誤。此方法在 Python 2.6 版本中引入。

語法

以下是 Python os.closerange() 方法的語法:

os.closerange(fd_low, fd_high);

引數

  • fd_low - 這是要關閉的最低檔案描述符。

  • fd_high - 這是要關閉的最高檔案描述符。

返回值

此方法不返回值。

示例 1

以下示例顯示了 Python os.closerange() 方法的用法。在這裡,我們建立了一個檔案描述符 'os.O_RDWR|os.O_CREAT'。然後,我們在檔案中寫入字串“This is test”。之後,我們使用此方法關閉檔案。

import os, sys
# Open a file
fd = os.open( "code.txt", os.O_RDWR|os.O_CREAT )
# Write one string
string = "This is test"
x = str.encode(string)
os.write(fd, x)
# Close a single opened file
os.closerange( fd, fd)
print ("Closed all the files successfully!!")

這將建立給定的檔案 foo.txt,然後在該檔案中寫入給定的內容。這將產生以下結果:

Closed all the files successfully!!

示例 2

值分別為 0 和 1 的檔案描述符分別用作標準輸入和輸出。

在這裡,我們將標準範圍 '0' 作為 fd_low 和 '1' 作為 fd_high 作為引數傳遞給 closerange() 方法。

import os
filedesc = os.open( "code.txt", os.O_RDWR|os.O_CREAT )
os.closerange(0,1)
print ("Closed all the files successfully!!")

執行上述程式碼時,我們得到以下輸出:

Closed all the files successfully!!

示例 3

在下面給出的示例中,我們建立了一個檔案描述符 'r'。這意味著讀取檔案。

import os
file = "code.txt"
file_Object = open(file, "r")
fd = file_Object.fileno()
print("The descriptor of the file for %s is %s" % (file, fd))
os.closerange(fd,fd)

以下是上述程式碼的輸出:

The descriptor of the file for code.txt is 3

示例 4

值為 2 的檔案描述符是標準錯誤。

在這裡,我們將值 '2' 作為 fd_high 作為引數傳遞給 closerange() 方法。

import os
filedesc = os.open( "code.txt", os.O_RDWR|os.O_CREAT )
os.closerange(0,2)
print ("Closed all the files successfully!!")

上述程式碼的輸出如下:

Traceback (most recent call last):
  File "/home/sarika/Desktop/chown.py", line 4, in 
    print ("Closed all the files successfully!!")
OSError: [Errno 9] Bad file descriptor
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
OSError: [Errno 9] Bad file descriptor
os_file_methods.htm
廣告