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,
相关文档:
从小老师就教导我们,不会做的题就选C,因为选择题选C的概率是最高的。事实上真是如此吗?今天我突发奇想,利用Google做了一个小实验。统计显示,答案选C的题果然是最多的!
Results 1 - 10 of about 364,000 for "这道题选A".
Results 1 - 10 of about 352,000 for "这道题选B".
Results 1 - 10 of about 521,000 for ......
可恶、可悲、可耻、可怜、可叹、可笑!!!
2009年10月15日,一个令广大python编程工作爱好者哭笑不得的事发生了——python的官方网站(http://www.python.org)被伟大的天朝给封了!
当时,有人说是因为有一个H网站和python的官网很像,封错了。于是,我试着打开了那个“相似的网站http://www.python.com ......
在paramiko中使用用户名和密码通过sftp传输文件,不使用key文件。
import getpass
import select
import socket
import traceback
import paramiko
def putfile():
#import interactive
# setup logging
paramiko.util.log_to_file('demo.log')
username = username
hostname = hostname
......
简单加密,用python来写写。
#coding=utf-8
'''
Description: 可逆的加密与解密
Environment: python2.5.x
Author:idehong@gmail.com
'''
import os
import sys
class Code(object):
'''可逆的加密与解密'''
def __init__(self, key = "idehong@gmail.com"):
self.__src_key ......
为了从字符串中提取时间,并进行比较,因此有了这个问题,如何将字符串转换成datetime类型
1.字符串与time类型的转换
>>> import time
>>> timestr = "time2009-12-14"
>>> t = time.strptime(timest ......