Python os.dup2() Method
Python OS File/Directory Methods
Overview
os.dup2() method is used to duplicate a file descriptor fd to another fd2.
Available on Unix, Windows.
Syntax
dup2()The method syntax format is as follows:
os.dup2(fd, fd2);
Parameters
fd-- The file descriptor to be duplicated
fd2-- The file descriptor to copy to
Return Value
No return value.
Example
The following example demonstrates the use of the dup2() method:
#!/usr/bin/python # -*- coding: UTF-8 -*- import os, sys # 打开文件 fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT ) # 写入字符串 os.write(fd, "This is test") # 文件描述符为 1000 fd2 = 1000 os.dup2(fd, fd2); # 在新的文件描述符上插入数据 os.lseek(fd2, 0, 0) str = os.read(fd2, 100) print "读取的字符串是 : ", str # 关闭文件 os.close( fd ) print "关闭文件成功!!"
The output of the above program is:
读取的字符串是 : This is test 关闭文件成功!!Other Extensions