Come reindirizzare l'output interprete Python e lo prende in una stringa in programma in C ++?
-
30-09-2019 - |
Domanda
io sto usando pitone C ++ API per eseguire comandi Python da programma in C ++. Voglio prendere tutto l'output pitone in una stringa, sono riuscito dal seguente reindirizzamento, a pitoni cattura stdout e stderr uscita:
#python script , redirect_python_stdout_stderr.py
class CatchOutput:
def __init__(self):
self.value = ''
def write(self, txt):
self.value += txt
catchOutput = CatchOutput()
sys.stdout = catchOutput
sys.stderr = catchOutput
#C++ code
PyObject *pModule = PyImport_AddModule("__main__");
PyRun_SimpleString("execfile('redirect_python_stdout_stderr.py')");
PyObject *catcher = PyObject_GetAttrString(pModule,"catchOutput");
PyObject *output = PyObject_GetAttrString(catcher,"value");
char* pythonOutput = PyString_AsString(output);
Ma non so che cosa fare per catturare anche pitoni interprete uscita ....
Soluzione
L'interprete Python verrà eseguito all'interno del vostro C ++ processo, in modo tutta la sua uscita andrà al stderr e stdout del programma stesso ++ C. Come catturare questa uscita è descritto in questa risposta . Si noti che con questo approccio non sarà necessario per catturare l'uscita nello script Python più -. Basta lasciarlo andare a stdout e catturare tutto in una volta in C ++
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow