Python os.dup()方法

Python的os.dup()方法返回可用于代替原始描述符的文件描述符fd的副本。

语法

以下是dup()方法的语法 -

os.dup(fd)

参数

  • fd − 这是原始的文件描述符。

此函数实现的功能相当于 -

for fd in xrange(fd_low, fd_high):
   try:
      os.close(fd)
   except OSError:
      pass

返回值

  • 此方法返回文件描述符的副本。

示例

以下示例显示了dup()方法的用法。

#!/usr/bin/python3
import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Get one duplicate file descriptor
d_fd = os.dup( fd )

# Write one string using duplicate fd
line = "this is test" 

# string needs to be converted byte object
b = str.encode(line)
os.write(d_fd, b)

# Close a single opened file
os.closerange( fd, d_fd)

print "Closed all the files successfully!!"

执行上面代码后,将得到以下结果 -

Closed all the files successfully!!

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