Python Frequently Asked Questions, Release 3.9.5 5.9. How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)? 61 Calling$_{PyObject_SetAttrString()}$ to assign to variables in the module also works. attr =PyObject_GetAttrString(module, "<attrname> "); You can then access the module’s attributes (i.e. any name defined in the module) as follows: 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}$ . module=PyImport_ImportModule( "<modulename> "); You can get a pointer to the module object as follows: >>> 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! A custom object to do the same would look like this: >>> import io , sys >>> sys.stdout =io .StringIO() >>> print('foo') >>> print('hello world! ') >>> sys.stderr.write(sys.stdout.getvalue()) foo hello world! The easiest way to do this is to use the io.StringIO class: 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. 5.9 How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)? 5.10 How do I access a module written in Python from C?