Boost logo

Boost :

From: Xavier Defrang (xavier_at_[hidden])
Date: 2000-09-25 07:38:49


Hello,

I looked around py_cpp and its documentation and this
set of classes looks quite impressive : you did a great job!

As far as I've seen, you focused on extending Python with C++
objects. But what about embedding python in C++ code. I've been
thinking about a pystream which could be used as follow :

void foo()
{
   pystream s;
   s << "import sys" << endl;
     << "print 'Hello world from embedded Python'" << endl
     << "print 'This program runs on', sys.platform" << endl;
}

These are only my very early thoughts about that pystream concept.
I'm too newbie to the Python embedding API to figure out all the
possibities of such a class but I'm sure some Pythonholic persons
in here will spot me some ideas...

I've been already excited by the way I could use std::copy() to
execute programs! ;)

Here's a piece of code I wrote in about 3 minutes
just to see how it could work... So it doesn't follow
boost the guidelines at the moment.

<snip>

#ifndef _pystream_h_included
#define _pystream_h_included

#include <string>
#include <python/Python.h>

class pystream {

  string _buf;

public:

  typedef pystream& (*manipulator)(pystream& pys);

  pystream();
  pystream(int argc, char* argv[]);

  ~pystream();

  pystream& operator << (const string& s);
  pystream& operator << (manipulator m);

  friend pystream& endl(pystream& pys);

};

inline pystream::pystream() : _buf()
{
  Py_Initialize();
}

inline pystream::pystream(int argc, char* argv[]) : _buf()
{
  Py_SetProgramName(argv[0]);
  Py_Initialize();
  PySys_SetArgv(argc, argv);
}

inline pystream::~pystream()
{
  Py_Exit(0);
}

inline pystream& pystream::operator << (const string& s)
{
  _buf += s;
  return *this;
}

inline pystream& pystream::operator << (manipulator m)
{
  return m(*this);
}

pystream& endl(pystream& pys)
{
  PyRun_SimpleString((char*)pys._buf.c_str());
  pys._buf = "";
  return pys;
}

</snip>

I hope you'll make some feedback about this pystream idea whatever
you find it useful or pointless. ;)

Btw, about the naming contest I like Python++ very much!

Cheers,

 - Xavier


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk