Python 致命错误:无法获取随机数来初始化 Python
环境 Windows 10、VSC 15
使用 CreateProcessA winapi 并传递 lpenvironment 变量来使用脚本运行 python。
当 lpenvironment 传递 null 时,它工作正常。
如果我设置环境变量 PATH 和 PYTHONPATH = "paths",并传递 LPSTR(env.c_Str()),它会在运行时抛出上述错误。
python版本是3.5.6
有什么帮助吗?
更多细节。
- 我使用 CreateProcessA WINAPI 运行子进程 python.exe“C:\Program Files\endpoint\Python_ML\mlprocessor_server.py”。
- 我想使用两个环境变量“PYTHONPATH”和“PATH”运行子进程。
PYTHONPATH="C:\Program Files\endpoint\Python";"C:\Program Files\endpoint\Python\Scripts";"C:\Program Files\endpoint\Python\include";"C:\Program Files\endpoint \Python\Lib";"C:\Program Files\endpoint\Python\libs";"C:\Program Files\endpoint\Python\Lib\site-packages";"C:\Program Files\endpoint\Python_ML"
PATH="C:\Program Files\endpoint\Python";"C:\Program Files\endpoint\Python\Lib";"C:\Program Files\endpoint\Python\Scripts";"C:\Program Files\endpoint \Python\libs"
由于某种原因,CreateProcessA 中的第 7 个参数失败,如果为 null,则 python.exe 运行成功,否则打印“Fatal Python error: failed to get random number to Initialize Python”。
我设置参数的方式如下...
std::string Base = Configuration::getBasePath();
std::string environPython = Base;
environPython.append("\\Python;");
environPython.append(Base);
environPython.append("\\Python\\Scripts;");
environPython.append(Base);
environPython.append("\\Python\\include;");
environPython.append(Base);
environPython.append("\\Python\\Lib;");
environPython.append(Base);
environPython.append("\\Python\\libs;");
environPython.append(Base);
environPython.append("\\Python\\Lib\\site-packages;");
environPython.append(Base);
environPython.append("\\Python\\_ML;");
environPython.push_back('\0');
std::string environPath = Base;
environPath.append("\\Python;");
environPath.append(Base);
environPath.append("\\Python\\Lib;");
environPath.append(Base);
environPath.append("\\Python\\Scripts;");
environPath.append(Base);
environPath.append("\\Python\\libs;");
environPath.push_back('\0');
std::string cmd = Base;
cmd.append("\\Python\\python.exe");
std::string params = "\"";
params.append(cmd);
params.append("\" \"");
params.append(Base);
params.append("\\Python\\_ML\\mlprocessor_server.py\"");
std::map env = { { "PYTHONPATH", environPython.data() },
{ "PATH", environPath.data() }};
// example for generating block of strings
std::vector<char> envBlock;
std::for_each(env.begin(), env.end(),
[&envBlock](const std::pair<std::string, std::string> & p) {
std::copy(p.first.begin(), p.first.end(), std::back_inserter(envBlock));
envBlock.push_back('=');
std::copy(p.second.begin(), p.second.end(), std::back_inserter(envBlock));
envBlock.push_back('\0');
}
);
envBlock.push_back('\0');
// feed this into ::CreateProcess()
LPVOID lpEnvironment = (LPVOID)envBlock.data();
bool result = CreateProcessA(cmd.c_str(), (LPSTR)params.c_str(), NULL, NULL, FALSE, CREATE_NO_WINDOW, lpEnvironment, NULL, &info, &pi);
结果始终为真,python.exe 未显示在任务管理器中,并给出 Fatal Python 错误:无法获取随机数来初始化 Python。
如果 lpEnvironment 为 NULL,则 python.exe 将显示在任务管理器中。