P
P
pcdesign2021-01-24 11:02:38
linux
pcdesign, 2021-01-24 11:02:38

How to grab python output in console?

Here is an example script

import logging
from time import sleep
   
while True: 
    print('Hello') 
    logging.warning('I told you so')  
    logging.warning('Watch out!')     
    sleep(1)

python main.py 2>&1 | grep Watch

And everything works.
600d281b9569e036938492.png

But such number with print any more does not transit.
python main.py 2>&1 | grep Hello
We will get an empty console.

Is there a way to filter prints?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-02-10
@pcdesign

Python buffers output by default - it doesn't print to stdout right away.
If you wait a little longer, then grep will then immediately print a bunch of Hello when the buffer is full and will be output to stdout in its entirety.
You can do this at the time you want by calling sys.stdout.flush().

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question