Python os.dup()方法

2019-10-16 23:04:18

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!!