在C应用程序中嵌入Python
来自官方文件在C应用程序中嵌入Python,python,c,Python,C,来自官方文件 #define PY_SSIZE_T_CLEAN #include <Python.h> int main(int argc, char *argv[]) { wchar_t *program = Py_DecodeLocale(argv[0], NULL); if (program == NULL) { fprintf(stderr, "Fatal error: cannot decode argv[0]\n"); exit(1)
#define PY_SSIZE_T_CLEAN
#include <Python.h>
int main(int argc, char *argv[])
{
wchar_t *program = Py_DecodeLocale(argv[0], NULL);
if (program == NULL) {
fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
exit(1);
}
Py_SetProgramName(program); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print('Today is', ctime(time()))\n");
if (Py_FinalizeEx() < 0) {
exit(120);
}
PyMem_RawFree(program);
return 0;
}
我查阅了文档,但没有得出结果。据我所知,有多种方法可以完成这项微小的任务,而且还需要额外的几行代码。我希望您能给我一个关于这种方式的指导或解决方法。我希望我能找到一个更好的方法,但这种方法似乎有效,(如果我找到更好的解决方案,将更新): 如果在Python中定义了一个类来捕获
sys.stdout
写入:
import sys
class CatchOutErr:
def __init__(self):
self.value = ''
def write(self, txt):
self.value += txt
catchOutErr = CatchOutErr()
sys.stdout = catchOutErr
sys.stderr = catchOutErr
并且您将从这个句柄接收的值传递给C++,转换为字符串,等等…
#include <Python.h>
#include <iostream>
#include <stdio.h>
int main(int argc, char *argv[])
{
Py_Initialize();
PyObject *pModule = PyImport_AddModule("__main__"); //create main module
std::string stdOutErr = "import sys\nclass CatchOutErr:\n\tdef __init__(self):\n\t\tself.value = ''\n\tdef write(self, txt):\n\t\tself.value += txt\ncatchOutErr = CatchOutErr()\nsys.stdout = catchOutErr\nsys.stderr = catchOutErr\n";
PyRun_SimpleString(stdOutErr.c_str()); //invoke code to redirect
PyRun_SimpleString("from time import time,ctime\n"
"print('Today is', ctime(time()))\n");
PyObject *catcher = PyObject_GetAttrString(pModule, "catchOutErr"); //get our catchOutErr created above
PyObject *output = PyObject_GetAttrString(catcher,"value"); //get the stdout and stderr from our catchOutErr object
std::string s = PyString_AsString(output);
Py_DECREF(catcher);
Py_DECREF(output);
Py_DECREF(s);
std::cout << s;
return 0;
}
#包括
#包括
#包括
int main(int argc,char*argv[])
{
Py_初始化();
PyObject*pModule=PyImport\u AddModule(“\u main\u”);//创建主模块
std::string stdouerr=“导入系统\n类CatchOutErr:\n\tdef\uuuu init\uuuuuuuuuuuuself(self):\n\tdef write(self,txt):\n\t\tself.value+=txt\ncatchOutErr=CatchOutErr()\nsys.stdout=CatchOutErr\nsys.stderr=CatchOutErr\n”;
PyRun_SimpleString(stdOutErr.c_str());//调用代码重定向
PyRun_SimpleString(“从导入时间开始,ctime\n”
“打印('Today is',ctime(time()))\n”);
PyObject*catcher=PyObject_GetAttrString(pModule,“catchOutErr”);//获取上面创建的catchOutErr
PyObject*output=PyObject\u GetAttrString(catcher,“value”);//从catchOutErr对象获取stdout和stderr
std::string s=PyString\u AsString(输出);
Py_DECREF(捕手);
Py_DECREF(输出);
Py_DECREF(s);
std::您的问题中的示例代码似乎来自于。同一页上的详细解释了这一点。您需要什么具体信息?正如我在原始帖子的开头所述,代码已经来自官方文档页面。下一页的示例指向一个结构,该结构使用argum从脚本文件调用函数我想做的只是简单地分配PyRun_SimpleString()的输出一个字符数组,也就是说一个字符串变量。你为什么要打印输出?你不会在C中使用printf
。你为什么要在Python中使用print
?谢谢你的回答。从我的角度来看,你的方法似乎也行得通。
#include <Python.h>
#include <iostream>
#include <stdio.h>
int main(int argc, char *argv[])
{
Py_Initialize();
PyObject *pModule = PyImport_AddModule("__main__"); //create main module
std::string stdOutErr = "import sys\nclass CatchOutErr:\n\tdef __init__(self):\n\t\tself.value = ''\n\tdef write(self, txt):\n\t\tself.value += txt\ncatchOutErr = CatchOutErr()\nsys.stdout = catchOutErr\nsys.stderr = catchOutErr\n";
PyRun_SimpleString(stdOutErr.c_str()); //invoke code to redirect
PyRun_SimpleString("from time import time,ctime\n"
"print('Today is', ctime(time()))\n");
PyObject *catcher = PyObject_GetAttrString(pModule, "catchOutErr"); //get our catchOutErr created above
PyObject *output = PyObject_GetAttrString(catcher,"value"); //get the stdout and stderr from our catchOutErr object
std::string s = PyString_AsString(output);
Py_DECREF(catcher);
Py_DECREF(output);
Py_DECREF(s);
std::cout << s;
return 0;
}
...
PyObject *output = PyObject_GetAttrString(catcher,"value"); //get the stdout and stderr from our catchOutErr object
PyObject *encodedData = PyUnicode_AsEncodedString(output, "ascii", NULL);
Py_DECREF(output);
Py_DECREF(encodedData);
char* buf;
Py_ssize_t len;
PyBytes_AsStringAndSize(encodedData, &buf, &len);
std::cout << std::string(buf) << std::endl;