Python os.dup2()方法

Python的os.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!!

上一篇: Python os模块方法 下一篇: Python异常处理