私は、実行中に時々いくつかのタスクを実行するためにpythonを呼び出す必要があるプログラムを持っています。私はPythonを呼び出す関数が必要で、はpythons stdoutをキャッチし、それをいくつかのファイルに置きます。 これは私の問題は、与えられたコマンド(pythonInput)についてすべてのpython出力をキャッチすることです関数の宣言C++コードでpython stdoutをキャッチする方法
pythonCallBackFunc(const char* pythonInput)
です。 私はPython APIに関する経験がなく、私はこれを行う正しい技法が何か分かりません。 私が試した最初のことはPythonのsdtoutとstderrをPy_run_SimpleStringを使ってリダイレクトすることです これは私が書いたコードのいくつかの例です。
#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;
}
これを行うより良い方法はありますか? PyRun_SimpleString( "5 ** 3")は何も表示しません(python conlsulは結果を出力します:125)
多分、私は視覚的に使用していますスタジオ2008年 おかげで、私はマークの提案に従って作った
変更 アレックス
:#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;
}
私はメイン実行した後に取得する出力:
それは私のために良いですが、唯一の問題は、それは私がなぜ知っているが、このコマンドを実行した後いけない
Here's the output: 123
Here's the output: 6
Here's the output:
Here's the output: 2
する必要があります:PythonPrintingを( "1 + 5")、PyString_AsString(出力)コマンドは6の代わりに空の文字列(char *)を返す... :(私はこの出力を失わないようにすることができますか?
Thaks、 アレックス
プログラミングに関する質問はStackOverflowにあります。 –