【发布时间】:2014-06-08 21:33:20
【问题描述】:
在关注pythonembedding/extending tutorial时,我想出了以下代码
#include <boost/filesystem.hpp>
#include <Python.h>
static PyObject *
spam_system(PyObject *self, PyObject *args) {
const char *command;
int sts;
if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = system(command);
return PyLong_FromLong(sts);
}
static char SpamModuleName[] = "spam\000";
int main(int argc, char const *argv[]) {
Py_SetPath((
boost::filesystem::canonical("./python_lib.zip").wstring()
).c_str());
PyImport_AppendInittab(SpamModuleName,[](){
static PyMethodDef SpamMethods[] = {
{"system", spam_system, METH_VARARGS, "Execute a shell command."},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef spammodule = {
PyModuleDef_HEAD_INIT,
SpamModuleName,
NULL,
-1,
SpamMethods,
NULL, NULL, NULL, NULL
};
return PyModule_Create(&spammodule);
});
Py_Initialize();
PyRun_SimpleString(
"import spam\n"
"status = spam.system(\"ls -l\")\n"
);
Py_Finalize();
return 0;
}
代码编译良好(使用 g++ -std=c++11 main.cpp -lpython33.64 -lboost_filesystem -lboost_system -s 我使用 x64 native mingw toolchain by Stephan T. Lavavej)但是在运行我的程序时分配了大约 4 gig 的 ram 并且在 (procexp screenshot) 和 PyRun_SimpleString("import spam\n") 中有 100% 的 cpu 使用率比经常崩溃的蟒蛇MemoryError。
PyImport_ImportModule(SpamModuleName); 也使程序崩溃,在分配大量内存之后也是如此(事实上我从未成功运行过此函数)。
如果我结束所有其他程序并尽可能多地释放内存,则程序运行良好并产生预期的输出,但资源消耗使其无法使用。我在做什么错/是什么让 python 使用了这么多资源?
编辑在对 mingw-w64 irc 进行讨论后,我得到了它的工作,并将发布解决方案作为答案,以防其他人发现自己在我的位置
【问题讨论】: