Process.communicate And Getche() Fails
Solution 1:
Adam Rosenfield's answer is a sensible approach if you can modify the behavior of the called program. Otherwise, if you really need to write to the console input buffer, try PyWin32's win32console module. That said, I'm not sure how to get the character echo part working correctly when stdout is piped. It ends up printing to the start of the line.
C:
#include<stdio.h>intmain(int argc, char *argv[]){
int response;
printf("Enter \"a\": ");
response = getche();
printf("\nYou entered \"%c\" ", response);
return0;
}
/* gcc test_getch.c -o test_getch.exe */
Python:
import subprocess
import win32console
def make_buf(c):
buf = win32console.PyINPUT_RECORDType(win32console.KEY_EVENT)
buf.KeyDown = 1
buf.RepeatCount = 1
buf.Char = c
return buf
con_in = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
cmd = ["test_getch.exe"]
p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
buf = make_buf('a')
con_in.WriteConsoleInput([buf])
Solution 2:
getche
reads from the console, not from standard input. If your Python process is running in a console window, then your subprocess will still try reading input from that same console, not the pipe it's being passed in as standard input.
It might be possible to create another invisible console window, attach it to the subprocess, and feed it input, but that's very complicated and error-prone.
I'd recommend instead just rewriting your program to only read from standard input instead of using getche()
. If you really want to have it react to keystrokes without requiring the user to press Enter, then I'd suggest having it change its behavior depending on whether or not standard input is coming from a terminal. If it is, use getche
, and if not, just read directly from stdin
. You can test this using _isatty
(or the POSIX-equivalent isatty
; for some reason, Microsoft has decided to deprecate the POSIX name in their runtime). For example:
int ReadChar()
{
if(_isatty(0))
{
// stdin is a terminal
return _getche();
}
else
{
// stdin is not a terminal
return getchar();
}
}
Post a Comment for "Process.communicate And Getche() Fails"