Boost logo

Boost Users :

Subject: Re: [Boost-users] (Boost.Python) How to print from C++ to the same stream as Python's 'print' does?
From: Christopher Currie (christopher_at_[hidden])
Date: 2009-05-13 04:11:12

On Mon, May 11, 2009 at 2:17 PM, Early Ehlinger <earlye_at_[hidden]> wrote:
> Basically, you need to create a streambuf class that calls
> PySys_WriteStdout() inside your_streambuf_class::sync().

It's probably fairly straightforward to do this using Boost.Iostreams,
by creating a model of Sink:

include <Python.h>

#include <algorithm> // min
#include <iosfwd> // streamsize
#include <boost/iostreams/categories.hpp> // sink_tag
#include <boost/iostreams/stream.hpp> // stream
#include <boost/format.hpp> // format

class pysys_stdout_sink {
    typedef char char_type;
    typedef boost::iostreams::sink_tag category;

    std::streamsize write( const char* s, std::streamsize n ) {
        // PySys_WriteStdout truncates to 1000 chars
        static const std::streamsize MAXSIZE = 1000;

        std::streamsize written = std::min( n, MAXSIZE );
        PySys_WriteStdout( (boost::format("%%.%1%s") %
written).str().c_str(), s );

        return written;

boost::iostreams::stream<pysys_stdout_sink> pysys_stdout;

int main()
    pysys_stdout << "Hello, Python world!\n";


Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at