Python 3 输出重定向使用C/C++
Python 3 输出重定向使用C/C++
By:gddsky
目标
希望将Python 3的输出重定向到自定义的输出目标。
核心
Python使用sys.stdout、sys.stderr做输出目标,只要我们替换这两个值就可以重定向到我们自定义目标。替换的值的规则在Python的文档中sys (module)的sys.stdout上面说明只要添加一个write函数就可以了。像这样:
write(self, str)
我们只要在这个函数里面调用我们自己的输出函数就可以实现该目标了。
方案
在C++中写一个Python模块,并导入
在C++中利用PyRun_SimpleString建立一个PyObject去替换原始的sys.stdout、sys.stderr
搞定!!!
代码
模块定义部分代码(用python demo下的例子改写的)
static PyObject *console_write(PyObject *self, PyObject* args)
{
if (s_pyConsoleNotify != NULL)
{
const char* pMsgString=0;
if (!PyArg_ParseTuple( args, "s", &pMsgString ))
{
return NULL;
}
// 我们自己的输出函数
myprint(pMsgString);
}
Py_INCREF( Py_None );
return Py_None;
}
static PyMethodDef console_methods[] = {
{"test", console_test, METH_NOARGS, "Return the meaning of everything."},
{"write", console_write, METH_VARARGS, NULL},
{NULL, NULL} /* sentinel */
};
static struct PyModuleDef consolemodule = {
{}, /* m_base */
"console_capi", /* m_name */
0, /* m_doc */
0, /* m_size */
console_methods,
相关文档:
什么是回调函数?
简而言之,回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用为调用它所指向的函数时,我们就说这是回调函数。
为什么要使用回调函数?
因为可以把调用者与被调用者分开。调用者不关心谁是被调用者,所有它需知道的,只是存在 ......
代码如下:
#!/usr/bin/env python
# -*-coding:UTF-8-*-#
from common import *
import Image, ImageFilter, math, sys, os, random
def modifyImageObj(img, matrix) :
width, height = img.size
for h in range(0, height) :&n ......
from random import randint #导入随即函数
def guessNum(): &nbs ......
Python语言
: 导出邮箱里的联系人:支持Gmail,126,网易,搜狐,Hotmail,新浪,雅虎,MSN
#!/usr/bin/env python
#coding=utf-8
from
BeautifulSoup
import
BeautifulSoup
import
os
,
urllib
,
urllib2
,
pdb
import
cookielib
import
httplib
import
csv
,
re
GDATA_URL
=
'/accoun ......