Reassign or discard Popen().stdout from a server process

Nobody nobody at nowhere.com
Thu Feb 3 04:48:38 EST 2011


On Tue, 01 Feb 2011 08:30:19 +0000, John O'Hagan wrote:

> I can't keep reading because that will block - there won't be any more
> output until I send some input, and I don't want it in any case.
> 
> To try to fix this I added:
> 
> proc.stdout = os.path.devnull
> 
> which has the effect of stopping the server from failing, but I'm not
> convinced it's doing what I think it is.

It isn't. os.path.devnull is a string, not a file. But even if you did:

	proc.stdout = open(os.path.devnull, 'w')

that still wouldn't work.

> If I replace devnull in the above line with a real file, it stays empty
> although I know there is more output, which makes me think it hasn't
> really worked. 

It hasn't.

> Simply closing stdout also seems to stop the crashes, but doesn't that mean 
> it's still being written to, but the writes are just silently failing? In 
> either case I'm wary of more elusive bugs arising from misdirected stdout.

If you close proc.stdout, the next time the server writes to its stdout,
it will receive SIGPIPE or, if it catches that, the write will fail with
EPIPE (write on pipe with no readers). It's up to the server how it deals
with that.

> Is it possible to re-assign the stdout of a subprocess after it has started? 

No.

> Or just close it? What's the right way to read stdout up to a given
> line, then discard the rest?

If the server can handle the pipe being closed, go with that. Otherwise,
options include redirecting stdout to a file and running "tail -f" on the
file from within Python, or starting a thread or process whose sole
function is to read and discard the server's output.




More information about the Python-list mailing list