Python3-os-pipe

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

Python 3-os.pipe()メソッド

説明

メソッド* pipe()*はパイプを作成し、それぞれ読み取りと書き込みに使用できるファイル記述子(r、w)のペアを返します

構文

以下は* pipe()*メソッドの構文です-

os.pipe()

パラメーター

NA

戻り値

このメソッドは、ファイル記述子のペアを返します。

次の例は、pipe()メソッドの使用方法を示しています。

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

print ("The child will write text to a pipe and ")
print ("the parent will read the text written by child...")

# file descriptors r, w for reading and writing
r, w = os.pipe()

processid = os.fork()
if processid:
   # This is the parent process
   # Closes file descriptor w
   os.close(w)
   r = os.fdopen(r)
   print ("Parent reading")
   str = r.read()
   print ("text =", str   )
   sys.exit(0)
else:
   # This is the child process
   os.close(r)
   w = os.fdopen(w, 'w')
   print ("Child writing")
   w.write("Text written by child...")
   w.close()
   print ("Child closing")
   sys.exit(0)

結果

上記のプログラムを実行すると、次の結果が生成されます-

The child will write text to a pipe and
the parent will read the text written by child...
Parent reading
('text =', 'Text written by child...')
The child will write text to a pipe and
the parent will read the text written by child...
Child writing
Child closing.