1. 実現したいこと
C++のプログラムから呼び出したPython プログラムの標準出力、標準エラー出力を変数に格納したいと考えています。
変数に格納する方法について、ご教示ください。
2. 該当のソースコード
cpp
1#include <Python.h> 2#include <iostream> 3 4using namespace std; 5 6int main() 7{ 8 char mybuf[8192]; 9 10 /* printf() displays the string inside quotation */ 11 Py_Initialize(); 12 setvbuf(stdout, mybuf, _IOFBF, sizeof(mybuf)); 13 FILE *exp_file = fopen("./test.py", "r"); 14 PyRun_SimpleFile(exp_file, "./test.py"); 15 PyObject * module = PyImport_AddModule("__main__"); 16 PyObject *result = PyObject_CallObject(module, NULL); 17 cout << mybuf << endl; 18 fflush(stdout); 19 printf("Hello, World!"); 20 return 0; 21}
python
1def test(): 2 try: 3 // 処理 4 except Exception as e: 5 print('エラーが発生しました', file=sys.stderr) 6 sys.exit(1) 7 8if __name__ == '__main__': 9 test() 10 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

回答1件
あなたの回答
tips
プレビュー