Awasu » Embedding Python: Writing a C++ wrapper library (part 2)
Sunday 30th November 2014 8:03 AM []

We'll start off by converting this example, that runs a Python script in an external file, to use the new wrapper library.

We'll add a method to the Interpreter class to run a specified script.

Interpreter::runSimpleFile( const char* pFilename )
    // open the file 
    FILE* fp ;
    errno_t rc = fopen_s( &fp , pFilename , "r" ) ;
    if ( rc != 0 || fp == NULL )
        throw Exception( "Can't open file." ) ;

    // run the script
    int rc2 = PyRun_SimpleFile( fp , pFilename ) ;
    if ( rc2 != 0 )
        Exception::translateException() ;

We open the specified file and call PyRun_SimpleFile(), raising an exception if anything goes wrong.

To run an external script, all we need to do is this:

Interpreter::runSimpleFile( "c:/temp/" ) ;


While we're here, let's add a method to run Python code from a string.

Interpreter::runSimpleString( const char* pCode )
    // run the string 
    int rc = PyRun_SimpleString( pCode ) ;
    if ( rc != 0 )
        Exception::translateException() ;
Download the source code here.

2 Responses to this post

This was an unexpected Christmas present for me! I've been struggling trying to add Python to a project we've had running at work, and these articles explained it all so clearly. Since the license for your sample code was quite liberal, we adapted some of it and got everything working. Thank you so much!

I've been looking at Awasu and it seems very interesting. We might be able to use it for another project we're starting in the new year.

Thanks for the feedback, glad it was helpful.

Stop in at the forums if you have any questions about Awasu, and drop me a line if you want to talk about your next project - I might be able to point out ways to use Awasu.

Have your say