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

Stefan Behnel stefan_ml at behnel.de
Sat Apr 28 14:56:26 EDT 2012


Peter Faulks, 27.04.2012 22:31:
> On 27/04/2012 6:55 PM, Stefan Behnel wrote:
>> 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.
> 
> OK, I _think_ I'm getting warmer... But I wonder, do I need to create new
> sys.stdout / sys.stderr objects? Can I not simply assign a custom C
> function to the write() methods of the existing sys.stdout / sys.stderr
> objects?

You can try it in Python code.

In any case, writing a class that does what you want is likely not more
than a few lines of Cython code, including the interaction with Qt. It's
certainly more involved in C code, but you can still write a part of it in
Python code there and just implement a write() function in C to stick it
into a regular Python class.

Stefan




More information about the Python-list mailing list