Python3-os-dup2

提供:Dev Guides
移動先:案内検索

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