Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write Python scripts that work with Linux pipes?

Tags:

python

linux

In speaker.py, I use print to output text to STDOUT:

import time

while True:
    time.sleep(1)
    print("hello")

And in listener.py, I use input to read from STDIN:

while True:
    line = input()
    if not line:
        break
    print(line)

I'm trying to connect these two scripts with a pipe:

python speaker.py | python listener.py

But listner.py output nothing.

What's wrong?

like image 829
satoru Avatar asked Dec 25 '22 14:12

satoru


2 Answers

Nothing is wrong per se, but you bumped into buffering. Take out the sleep and you should see output pretty much immediately.

http://mywiki.wooledge.org/BashFAQ/009 is nominally a Bash question, but applies to any Unix-type I/O, and explains the issues thoroughly.

like image 112
tripleee Avatar answered Jan 07 '23 00:01

tripleee


An alternative to re-opening stdout as Andrea mentioned is to start up Python in unbuffered mode with the -u option:

python -u speaker.py | python -u listener.py
like image 20
ehaymore Avatar answered Jan 07 '23 00:01

ehaymore