How to write Python scripts that work with Linux channels?

In speaker.pyI use printto output text to STDOUT:

import time

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

And in listener.pyI use inputto read from STDIN:

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

I am trying to connect these two scripts to a channel:

python speaker.py | python listener.py

But listner.pyit doesn’t display anything.

What's wrong?

+4
source share
2 answers

Nothing bad in itself, but you ran into buffering. Take it sleepout and you will see the result almost immediately.

http://mywiki.wooledge.org/BashFAQ/009 is a nominal Bash question, but applies to any Unix type I / O and explains the problems in detail.

+5
source

stdout, , Python -u:

python -u speaker.py | python -u listener.py
+5

Source: https://habr.com/ru/post/1607086/


All Articles