2013-05-10 30 views
0

我在Windows上有一個C++程序,它從標準輸入中讀取字符。我想寫一個Python腳本來打開這個C++程序,然後讓腳本寫入程序的標準輸入。Python子進程將數據導向標準輸入

我可以在Python中成功創建子進程並從標準輸出讀取。但是,該程序無法通過Python腳本從標準輸入中接收任何內容。該程序使用ReadConsole()從標準中讀取,並且即使GetStdHandle()無誤返回,也會重複返回錯誤代碼6(無效句柄)。

下面是程序代碼:

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('xtyasmdmdjmdhjmdmjdmjd\n') 
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的任何建議,讓我知道。

感謝。

+0

'std :: cin.read()'有什麼問題? (可能有些東西 - 我的Windows覆蓋率現在很少/比較喜歡Linux)。 – 2013-05-10 01:09:42

+0

沒有。這不能解決它。 cin.getline(str,buffer_size)會重複返回0個字符。所以它可能以類似的方式失敗。它只是少通知爲什麼它的失敗。 – Bob 2013-05-10 16:35:29

+0

聽起來像流的錯誤,不可讀和/或EOF狀態。無論如何,爲了確認問題是在Python還是C++端,你可以檢查你是否可以輸入input_file | your_app'並從非鍵盤管道正確讀取它......如果是這樣,那麼它是python。如果沒有,'std :: string line;而(getline(std :: cin,line)){...}'是對標準輸入進行逐行解析的常用方法。 – 2013-05-11 06:15:32

回答

0

我想出了一個解決辦法這就給一些洞察到問題的本質。我在Visual Studio中使用Windows控制檯項目。我創建了一個新的「空白項目」,而是使用ReadConsole()的Windows API我使用了C++ API的std :: cin.getline()。這解決了這個問題。

再一次,這不是解決方法。但它表明問題似乎與Windows API或Visual Studio項目設置有關。

相關問題