0

I want to start a background process to tail a file, then read from the output so far on demand, while continuing to tail the file. I've tried a few things using subprocess but haven't been able to make it work.

Here's what I tried:

tail = subprocess.Popen(['tail', '-f', 'file.txt'], stdout=subprocess.PIPE)
reader = tail.stdout

#do stuff

output = reader.read()  #spins

I considered using reader.readline() manually, but I can't figure out how to terminate the loop, since there won't be an EOF.

ewok
  • 20,148
  • 51
  • 149
  • 254
  • Did you try [this](http://stackoverflow.com/questions/1196074/how-to-start-a-background-process-in-python) yet? It also leads to the doc that has other suggestions. – idjaw Apr 01 '16 at 18:09
  • Perhaps pipe the data you want from outside of the process? Feels like ages about but I had a simple script for debugging memcache, full thing is here http://stackoverflow.com/questions/3670323/setting-smaller-buffer-size-for-sys-stdin You would still need to ctrl+c to break the cycle. – David Apr 01 '16 at 18:12
  • I'm not sure how that's helpful. That answer talks about starting a process and detaching it from the parent, but doesn't address reading the output of that process. I don't need (or want) to detach the process, I just want it running in the background. – ewok Apr 01 '16 at 18:13
  • @David requiring a CTRL+C is a dealbreaker. This needs to be fully automated and can't depend on user input. – ewok Apr 01 '16 at 18:14
  • One other idea, if you want to break a busy loop when there is no more data, what about tracking the time between reads. After ever successful read you could reset a val like "last_read" and then check it on every cycle of a busy loop until it reaches some sort of time limit you defined? – David Apr 01 '16 at 18:15
  • 2
    @ewok have you seen [this](http://stackoverflow.com/questions/12523044/how-can-i-tail-a-log-file-in-python) ? – idjaw Apr 01 '16 at 18:17
  • 1
    @idjaw That does it! thanks. – ewok Apr 01 '16 at 18:20

0 Answers0