當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python 3 os.dup2()用法及代碼示例


描述

方法dup2()重複文件描述符fdfd2,如有必要,請先關閉後者。

注意− 僅在可用時分配新文件描述。在下麵給出的示例中,如果 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 3 - os.dup2() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。