0

I'm using python's subprocess to run a python script (let's call it script2.py), and that script is printing information to stdout which is redirected using PIPE. Problem is that script2.py stops printing information but it keeps running in the background. What i want is to detect that state (when nothing is written to stdout). Is there any way to do so?

I can simulate this behaviour with following:

script2.py

for i in range(0,1000):
    if i < 500:
        print "HUEHUE"

Next 500 iterations nothing will happen and that's what i need to detect in order to rerun the script.

Sir DrinksCoffeeALot
  • 593
  • 2
  • 11
  • 20
  • Why use subprocess when you could import the script and run it? – OneCricketeer Nov 03 '16 at 12:44
  • @cricket_007 while that is the ideal solution, sometimes you are working with scripts you haven't written and it's easier to just deal with the output then interact with the script. If he wrote it himself I totally agree with you. – bravosierra99 Nov 03 '16 at 12:54
  • Unfortunatelly `script2.py` was not written by me, i was given only the script that is running `script2.py` to detect "pause" state. – Sir DrinksCoffeeALot Nov 03 '16 at 13:08
  • 2
    On linux you can use [`select.select([p.stdout], [], [], timeout)`](https://docs.python.org/3/library/select.html#select.select) to wait at most `timeout` seconds for output on stdout, for a portable solution see [this](http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python) question – mata Nov 03 '16 at 13:17

1 Answers1

0

Popen.stdout If the stdout argument was PIPE, this attribute is a file object that provides output from the child process. Otherwise, it is None.

python documentation

So you probably need to decide an amount of time to wait before you consider your processes initial output to be done. So proc.stdout.readline() then sleep(1) then rinse and repeat.

bravosierra99
  • 1,331
  • 11
  • 23
  • Actually `script2.py` has to be run for 13 minutes, but the thing is that somewhere in those 13 minutes `script2.py` fails and needs to be run again from the beginning. That's why i need to detect that state and run it from the start to save some time. – Sir DrinksCoffeeALot Nov 03 '16 at 13:10
  • That's a completely different question. If you run subprocess.check-call it runs the script and throws an exception if it returns a non-zero return value. You could catch that and rerun the script if necessary – bravosierra99 Nov 03 '16 at 13:32