Python os.dup() 方法



Python 的 os.dup() 方法 返回給定檔案描述符的副本。這意味著該副本可以替代原始描述符使用。

獲得的新檔案描述符是非繼承的。非繼承的意思是,建立的檔案描述符不能被子程序繼承。子程序中所有非繼承的檔案描述符都會被關閉。

在 Windows 上,連結到標準流(如標準輸入 (0)、標準輸出 (1) 和標準錯誤 (2))的檔案描述符能夠被子程序繼承。如果父程序正在為特定檔案使用檔案描述符 3,並且父程序建立了一個子程序,則子程序也將為同一檔案使用檔案描述符 3。這被稱為可繼承檔案描述符。

語法

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

os.dup(fd)

引數

  • fd − 這是原始檔案描述符。

返回值

此方法返回檔案描述符的副本。

示例 1

以下示例演示了 Python os.dup() 方法的用法。這裡開啟一個檔案用於讀寫。然後透過該方法獲得一個副本檔案:

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

執行上述程式時,會產生以下結果:

Closed all the files successfully!!

示例 2

在以下示例中,檔案以只讀方式由所有者開啟。副本檔案的值將不同,但它將對應於原始檔案描述符所引用的同一檔案。

import os
import stat
# File path
path = "code.txt"
# opening the file for reading only by owner
filedesc = os.open(path, stat.S_IREAD)
print("The original file descriptor is:", filedesc)
# Duplicating the file descriptor
dup_filedesc = os.dup(filedesc)
print("The duplicated file descriptor is:", dup_filedesc)

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

The original file descriptor is: 3
The duplicated file descriptor is: 4
os_file_methods.htm
廣告