Python—將py文件編譯成so文件


環境准備以及編寫測試腳本

1.安裝cython,以及gcc編譯環境

[root@localhost ~]# pip install cython

2.編寫測試腳本:test.py

def test():
	print("hello python!")
	
def add(a, b):
	print(a + b)
	return a + b

方法1:使用python自帶的setup.py來編譯so

1.編寫setup.py文件,與test.py在同一個包下面,注意:此包還要有__init__.py文件,方便導入。因此此包有三個py文件。setup.py文件內容如下:

from distutils.core import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("test.py")
)

2.然后運行下面命令。linux上會生成test.so文件。可以刪除test.py文件了。

[root@localhost ~]# python setup.py build_ext --inplace

3.測試test.so文件,可以直接調用。

>>> import test
>>> test.test()                    # hello python!

  

https://blog.csdn.net/linshenyuan1213/article/details/72677246

https://www.jianshu.com/p/231aa8796807

https://www.hiwendi.com/detail/20/

https://www.jb51.net/article/171076.htm


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM