VIDEOCUBE
[Cython] Python 에서 C 라이브러리를 이용해 보자 본문
Cython 은 CPython 확장 모듈을 생성하고 이를 이용하여 외부 함수 인터페이스와 실행 속도 향상과 외부 라이브러리의 연동을 보다 향상 시킬 수 있도록
고안된 컴파일 언어이다
Cython 은 pyx 확장명을 사용하고, 컴파일 과정을 통하여 파이썬에서 import 형태로 사용될 수 있다.
컴파일은 다음 setup.py 를 이용하여 컴파일 할 수 있다
mathx.pyx 만들기
def inverse(float x):
cdef float y
y = 1.0 / x
return y
setup.py 만들기
#!/usr/bin/env python
from distutils.core import setup
from Cython.Build import cythonize
setup(name = 'Cython Library', ext_modules = cythonize("*.pyx"))
python setup.py build_ext --inplace
Traceback (most recent call last):
File "setup.py", line 6, in <module>
from Cython.Build import cythonize
ImportError: No module named Cython.Build
cython 을 설치 해야 한다.
pip는 epel 에서 설치 했던 블로그를 참조 바란다.
pip install cython
root@linux-01:/data/source/cython> pip install cython
You are using pip version 7.1.0, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Collecting cython
/usr/lib/python2.6/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
Downloading Cython-0.27.3.tar.gz (1.8MB)
100% |████████████████████████████████| 1.8MB 204kB/s
build-98P98t/cython/Cython/Plex/Scanners.o
/tmp/pip-build-98P98t/cython/Cython/Plex/Scanners.c:19:20: error: Python.h: 그런 파일이나 디렉터리가 없습니다
/tmp/pip-build-98P98t/cython/Cython/Plex/Scanners.c:21:6: error: #error Python headers needed to compile C extensions, please install development version of Python.
error: command 'gcc' failed with exit status 1
그냥 지나가는 적이 없네 에효...
yum install python-devel
설치 완료
root@linux-01:/data/source/cython> pip install cython
You are using pip version 7.1.0, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Collecting cython
Using cached Cython-0.27.3.tar.gz
Installing collected packages: cython
Running setup.py install for cython
Successfully installed cython-0.27.3
build 완료
root@linux-01:/data/source/cython> tree
.
├── build
│ └── temp.linux-x86_64-2.6
│ └── mathx.o
├── mathx.c
├── mathx.pyx
├── mathx.so
└── setup.py
mathx.so 을 사용하도록 python 을 이용하여 코드를 작성해 보자
import 는 mathx 로 설정하였다.
root@linux-01:/data/source/cython> python
Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mathx
>>>
>>> mathx.inverse(3.0)
0.3333333432674408
>>>
'개발 > 파이썬' 카테고리의 다른 글
Python3 설치 (0) | 2018.02.02 |
---|---|
[Python] PIP 파이썬 패키지 매니져 설치하기 (0) | 2018.01.30 |