Python Pipe

Muhammad Maisam Abbas Oct 10, 2023
Python Pipe

In operating systems, a pipe is used for inter-process communication. It is a way of passing information from one process to another.

The os module provides functionality to interact with the operating system in Python.

Use the os.pipe() Function to Create a Pipe in Python2

The os.pipe() function returns two file descriptors; one for writing data to the pipe and one for reading data written to the pipe. We will create a pipe to pass information between two processes.

import os

r, w = os.pipe()
p_id = os.fork()
if p_id:
    os.close(w)
    r = os.fdopen(r)
    print("Parent process reading data from the pipe")
    data = r.read()
    print("data =", data)
else:
    os.close(r)
    w = os.fdopen(w, "w")
    print("Child writing data to the pipe")
    w.write("data written by the child")
    w.close()

The child process writes some data to the pipe using the w file descriptor, and the parent process reads the data written to the pipe with the r file descriptor.

Output:

Child writing data to the pipe
Parent process reading data from the pipe
data = data written by the child

The pipe only allows one operation at a time. So, while reading data from it, we have to close the w file descriptor, and while writing data, we have to close the r file descriptor with the os.close() method.

Note
The above code works fine on Linux but raises exceptions while running on Windows because of the incompatibility of the os.fork() method.
Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn