Python子进程将数据定向到标准输入
Python subprocess directing data to standard intput
我在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项目设置有关。
相关文章:
- 我的程序没有从文件中读取并输入数据
- 输入数据成员未按要求工作
- 从标准输入读取文件后读取用户输入
- 如何从标准输入中检测格式化输入错误?
- C++ - 标准输入环路
- 使用 pybind11 调用 Python 函数时避免复制输入数据
- 快速读取标准输入缓冲区,无需检查
- 将标准输入中的双精度存储在矢量中
- 如何将 getline 与标准输入一起使用?
- 从 C++ 中的标准输入迭代读取字节
- 使用 python 或 c ++ 中的 sql 根据输入数据输出输出示例
- C++计算标准输入的字数
- 标准 cpp 数据结构和线程互斥锁?
- 如何从 c++ 中的给定标准输入中获取每个字符的偏移量?
- c++用输入数据创建数组
- 为什么此代码从标准输入中少一个输入?
- 如何在C++中从标准输入中获取变量输入
- 线程不刷新数据,无法从标准输入获取所有数据
- c++在标准输入上写入数据,并从标准输出中获得输出
- Python子进程将数据定向到标准输入