dup2()方法複製檔描述符fd到fd2,如果必要之後就關閉它。
注意:只有在新的檔描述可用時才被分配。 在下面給出的下麵的例子中,1000在可用時,1000將被分配作為重複的fd。
語法
以下是 dup2()方法的語法:
os.dup2(fd, fd2)
參數
-
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!!
上一篇:
Python3檔方法
下一篇:
Python3 os檔目錄的方法