栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在C ++代码中捕获python stdout

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在C ++代码中捕获python stdout

如果我正确地阅读了您的问题,您想将stdout / stderr捕获到C 中的变量中吗?您可以通过将stdout /
stderr重定向到python变量,然后将此变量查询到C
中来实现。请不要说我没有在下面做适当的引用计数:

#include <Python.h>#include <string>int main(int argc, char** argv){    std::string stdOutErr ="import sysnclass CatchOutErr:n    def __init__(self):n        self.value = ''n    def write(self, txt):n        self.value += txtncatchOutErr = CatchOutErr()nsys.stdout = catchOutErrnsys.stderr = catchOutErrn"; //this is python pre to redirect stdouts/stderr    Py_Initialize();    PyObject *pModule = Pyimport_AddModule("__main__"); //create main module    PyRun_SimpleString(stdOutErr.c_str()); //invoke pre to redirect    PyRun_SimpleString("print(1+1)"); //this is ok stdout    PyRun_SimpleString("1+a"); //this creates an error    PyObject *catcher = PyObject_GetAttrString(pModule,"catchOutErr"); //get our catchOutErr created above    PyErr_Print(); //make python print any errors    PyObject *output = PyObject_GetAttrString(catcher,"value"); //get the stdout and stderr from our catchOutErr object    printf("Here's the output:n %s", PyString_AsString(output)); //it's not in our C++ portion    Py_Finalize();    return 0;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/650398.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号