Python子进程将数据定向到标准输入

Python subprocess directing data to standard intput

本文关键字:标准输入 数据 子进程 Python      更新时间:2023-10-16

我在Windows上有一个c++程序,可以从标准输入中读取字符。我想写一个Python脚本,打开这个c++程序,然后让脚本写入程序的标准输入。

我可以成功地在Python中创建子进程并从标准输出中读取。然而,该程序无法从Python脚本中接收任何来自标准的内容。程序使用ReadConsole()从标准文件中读取,它反复返回错误代码6(无效句柄),即使GetStdHandle()返回没有错误。

程序代码如下:

char buffer[GIDE_BUFFER_SIZE];
HANDLE hConsole_c = GetStdHandle(STD_INPUT_HANDLE);
DWORD chars_read = 0;
if(hConsole_c == INVALID_HANDLE_VALUE )
    {
    gide_printf(LOG_ERR,"ERROR: INVALID_HANDLE_VALUE for stdout: %d.", GetLastError());
    fflush(stdout);
    keyboard_handler_running = false;
    main_thread_running = false;
    }
else if( hConsole_c == NULL)
    {
    gide_printf(LOG_ERR,"ERROR: Unable to get handle to standard output.");
    fflush(stdout);
    keyboard_handler_running = false;
    main_thread_running = false;
    }
gide_printf(LOG_DEBUG,"keyboard_listener thread started.");
Sleep(500); //sleep to give time for everything to come up.
print_menu();
memset(buffer, 0, sizeof(buffer));
//reads characters from console after enter is pressed.
//enter key adds CR and a LF so it adds two chars to all output.
while(keyboard_handler_running)
    {
    if( ReadConsole( hConsole_c, buffer, sizeof(buffer), &chars_read, NULL ) == 0)
        {
        gide_printf(LOG_ERR,"ERROR: Reading from console failed: %d.", GetLastError());
        ErrorHandler("blah");
        continue;
        }
    gide_printf(LOG_DEBUG,"Read %d chars from console.", chars_read);
.
.
.
.

Python脚本:

import time
import subprocess
from subprocess import Popen, PIPE, STDOUT
print '0'
proc = subprocess.Popen('program.exe', stdout=None, stdin=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
time.sleep(2)
print '1'
proc.stdin.write('xtyasmdmdjmdhjmdmjdmjdn')
time.sleep(2)
print '2'
proc.stdin.close()
proc.stdout.close()
proc.kill()

MSDN提到了以下内容:虽然ReadConsole只能与控制台输入缓冲区句柄一起使用,但ReadFile可以与其他句柄(如文件或管道)一起使用。如果ReadConsole与标准句柄一起使用,则该标准句柄已被重定向为控制台句柄以外的其他内容。http://msdn.microsoft.com/en-us/library/windows/desktop/ms684958%28v=vs.85%29.aspx

我想知道这是否与此有关。

如果有人对如何做到这一点有任何建议,或者有更好的方法使用Python,请告诉我。

谢谢。

我想出了一个变通方法,可以让我们对问题的本质有一些了解。我在Visual Studio中使用Windows控制台项目工作。我创建了一个新的"空白项目",而不是使用ReadConsole()的Windows API,我使用std::cin.getline()的c++ API。这就解决了问题。

再一次,这不是一个解决方案,而是一个变通方法。但它表明问题似乎与Windows API或Visual Studio项目设置有关。