when embedding Python, how do you redirect stdout/stderr?

David Gravereaux davygrvy at pobox.com
Sun Jun 17 13:46:01 EDT 2001


Dave Kuhlman <dkuhlman at rexx.com> wrote:

>If you want to do it all in C, then I do _not_ have an answer for
>you.
>
>However, if you want to do some of it in Python and initiate it
>from C, then create a Python class with a "write" method and use
>PyRun_SimpleString to assign an instance of that class to
>sys.stdout.

Ok, now I'm stuck.  In my Py::Std class i'm sending it the address of 2
functions I'd like to call when text is sent to stdout and stderr.  I've gotten
that far, but now how do I make a python object of this?  Here's what I have so
far.  I got kinda dizzy looking at Modules/xxmodule.c for a starting point.

Any help would be most appreciated.
--
David Gravereaux <davygrvy at pobox.com>
-=[ More Famous and Original than the Ray's across the street Ray's Pizza, NYC ]=-
-------------- next part --------------
#include "PyStd.hpp"

typedef struct {
	PyObject_HEAD
	WriteFunc stdChan;
} StdObject;

staticforward PyTypeObject Std_Type;


Py::Std::Std (WriteFunc _stdOut, WriteFunc _stdErr)
    : stdOut(_stdOut), stdErr(_stdErr)
{
}

Py::Std::~Std()
{
}

void Py::Std::InitStd()
{
    StdObject *self;

    self = PyObject_New(StdObject, &Std_Type);
    self->stdChan = stdOut;
    PySys_SetObject("stdout", reinterpret_cast<PyObject *>(self));

    self = PyObject_New(StdObject, &Std_Type);
    self->stdChan = stdErr;
    PySys_SetObject("stderr", reinterpret_cast<PyObject *>(self));
}


static PyObject *
write (PyObject *self, PyObject *args)
{
    PyObject *ob;

    if (!PyArg_ParseTuple(args, "O", &ob)) return NULL;
    // write here.
    Py_INCREF(Py_None);
    return Py_None;
}

struct PyMethodDef std_methods[] = {
    {"write", write, METH_VARARGS},
    {0L, 0L}
};
-------------- next part --------------
/*
 ------------------------------------------------------------------------------
 * PyStd.hpp --
 *
 *   Link the standard channels.
 *
 * Copyright (c) 1999-2001 Tomahawk Software Group
 *
 * See the file "license.txt" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * RCS: @(#) $Id: TclHash.hpp,v 1.8 2000/12/14 10:52:46 daveg Exp $
 ------------------------------------------------------------------------------
 */
#ifndef INC_PyStd_hpp__
#define INC_PyStd_hpp__

#include <Python.h>

typedef void (*WriteFunc) (PyObject *);

namespace Py {
    class Std
    {
    private:
	WriteFunc stdOut;
	WriteFunc stdErr;
    protected:
	void InitStd();
    public:
	Std (WriteFunc _stdOut, WriteFunc _stdErr);
	~Std ();
    };
}	// namespace Py
#endif	// #ifndef INC_PyStd_hpp__


More information about the Python-list mailing list