Python Script를 C/C++ 코드에서 실행시키기

less than 1 minute read

이런 기능을 전문용어로 Embedded Python이라고 한다.

대충 이런 이름의 패키지를 설치해주면 관련 라이브러리가 함께 설치된다. python-dev, python-devel, python2.7-dev

파이썬 도큐먼트에 친절하게도 샘플코드가 제공되고 있다.

test.c라는 파일을 생성한다.

#include

int main(int argc, char *argv[]) { Py_SetProgramName(argv[0]); /* optional but recommended */ Py_Initialize(); PyRun_SimpleString(“from time import time,ctime\n” “print ‘Today is’,ctime(time())\n”); Py_Finalize(); return 0; }

리눅스에서 컴파일하는건 참… 힘든일이다.

Ctrl+F5누르면 자동으로 되는거라고 배운 사람들에게는

하다보면 익숙해지겠지 오브젝트 파일까지만 생성되는거 # gcc -pthread -fno-strict-aliasing -fwrapv -Wall -Wstrict-prototypes -fPIC -std=c99 -O3 -fomit-frame-pointer -Isrc/ -I/usr/include/python2.7 -c test.c -o test.o 

실행파일이 생성되는거 # gcc -I/usr/include/python2.7 ptest.c -lpython2.7

컴파일을 하고 링크를 해야되잖아… libpython2.7.so를 써야되니까 gcc에 -lpython2.7을 써주면 되는거야

 

참고링크 http://www.cyberciti.biz/faq/debian-ubuntu-linux-python-h-file-not-found-error-solution/ http://docs.python.org/2/extending/embedding.html