Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Popen.poll() and Popen.wait()

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.

like image 491
Alan Evangelista Avatar asked Dec 12 '12 04:12

Alan Evangelista


1 Answers

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.

like image 106
icktoofay Avatar answered Sep 21 '22 15:09

icktoofay