Latest web development tutorials

Python3 os.dup2 () method

Python3 OS file / directory methods Python3 OS file / directory methods


Outline

os.dup2 () method is used to copy a file descriptor fd to another fd2.

Unix, is available on Windows.

grammar

dup2 () method syntax is as follows:

os.dup2(fd, fd2);

parameter

  • fd - the file descriptor to be copied

  • fd2 - Copy file descriptor

return value

No return value.

Examples

The following example demonstrates dup2 () method of use:

#!/usr/bin/python3

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 above program output is:

读取的字符串是 :  This is test
关闭文件成功!!

Python3 OS file / directory methods Python3 OS file / directory methods