Python os.dup2() 方法



Python os.dup2() 方法用於將給定的檔案描述符複製到另一個檔案描述符。如果需要,原始檔案描述符將被關閉。

獲得的新檔案描述符是可繼承的。可繼承的意思是,建立的檔案描述符可以被子程序繼承。如果父程序正在使用檔案描述符 3 訪問某個特定檔案,並且父程序建立了一個子程序,那麼子程序也將使用檔案描述符 3 訪問同一個檔案。這被稱為可繼承檔案描述符。

注意 - 只有當新的檔案描述符可用時,才會分配新的檔案描述符。

語法

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

os.dup2(fd, fd2);

引數

  • fd - 要複製的檔案描述符。

  • fd2 - 複製到的檔案描述符。

返回值

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

示例 1

以下示例演示了 Python os.dup2() 方法的使用。這裡,如果 1000 可用,則將其分配為副本 fd。

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)
# Now duplicate this file descriptor as 1000
fd2 = 1000
os.dup2(fd, fd2);
# Now read this file from the beginning using fd2.
os.lseek(fd2, 0, 0)
str = os.read(fd2, 100)
print ("Read String is : ", str)
# Close opened file
os.close( fd )
print ("Closed the file successfully!!")

當我們執行以上程式時,它會產生以下結果:

Read String is :  b'This is test'
Closed the file successfully!!

示例 2

在這裡,我們檢查給定的兩個檔案描述符是否不同。這是使用 sameopenfile() 方法完成的。此方法返回一個布林值

import os
filepath = "code.txt"
fd1 = os.open(filepath, os.O_RDONLY)
fd2 = os.open("python.txt", os.O_RDONLY)
print("Before duplicating file descriptor:", os.path.sameopenfile(fd1, fd2))
fd2 = os.dup2(fd1, fd2)
print("After duplicating file descriptor:", os.path.sameopenfile(fd1, fd2))
os.close(fd1)
os.close(fd2)

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

Before duplicating file descriptor: False
After duplicating file descriptor: True
python_file_methods.htm
廣告