subprocess: reading from stdout hangs process termination, waiting for ENTER keyboard signal

MRAB google at mrabarnett.plus.com
Tue Apr 14 12:52:47 EDT 2009


giohappy wrote:
> Hello everyone.
> I'm trying to use subprocess module to launch a Windows console
> application. The application prints some results to standard output
> and then waits for the user to press any key to terminte. I can't
> control this behaviour, as the application is not mine...
> I'm stuck at the very first lines of my code. I'm trying to force
> process termination (even with proc.terminate()), and it works only if
> I don't read from stdout. If I do proc.stdout.read() the process
> hangs, and I have to manually press the keyboard to interrupt it.
> Probably it's due a low-level handle that is kept on the process
> stdout, waiting for the keypress event...
> 
> How can I solve it?
> Giovanni
> 
> ------- Code excerpt-------
> 
> proc = subprocess.Popen('the_app.exe',
>                        shell=True,
>                        stdout=subprocess.PIPE,
>                        )
> #stdout_value = proc.communicate()[0]
> stdout_value = proc.stdout.read()
> PROCESS_TERMINATE = 1
> handle = win32api.OpenProcess(PROCESS_TERMINATE, False, proc.pid)
> win32api.TerminateProcess(handle, -1)
> win32api.CloseHandle(handle)
> print stdout_value
> 
Try this:

proc = subprocess.Popen('the_app.exe',
                        shell=True,
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        )
stdout_value = proc.communicate("\n")[0]




More information about the Python-list mailing list