Python programs can link their input and output streams together using pipe (‘|’) operations. Piping isn’t a feature of Python, but rather comes from operating system. Nevertheless, a Python program can leverage such a feature to create powerful operating system scripts that are highly portable across platforms. For example, developer toolchains can be scripted together using Python. I personally have used Python to feed input into unit testing for my Java/Kotlin programs.
This post is a modified example of a demonstration found in Programming Python: Powerful Object-Oriented Programming. It uses a producer and consumer script to demonstrate one program feeding input into another Python program.
writer.py
Here is the code for writer.py
family = [ 'Bob Belcher', 'Linda Belcher', 'Tina Belcher', 'Gene Belcher', 'Louise Belcher' ] for f in family: print(f)
Nothing special here. We are just building up a list that prints out the names of our favorite TV family, the Belchers.
reader.py
This code receives the output from writer.
while True: try: print('Entering {}'.format(input())) except EOFError: break
Once again, this is a simple script. Without a pipe operation, the input() statement on line 3 would normally collect the input from the keyboard. That’s not what is going to happen here.
Demonstration
We are going to execute these scripts by running the command below in the terminal.
python writer.py | python reader.py The pipe '|' character does the job of connecting writer.py's output stream to reader.py's input stream. Thus, print statements in writer.py connect to input statements in reader.py. Here is the output of this operation. Entering Bob Belcher Entering Linda Belcher Entering Tina Belcher Entering Gene Belcher Entering Louise Belcher