(3.2) Overload print() using the C API?

Stefan Behnel stefan_ml at behnel.de
Fri Apr 27 04:55:48 EDT 2012


Peter Faulks, 27.04.2012 10:36:
> On 27/04/2012 5:15 PM, Stefan Behnel wrote:
>> Peter Faulks, 26.04.2012 19:57:
>>> I want to extend an embedded interpreter so that calls to print() are
>>> automagically sent to a C++ gui (windows exe) via a callback function in
>>> the DLL.
>>>
>>> Then I'll be able to do this:
>>>
>>> ----test.py----
>>> import printoverload
>>>
>>> printoverload.set_stdout()
>>> printoverload.set_stderr()
>>>
>>> print("this will be sent to a C function in printoverload.pyd")
>>> ---------------
>>
>> Why would you want to divert only "print" instead of changing sys.stdout in
>> general? Not all output comes from print calls.
>>
> Because I don't want to have to poll the stdout buffer.

You don't have to. It's delivered right at your door and even rings the
bell when it arrives to hand over the parcel in person.


> I want the script
> itself to update a window in the host application (via the extension) every
> time the script calls print().

Then replace sys.stdout (and maybe also sys.stderr) by another object that
does what you want whenever its write() method is called.


> But I guess that won't work if the script raises an exception...

Yep, you better catch those yourself. The C-API function you use for
executing the Python code in the first place will tell you when there was
an error.

BTW, my mention of Cython wasn't just a joke. You might want to look at it
because it makes these things essentially trivial compared to plain C-API
code in C.

Stefan




More information about the Python-list mailing list