开发者

Python: subprocess.popen()

I have a question regarding subprocess.pop开发者_StackOverflow社区en():

If supposedly the command executed is in a while loop - is there any way for subprocess.popen() to detect it and exit after printing the first output?

Or is there any other way to do this and print the result?

As you see the following program executed on a linux machine just keeps on executing:

  >>> import os
  >>> import subprocess as sp
  >>> p = sp.Popen("yes", stdout=sp.PIPE)
  >>> result = p.communicate()[0]


The communicate method is only useful if the program being called is expected to terminate soon with relatively little output. In the case of your example, the "yes" program never terminates, so communicate never completes. In order to deal with subprocesses which execute indefinitely, and may produce a lot of output, you will need to include a loop which repeatedly calls p.poll() until p.poll() returns a value other than None, which would indicate that the process has terminated. While in this loop you should read from p.stdout and p.stderr to consume any output from the program. If you don't consume the output, the buffers may fill up and cause the program to block waiting to be able to write more output.

import subprocess
import time

p = subprocess.Popen("yes", stdout=subprocess.PIPE)
result = ""

start_time = time.time()

while (p.poll() is None):
  result += p.stdout.read(8192)
  time.sleep(1)
  if (time.time() - start_time) > 5:
    print "Timeout"
    break

print result

Note that the above example will run indefinitely until you kill the "yes" subprocess it is reading input from. If you want to detect that the process doesn't terminate, you can add a time check to the while loop, and jump out at some point once enough time has passed.

If you are certain that your subprocess will terminate of it's own accord, you can simply call communicate() and get back the output, but this does not work in your example for the reasons I explain above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜