Python方法dup2()将文件描述符fd复制到fd2,如果需要,先关闭后者。
注意-新文件说明只有在可用时才会分配。在下面给出的Example中,当1000可用时,1000将被分配为重复的FD。
os.dup2(fd, fd2) - 语法
os.dup2(fd, fd2);
fd - 这是要复制的文件描述符。
fd2 - 这是重复的文件描述符。
os.dup2(fd, fd2) - 返回值
此方法返回文件描述符的副本。
os.dup2(fd, fd2) - 示例
以下示例显示了dup2()方法的用法。
#!/usr/bin/python import os, sys # Open a file fd=os.open( "foo.txt", os.O_RDWR|os.O_CREAT ) # Write one string os.write(fd, "This is test") # 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 : This is test Closed the file successfully!!