Embedded python console and FILE* in python 3.2

Thomas Jollans t at jollybox.de
Mon Aug 8 17:31:38 CEST 2011


On 08/08/11 17:17, Francis Labarre wrote:
> Hello everyone,
> 
> I'm currently trying to port some embedded code from python 2.7 to
> python 3.2.
> 
> The current code replicate the basic behavior of the python interpreter
> in an
> MFC application. When a command is entered in our embedded interpreter, 
> we write it to a FILE* then transform this FILE* into a Python file with
> the api
> function PyFile_FromFile and assign it to python's stdin. We also assign
> another
> FILE* as python's stdout and stderr. We then call PyRun_InteractiveOne
> to execute
> the statement as the python interpreter normally would. Finally, we
> can easily retrieve
> the result of the execution from the output FILE*.
> 
> This is currently the only approach we have found that allows us to
> retrieve the 
> result of executing a statement exactly as the interpreter would.
> 
> The problem is that the implementation of files has changed in python 3
> and the function
> PyFile_FromFile has been removed.
> 
> Does anyone knows a way to achieve the same thing as this function
> either trough the io module
> or the python/C api? Or could there be a better approach to what we are
> trying to achieve?
> 
> Keep in mind that we need to obtain the result of any statement, i.e. :
> 
> If the command is "2+2" the result should be "4", if the command is
> "1/0" the result should be
> 
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> ZeroDivisionError: division by zero
> 
> 
> Thank you,
> 
> F.L.
> 
> 


I assume you could simply use PyFile_FromFd?

The more elegant solution might be to create custom Python file-like
objects for std{in,out,err} that communicate directly with your application.

Thomas



More information about the Python-list mailing list