実行中にいくつかのタスクを実行するためにPythonを呼び出す必要があるプログラムがあります。pythonを呼び出し、 pythons stdoutをキャッチして、それをファイルに入れる関数が必要です。これは関数の宣言です
pythonCallBackFunc(const char* pythonInput)
私の問題は、特定のコマンド(pythonInput)のすべてのPython出力をキャッチすることです。私はPythonAPIの経験がなく、これを行うための正しい手法がわかりません。私が最初に試したのは、Py_run_SimpleStringを使用してPythonのsdtoutとstderrをリダイレクトすることです。これは、私が作成したコードの例です。
#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は数式を取得しても何もしません。たとえば、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;
}
mainを実行した後に取得する出力:
Here's the output: 123
Here's the output:
Here's the output:
Here's the output: 2
それは私にとっては良いことですが、問題は1つだけです。
Here's the output: 123
Here's the output: 6
Here's the output:
Here's the output: 2
理由はわかりませんが、次のコマンドを実行した後:PythonPrinting( "1 + 5")、PyString_AsString(output)コマンドは6ではなく空の文字列(char *)を返します...:(これを失うことができない何かがありますか出力?
サックス、アレックス