Come per la cattura di pitone stdout in codice C ++
-
29-09-2019 - |
Domanda
Ho un programma che nel corso di essa la corsa a volte ha bisogno di chiamare pitone al fine di preforme alcuni compiti. Ho bisogno di una funzione che chiama pitone e catture pitoni stdout e la mette in un certo file. Si tratta di una dichiarazione della funzione
pythonCallBackFunc(const char* pythonInput)
Il mio problema è quello di catturare tutto l'output pitone per un determinato comando (pythonInput). Non ho esperienza con Python API e non so che cosa è la tecnica giusta per fare questo. La prima cosa che ho provato è quello di sdtout e stderr reindirizzamento di pitone con Py_run_SimpleString questo è un esempio del codice che ho scritto.
#include "boost\python.hpp"
#include <iostream>
void pythonCallBackFunc(const char* inputStr){
PyRun_SimpleString(inputStr);
}
int main () {
...
//S0me outside functions does this
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("old_stdout = sys.stdout");
PyRun_SimpleString("fsock = open('python_out.log','a')");
PyRun_SimpleString("sys.stdout = fsock");
...
//my func
pythonCallBackFunc("print 'HAHAHAHAHA'");
pythonCallBackFunc("result = 5");
pythonCallBackFunc("print result");
pythonCallBackFunc("result = 'Hello '+'World!'");
pythonCallBackFunc("print result");
pythonCallBackFunc("'KUKU '+'KAKA'");
pythonCallBackFunc("5**3");
pythonCallBackFunc("prinhghult");
pythonCallBackFunc("execfile('stdout_close.py')");
...
//Again anothers function code
PyRun_SimpleString("sys.stdout = old_stdout");
PyRun_SimpleString("fsock.close()");
Py_Finalize();
return 0;
}
C'è un modo migliore per fare questo? Inoltre, per qualche ragione PyRun_SimpleString non fa nulla quando la situazione è un po 'di espressione matematica, per esempio PyRun_SimpleString ( "5 ** 3") non stampa (python conlsul stampe il risultato: 125)
forse è importante, io sto usando Visual Studio 2008. Grazie, Alex
modifiche che ho apportato secondo il suggerimento di Mark:
#include <python.h>
#include <string>
using namespace std;
void PythonPrinting(string inputStr){
string stdOutErr =
"import sys\n\
class CatchOut:\n\
def __init__(self):\n\
self.value = ''\n\
def write(self, txt):\n\
self.value += txt\n\
catchOut = CatchOut()\n\
sys.stdout = catchOut\n\
sys.stderr = catchOut\n\
"; //this is python code to redirect stdouts/stderr
PyObject *pModule = PyImport_AddModule("__main__"); //create main module
PyRun_SimpleString(stdOutErr.c_str()); //invoke code to redirect
PyRun_SimpleString(inputStr.c_str());
PyObject *catcher = PyObject_GetAttrString(pModule,"catchOut");
PyObject *output = PyObject_GetAttrString(catcher,"value");
printf("Here's the output: %s\n", PyString_AsString(output));
}
int main(int argc, char** argv){
Py_Initialize();
PythonPrinting("print 123");
PythonPrinting("1+5");
PythonPrinting("result = 2");
PythonPrinting("print result");
Py_Finalize();
return 0;
}
L'output che ottengo dopo l'esecuzione principale:
Here's the output: 123
Here's the output:
Here's the output:
Here's the output: 2
E 'un bene per me, ma solo un problema, dovrebbe essere
Here's the output: 123
Here's the output: 6
Here's the output:
Here's the output: 2
Non so perché, ma dopo l'esecuzione di questo comando: PythonPrinting ( "1 + 5"), comando restituisce PyString_AsString (uscita) una stringa vuota (char *) al posto di 6 ... :( C'è somthing non posso fare di perdere questa uscita?
Thaks, Alex
Soluzione
Se io sto leggendo la tua domanda correttamente, si desidera catturare output / error in una variabile all'interno del vostro C ++? È possibile farlo reindirizzando output / error in una variabile di pitone e poi l'interrogazione di questa variabile nel vostro C ++. Si prega di non che io non ho fatto il corretto conteggio ref di seguito:
#include <Python.h>
#include <string>
int main(int argc, char** argv)
{
std::string stdOutErr =
"import sys\n\
class CatchOutErr:\n\
def __init__(self):\n\
self.value = ''\n\
def write(self, txt):\n\
self.value += txt\n\
catchOutErr = CatchOutErr()\n\
sys.stdout = catchOutErr\n\
sys.stderr = catchOutErr\n\
"; //this is python code to redirect stdouts/stderr
Py_Initialize();
PyObject *pModule = PyImport_AddModule("__main__"); //create main module
PyRun_SimpleString(stdOutErr.c_str()); //invoke code to redirect
PyRun_SimpleString("print(1+1)"); //this is ok stdout
PyRun_SimpleString("1+a"); //this creates an error
PyObject *catcher = PyObject_GetAttrString(pModule,"catchOutErr"); //get our catchOutErr created above
PyErr_Print(); //make python print any errors
PyObject *output = PyObject_GetAttrString(catcher,"value"); //get the stdout and stderr from our catchOutErr object
printf("Here's the output:\n %s", PyString_AsString(output)); //it's not in our C++ portion
Py_Finalize();
return 0;
}
Altri suggerimenti
Ecco una soluzione amichevole C ++ ho sviluppato negli ultimi tempi.
spiego un paio di dettagli di esso sul mio blog: Python sys.stdout reindirizzamento in C ++ dove ho anche punto di repository GitHub al mio in cui versione più recente può essere trovata. Qui è completo esempio in base al codice corrente al momento del distacco questa risposta:
#include <functional>
#include <iostream>
#include <string>
#include <Python.h>
namespace emb
{
typedef std::function<void(std::string)> stdout_write_type;
struct Stdout
{
PyObject_HEAD
stdout_write_type write;
};
PyObject* Stdout_write(PyObject* self, PyObject* args)
{
std::size_t written(0);
Stdout* selfimpl = reinterpret_cast<Stdout*>(self);
if (selfimpl->write)
{
char* data;
if (!PyArg_ParseTuple(args, "s", &data))
return 0;
std::string str(data);
selfimpl->write(str);
written = str.size();
}
return PyLong_FromSize_t(written);
}
PyObject* Stdout_flush(PyObject* self, PyObject* args)
{
// no-op
return Py_BuildValue("");
}
PyMethodDef Stdout_methods[] =
{
{"write", Stdout_write, METH_VARARGS, "sys.stdout.write"},
{"flush", Stdout_flush, METH_VARARGS, "sys.stdout.flush"},
{0, 0, 0, 0} // sentinel
};
PyTypeObject StdoutType =
{
PyVarObject_HEAD_INIT(0, 0)
"emb.StdoutType", /* tp_name */
sizeof(Stdout), /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"emb.Stdout objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
Stdout_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
};
PyModuleDef embmodule =
{
PyModuleDef_HEAD_INIT,
"emb", 0, -1, 0,
};
// Internal state
PyObject* g_stdout;
PyObject* g_stdout_saved;
PyMODINIT_FUNC PyInit_emb(void)
{
g_stdout = 0;
g_stdout_saved = 0;
StdoutType.tp_new = PyType_GenericNew;
if (PyType_Ready(&StdoutType) < 0)
return 0;
PyObject* m = PyModule_Create(&embmodule);
if (m)
{
Py_INCREF(&StdoutType);
PyModule_AddObject(m, "Stdout", reinterpret_cast<PyObject*>(&StdoutType));
}
return m;
}
void set_stdout(stdout_write_type write)
{
if (!g_stdout)
{
g_stdout_saved = PySys_GetObject("stdout"); // borrowed
g_stdout = StdoutType.tp_new(&StdoutType, 0, 0);
}
Stdout* impl = reinterpret_cast<Stdout*>(g_stdout);
impl->write = write;
PySys_SetObject("stdout", g_stdout);
}
void reset_stdout()
{
if (g_stdout_saved)
PySys_SetObject("stdout", g_stdout_saved);
Py_XDECREF(g_stdout);
g_stdout = 0;
}
} // namespace emb
int main()
{
PyImport_AppendInittab("emb", emb::PyInit_emb);
Py_Initialize();
PyImport_ImportModule("emb");
PyRun_SimpleString("print(\'hello to console\')");
// here comes the ***magic***
std::string buffer;
{
// switch sys.stdout to custom handler
emb::stdout_write_type write = [&buffer] (std::string s) { buffer += s; };
emb::set_stdout(write);
PyRun_SimpleString("print(\'hello to buffer\')");
PyRun_SimpleString("print(3.14)");
PyRun_SimpleString("print(\'still talking to buffer\')");
emb::reset_stdout();
}
PyRun_SimpleString("print(\'hello to console again\')");
Py_Finalize();
// output what was written to buffer object
std::clog << buffer << std::endl;
}
Questo permette di uscita sys.stdout.write
intercettare con qualsiasi tipo di callable C ++ entità: funzione libera, la funzione di membro di classe, oggetti funzione citate o funzioni, anche anonime, come nell'esempio sopra dove io uso C ++ 11 lambda .
Nota, questo è un esempio minimo per presentare il concetto essenziale. Nel codice di produzione-pronto, ha bisogno sicuramente più attenzione di tutto il conteggio dei riferimenti di PyObject
, sbarazzarsi di stato globale, e così via.
So che questa domanda è vecchio, ma una parte della domanda non ha ancora ricevuto alcuna risposta:
"Come uscita cattura di comandi che non direttamente scrivere al stdout di Python, come:? 1 + 1"
Ecco i passaggi (per Python 3.4):
-
Redirect output / error in una variabile Python utilizzando la soluzione di Mark: https://stackoverflow.com/a/4307737/ 1046299
-
funzione di copia
PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
dal codice sorgente Python. Si trova nel file dipythonrun.c
-
Modifica il nome
PyRun_InteractiveOneObject
funzioni e la firma in modo che la nuova funzione richiede unconst char*
(il vostro comando) come primo parametro invece di unFILE*
. Allora si avrà bisogno di utilizzarePyParser_ASTFromStringObject
invece diPyParser_ASTFromFileObject
nell'implementazione della funzione. Si noti che è necessario copiare la funzionerun_mod
come è da Python in quanto è chiamato all'interno della funzione. -
Chiamare la nuova funzione con il comando, per esempio
1+1
. Stdout dovrebbe ora ricevere il2
uscita.