Input by pipe

Pipe is another form of redirection. This technique is used to pass information from one program to another. The | symbol denotes pipe. By using the pipe technique, we can use more than two commands in such a way that the output of one command acts as input to the next command.

Now, we are going to see how we can accept an input using pipe. For that, first we'll write a simple script that returns a floor division. Create a script called accept_by_pipe.py and write the following code in it:

import sys

for n in sys.stdin:
print ( int(n.strip())//2 )

Run the script and you will get the following output:

$ echo 15 | python3 accept_by_pipe.py
Output:
7

In the preceding script, stdin is a keyboard input. We are performing a floor division on the number we enter at runtime. The floor division returns only the integer part of the quotient. When we run the program, we pass 15 followed by the pipe | symbol, and then our script name. So, we are providing 15 as input to our script. So the floor division is performed and we get the output as 7.

We can pass multiple input to our script. So, in the following execution, we have passed multiple input values as 15, 45, and 20. For handling multiple input values, we have written a for loop in our script. So, it will first take the input as 15, followed by 45, and then 20. The output will be printed on a new line for each input, as we have written between the input value. To enable this interpretation of a backslash, we passed the -e flag:

$ echo -e '15
45
20' | python3 accept_by_pipe.py
Output:
7
22
10

After running this, we got floor divisions for 15, 45 and 20 as 7, 22, and 10, respectively, on new lines.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset