Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a python script line-by-line using the C++ Python API

My goal is ultimately to execute a python script that manipulates values in my C++ program, one line at a time, returning execution to my C++ program between statements in the python script. Right now, I'm been attempting to feed the python interpreter my script one line at a time. But it wants a context, and I have no idea how to construct that. Can anyone point me to some good tutorials (the documentation is not very good for this).

I chose the answer that most closely answered my question, but I believe this may not be enough control for some applications. An answer that works for those applications might involve lower-level calls in the Python API. Please answer the question if you have an answer that grants more control over execution.

I Asked another question following this one, because I encountered different problems afterwards which are very closely related. Link: Python C API - Stopping Execution (and continuing it later)

like image 446
Miles Avatar asked Oct 10 '22 18:10

Miles


2 Answers

I think it will be difficult to feed a script one line at a time. Look into sys.settrace() to set a function that is invoked at each line of execution. You can also set it in the C API using PyEval_SetTrace, in a slightly different form.

like image 56
Ned Batchelder Avatar answered Oct 12 '22 08:10

Ned Batchelder


I am not 100% sure that I fully understand your goal, but some 8 months ago I wanted to do something similar. I wanted to be able to drive my c++ application from python scripts. I was on win32, Qt, gcc. It turns out that these days gdb, the debugger for gcc, can be scripted via python. It took me a lot of reading and few days of work, but it worked well. I did not have to add any extra code into my c++ sources!

like image 25
Radim Cernej Avatar answered Oct 12 '22 09:10

Radim Cernej