Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python os.dup2() method

Python os.dup2() method

Python File methods Python OS file/directory methods


Overview

The os.dup2() method duplicates one file descriptor fd onto another fd2.

Available on Unix and Windows.

Syntax

The **dup2()** method syntax is as follows:



os.dup2(fd, fd2);

Parameters

Return Value

No value is returned.

Example

The following example demonstrates the use of the dup2() method:



#!/usr/bin/python

# -*- coding: UTF-8 -*-



import os, sys



# Open file

fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )



# Write string

os.write(fd, "This is test")



# File descriptor is 1000

fd2 = 1000

os.dup2(fd, fd2);



# Insert data on a new file descriptor

os.lseek(fd2, 0, 0)

str = os.read(fd2, 100)

print "读取的字符串是 : ", str



# Close file

os.close( fd )



print "关闭文件成功!!"

The output of the above program is:



读取的字符串是 :  This is test

关闭文件成功!!

Python File methods Python OS file/directory methods