Python的os.dup2()
方法將檔案描述符fd
複製到fd2
,如果需要,首先關閉後者。
註 - 僅當檔案可用時才會分配新的檔案描述。在下面給出的範例中,當在
1000
可用時,1000
將被分配給fd
。
語法
以下是dup2()
方法的語法 -
os.dup2(fd, fd2)
引數
返回值
範例
以下範例顯示了dup2()
方法的用法。
#!/usr/bin/python3
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# Write one string using duplicate fd
line = "this is test"
# string needs to be converted byte object
b = str.encode(line)
os.write(fd, b)
# 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)
line = os.read(fd2, 100)
str = line.decode()
print ("Read String is : ", str)
# Close opened file
os.closerange( fd,fd2 )
print ("Closed the file successfully!!")
執行上面程式碼後,將得到以下結果 -
Read String is : This is test
Closed the file successfully!!