The introduction
Let's say I have a C++ app, with embedded python script. The Script does some heavy calculation, which take significant time to be ended. I can extract the result of the script, when it is finished. However it would be convenient, to know what is the actual stay of calculation - is it 10% or maybe half of job is done at the moment? Here's an example code (using boot python
):
app.cpp
#include <iostream>
#include <boost/python.hpp>
using namespace boost::python;
int main()
try
{
Py_Initialize();
object module = import("__main__");
object name_space = module.attr("__dict__");
exec_file("Script.py", name_space, name_space);
object MyFunc = name_space["MyFunc"];
object result = MyFunc();
double sum = extract<double>(sum);}
Py_Finalize();
Script.py
def MyFunc():
cont = 0
while (cont < 10000):
#...some calculations here, increasing "result" value on each step...
cont +=1
return result
The problem
If the code would be all in C++ I could use native framework tools like emit
, to access GUI progress bar slot, and update its value. But what in the case described above? In console app I could print cont
every time, directly from python. However it is not solution for any C++ with GUI. Is there any way to determinate, from C++ code level, on which lap of loop is the execution of Script.py
? Or maybe there is any other solution to serve the progress bar?
To sum up the conclusions from comment section: The problem can be solved by giving a callback to function called from python. The .cpp would look like this:
#include <iostream>
#include <boost/python.hpp>
using namespace boost::python;
int main(){
Py_Initialize();
object module = import("__main__");
object name_space = module.attr("__dict__");
exec_file("Script.py", name_space, name_space);
object MyFunc = name_space["MyFunc"];
object result = MyFunc();
double sum = extract<double>(sum);}
Py_Finalize();}
callback(int cont){
int cont_final = 10000;
double progr = cont / cont_final * 100;
cout << cont << "\n";}
Keep in mind that the callback need to be static member or free function (in this case I've shown the second option). If you need to pass also state (for example due of GUI), look HERE.
Python part would be:
def MyFunc(callback):
cont = 0
while (cont < 10000):
#...some calculations here, increasing "result" value on each step...
cont +=1
callback(cont) #Here we call progress update
return result
And that's it - in the results the progress indicator from 0 to 100 will be printed to console.