PyRun_SimpleString
を使ってpythonのコードをべた書きし、cからpythonを走らせられるかと思い試行錯誤しています
https://blanktar.jp/blog/2013/05/use-python-by-c-lang.html
試しに次のコードをcで実行した結果
c
1 2#include <stdio.h> 3#include <Python.h> 4 5void set_path(void){ 6 PyObject *sys = PyImport_ImportModule("sys"); 7 PyObject *sys_path = PyObject_GetAttrString(sys, "path"); 8 PyObject *dir = PyUnicode_FromString("."); 9 PyList_Append(sys_path, dir); 10} 11 12int main(void){ 13 14 /* pythonインタラプタを初期化 */ 15 Py_Initialize(); 16 set_path(); 17 18 PyRun_SimpleString("def func():"); 19 PyRun_SimpleString("print('this printed by python')"); 20 PyRun_SimpleString("return ('byt, this printed by C')"); 21 /*PyRun_SimpleString("import cv2"); 22 PyRun_SimpleString("im = cv2.imread('teratail.jpg')"); 23 PyRun_SimpleString("cv2.imshow('1', im)"); 24 PyRun_SimpleString("cv2.waitKey()"); 25 PyRun_SimpleString("cv2.destroyAllwindows()"); */ 26 27 28 /* pythonインタラプタを終了 */ 29 Py_Finalize(); 30 return 0; 31 32} 33
File "<string>", line 1 def func(): ^ SyntaxError: unexpected EOF while parsing this printed by python File "<string>", line 1 SyntaxError: 'return' outside function
defで関数を定義した場合PyRun_SimpleStringを使用する際、インデントがなされていないため
SyntaxError: unexpected EOF while parsing
となってしまうのでしょうか?
SyntaxError: 'return' outside function
については以下のサイトから原因はわかりました
しかし対処方法までは...
もしかしたらインデントがないためpythonのreturnとcのreturnが同じ行ということなのでしょうか
http://www.tensorflowz.com/faq/html/Tensorflow_SyntaxError-return-outside-function-6F.html
試しにPyRun_SimpleStringの前にスペースで空白を作ったりdef func():の後ろにスペースを空けたりしたのですがかわりませんでした。
なにか策があれば教えてください
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/01 04:58