Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #25912

Re: How to print stdout before writing stdin using subprocess module in Python?

From Nobody <nobody@nowhere.com>
Subject Re: How to print stdout before writing stdin using subprocess module in Python?
Date 2012-07-23 19:29 +0100
Message-Id <pan.2012.07.23.18.29.27.455000@nowhere.com>
Newsgroups comp.lang.python
References <6b50a02c-835a-41cb-83c9-8d051a516e38@googlegroups.com>
Organization Zen Internet

Show all headers | View raw


On Mon, 23 Jul 2012 06:01:23 -0700, Sarbjit singh wrote:

> proc = subprocess.Popen("cp -i a.txt b.txt", shell=True,
>  stdin=subprocess.PIPE, stdout=subprocess.PIPE,
>  stderr=subprocess.STDOUT,)
> stdout_val, stderr_val = proc.communicate()
> print stdout_val b.txt?
> 
> proc.communicate("y")
> 
> Now in this example if i read only stdout/stderr and prints it, later on
> if i try to write "y" or "n" based on user's input, i got an error that
> channel is closed. Can some one please help me on achieving this
> behavior in python such that i can print stdout first, then should take
> user input and write stdin later on.

You can't use .communicate() if you want an interact with the child
process. Any text given as an argument is sent to the child, then the
child's stdin is closed. Then it reads the child's stdout and/or stderr
until the child terminates.

If you want to interact with the child, you need to write to proc.stdin
and read from proc.stdout and/or proc.stderr. And you need to do this
asynchronously, i.e. you either need to use non-blocking I/O or multiple
threads, otherwise you risk deadlock. Look at the source code for the
.communicate() method in subprocess.py for examples (the Unix version uses
non-blocking I/O, the Windows version uses threads).

Even that may not be enough, as the child process may behave differently
if std{in,out,err} are pipes rather than a tty. Typically, stdin and
stdout are line-buffered when associated with a tty but block-buffered
otherwise (e.g. when associated with a pipe).

If pipes don't work, the only solution may be to run the child process on
a pseudo-tty (pty); see the pty module or the os.openpty() function.

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

How to print stdout before writing stdin using subprocess module in Python? Sarbjit singh <sarbjit1987@gmail.com> - 2012-07-23 06:01 -0700
  Re: How to print stdout before writing stdin using subprocess module in Python? Peter Otten <__peter__@web.de> - 2012-07-23 15:38 +0200
  Re: How to print stdout before writing stdin using subprocess module in Python? Nobody <nobody@nowhere.com> - 2012-07-23 19:29 +0100

csiph-web