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異常處理