0

My python program prints a lot of output. But I often only need the start of it, so I pipe it to head. How can I change my program to exit once head is done?

example.py:

import time

for i in range(100):
    # Print some output
    print("x" * 100)
    # TODO: Exit here when 'head' is done
while True:
    # continue working
    time.sleep(1)

Currently, when I run python example.py | head -n10, I see 10 lines of output in the terminal, but the program keeps running.

How can I exit my python script as soon as head has received all of the output it requires?

ColBeseder
  • 3,579
  • 3
  • 28
  • 45
  • Possible duplicate of http://stackoverflow.com/questions/28315446/detect-when-reader-closes-named-pipe-fifo – Jim Stewart Nov 17 '16 at 08:51
  • What does `top` show when the python code is running, but head has printed all 10 lines. There might be a way to infer the pid of head and check for that, but it would be foolable. – Tristan Bodding-Long Nov 17 '16 at 09:20

0 Answers0