Usage of stdout.close() in python's subprocess module when piping -


in python subprocess module, if wanted run shell command

foo | grep bar 

from within python, might use

p1 = popen(["foo"], stdout = pipe) p2 = popen(["grep", "bar"], stdin = p1.stdout, stdout = pipe) p1.stdout.close() output = p2.communicate()[0] 

i'm confused line p1.stdout.close(). if you'll forgive me, i'll trace through how think program works, , error reveal itself.

it seems me when line output = p2.communicate()[0] enacted python, python tries call p2, recognizes needs output p1. calls p1, executes foo , throws output on stack p2 can finish executing. , p2 finishes.

but in trace p1.stdout.close() happen. happening? seems me ordering of lines might matter too, following wouldn't work:

p1 = popen(["foo"], stdout = pipe) p1.stdout.close() p2 = popen(["grep", "bar"], stdin = p1.stdout, stdout = pipe) output = p2.communicate()[0] 

and that's status of understanding.

p1.stdout.close() necessary foo detect when pipe broken e.g., when p2 exits prematurely.

if there no p1.stdout.close() p1.stdout remains open in parent process , if p2 exits; p1 won't know nobody reads p1.stdout i.e., p1 continue write p1.stdout until corresponding os pipe buffer full , blocks forever.


Comments

Popular posts from this blog

Why can rails not find a route created by a helper? -

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -