9

I'm using the following command to run a shell command (creating a subprocess):

cmd = "ls"
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)

Then, I want to get its return code when it's finished. I should use wait() or poll()? It seems to me wait() is equal to a poll() enclosed in a busy wait. Something like:

while process.poll() == None:
    time.sleep(0.5)

I read that wait() could generate a deadlock if stdout/stderr buffer is filled. process.poll() used like above also could generate a deadlock? If this is true, I should use process.comunicate() to solve the problem? Nowadays, I only use process.comunicate() when I'm interested in the subprocess stdout/stderr.

Thanks in advance.

Dmitry Ginzburg
  • 7,391
  • 2
  • 37
  • 48
Alan Evangelista
  • 2,888
  • 6
  • 35
  • 45

1 Answers1

4

Yes. subprocess.poll, when used in a loop like that, will cause a deadlock if the stdout is piped into your process and you aren't reading from it. If you don't pipe stdout or you're consistently reading from it, neither poll nor wait will deadlock. subprocess.communicate will solve the deadlock in the cases it would occur. However, if you just want to run a command, check its return code, and get its output, use subprocess.check_output, which wraps all of that.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • 1
    subprocess.check_output was introduced in Python 2.7. I'm using Python 2.6, so I'll need to implement the solution manually. – Alan Evangelista Dec 12 '12 at 05:31
  • 2
    @AlanEvangelista: Obviously, this is a hack, but on systems with Python 2.6, I've just copied the 2.7 `subprocess.py` into the appropriate 2.6 directory and made a few syntax changes (no set literal notation in 2.6, if I recall) and it worked okay. – icktoofay Dec 12 '12 at 05:44