1. 実現したいこと
C++のプログラムから呼び出したPython プログラムの標準出力、標準エラー出力を変数に格納したいと考えています。
変数に格納する方法について、ご教示ください。
2. 該当のソースコード
cpp
#include <Python.h> #include <iostream> using namespace std; int main() { char mybuf[8192]; /* printf() displays the string inside quotation */ Py_Initialize(); setvbuf(stdout, mybuf, _IOFBF, sizeof(mybuf)); FILE *exp_file = fopen("./test.py", "r"); PyRun_SimpleFile(exp_file, "./test.py"); PyObject * module = PyImport_AddModule("__main__"); PyObject *result = PyObject_CallObject(module, NULL); cout << mybuf << endl; fflush(stdout); printf("Hello, World!"); return 0; }
python
def test(): try: // 処理 except Exception as e: print('エラーが発生しました', file=sys.stderr) sys.exit(1) if __name__ == '__main__': test() print("success main", file=sys.stdout)
3. 自分で調べたことや試したこと
標準出力の内容をmybufに格納できると思ったのですが、Pythonプログラムから出力している標準出力の内容は、変数mybufに格納されず、コンソールに出力がされました。
4. 使っているツールのバージョンなど補足情報
環境:CentOS7
※ Docker imageを使用
Python:3.6.8
GCC:4.8.5
参考になるかも
https://stackoverflow.com/questions/46632488/how-to-catch-python-3-stdout-in-c-code
まだ回答がついていません
会員登録して回答してみよう