我想使用CreateProcessW启动Python控制台,然后使用描述here的方法将一些命令发送到其stdin。该过程似乎已正确启动,但命令无效。
我尝试了相同的代码,将“python.exe”替换为其他可执行文件,它们工作正常:它们接收并响应发送的命令。
此外,我可以在新控制台中打开进程(使用 si.dwFlags ),但不显示任何输入/输出,因此很难获得任何反馈。现在,我已经尝试过发送“exit()”,它应该关闭进程,或其他应该产生副作用的代码。
所以:
我知道还有其他选择,比如在C中嵌入python解释器并使用PyRun_SimpleString(https://docs.python.org/2/extending/embedding.html),但我想知道为什么这种方法不适用于python.exe。
提前致谢。
-
启动进程的代码(对于python.exe,确实创建了一个新进程,并且CreateProcessW的返回值没问题):
STARTUPINFOW si;
PROCESS_INFORMATION pi;
SECURITY_ATTRIBUTES security_attributes;
WCHAR cmd[256] = L"python.exe";
DWORD _process_id;
HANDLE _input_read;
HANDLE _input_write;
HANDLE _output_read;
HANDLE _output_write;
security_attributes.nLength = sizeof(SECURITY_ATTRIBUTES);
security_attributes.bInheritHandle = TRUE;
security_attributes.lpSecurityDescriptor = NULL;
CreatePipe(&_output_read, &_output_write, &security_attributes, 0);
CreatePipe(&_input_read, &_input_write, &security_attributes, 0);
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
si.hStdInput = _input_read;
si.hStdOutput = _output_write;
si.hStdError = _output_write;
si.wShowWindow = SW_SHOW;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES | CREATE_NEW_CONSOLE;
ZeroMemory( &pi, sizeof(pi) );
if( CreateProcessW( NULL, // New command line window. No module name (use command line)
(LPWSTR)cmd, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
TRUE, // Set handle inheritance to FALSE
CREATE_NEW_CONSOLE, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi)) // Pointer to PROCESS_INFORMATION structure
{
_process_id = pi.dwProcessId;
_open_ok = true;
}
发送命令的代码(对于其他应用程序,它工作正常;对于python.exe,WriteFile返回值是OK, bytes_written 对应于命令字符串的长度,但没有效果)。
DWORD bytes_written;
if(!_open_ok) {
return FALSE;
}
if( !WriteFile(_input_write, cmd.c_str(), cmd.length(), &bytes_written, NULL)) {
return false;
}
else if(cmd.length() != bytes_written) {
return false;
}
return true;