## 5.9 How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)? 

In Python code, define an object that supports the write() method. Assign this object to sys.stdout and sys.stderr . Call print_error, or just allow the standard traceback mechanism to work. Then, the output will go wherever your write() method sends it. 

The easiest way to do this is to use the io.StringIO class: 

>>> import io , sys >>> sys.stdout =io .StringIO() >>> print('foo') >>> print('hello world! ') >>> sys.stderr.write(sys.stdout.getvalue()) foo hello world! 

A custom object to do the same would look like this: 

>>> import io , sys >>> classStdoutCatcher (io.TextIOBase): ... def __init__ (self): ... self.data =[] ... def write(self, stuff): ... self.data.append(stuff) ... >>> import sys >>> sys.stdout =StdoutCatcher() >>> print('foo') >>> print('hello world! ') >>> sys.stderr.write(''.join(sys.stdout.data)) foo hello world! 

## 5.10 How do I access a module written in Python from C? 

You can get a pointer to the module object as follows: 

module=PyImport_ImportModule( "<modulename> "); 

If the module hasn’t been imported yet (i.e. it is not yet present in$_{sys.modules}$ ), this initializes the module; otherwise it simply returns the value of sys.modules["<modulename>"] . Note that it doesn’t enter the module into any namespace – it only ensures it has been initialized and is stored in$_{sys.modules}$ . 

You can then access the module’s attributes (i.e. any name defined in the module) as follows: 

attr =PyObject_GetAttrString(module, "<attrname> "); 

Calling$_{PyObject_SetAttrString()}$ to assign to variables in the module also works. 

