当前位置:   article > 正文

【Ubuntu】将多个python文件打包为.so文件

【Ubuntu】将多个python文件打包为.so文件

1.为什么要将python打包为.so文件?

保护源码

2.实战例子

a.安装相应的包
pip install cython

 验证安装是否成功

cython --version
b.实战的文件目录和内容 

hi.py

  1. # This is a sample Python script.
  2. # Press Shift+F10 to execute it or replace it with your code.
  3. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
  4. def print_hi(name):
  5. # Use a breakpoint in the code line below to debug your script.
  6. print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
  7. # Press the green button in the gutter to run the script.
  8. if __name__ == '__main__':
  9. print_hi('PyCharm')
  10. # See PyCharm help at https://www.jetbrains.com/help/pycharm/

hello.py

  1. def hello(name):
  2. print("hello " + name)

bye.py

  1. def bye(name):
  2. print("bye " + name)

 setup.py

把需要转换的py文件都放进去

  1. from distutils.core import setup
  2. from Cython.Build import cythonize
  3. setup(ext_modules = cythonize(["hi.py", "hello.py", "bye.py"]))

terminal运行命令

python setup.py build_ext

 运行log

  1. Compiling hi.py because it changed.
  2. Compiling hello.py because it changed.
  3. Compiling bye.py because it changed.
  4. [1/3] Cythonizing bye.py
  5. /home/huanglu/anaconda3/envs/segment-system/lib/python3.10/site-packages/Cython/Compiler/Main.py:381: FutureWarning: Cython directive 'language_level' not set, using '3str' for now (Py3). This has changed from earlier releases! File: /home/huanglu/Desktop/liubin/so-test/bye.py
  6. tree = Parsing.p_module(s, pxd, full_module_name)
  7. [2/3] Cythonizing hello.py
  8. /home/huanglu/anaconda3/envs/segment-system/lib/python3.10/site-packages/Cython/Compiler/Main.py:381: FutureWarning: Cython directive 'language_level' not set, using '3str' for now (Py3). This has changed from earlier releases! File: /home/huanglu/Desktop/liubin/so-test/hello.py
  9. tree = Parsing.p_module(s, pxd, full_module_name)
  10. [3/3] Cythonizing hi.py
  11. /home/huanglu/anaconda3/envs/segment-system/lib/python3.10/site-packages/Cython/Compiler/Main.py:381: FutureWarning: Cython directive 'language_level' not set, using '3str' for now (Py3). This has changed from earlier releases! File: /home/huanglu/Desktop/liubin/so-test/hi.py
  12. tree = Parsing.p_module(s, pxd, full_module_name)

 运行结果

 可以发现多了几个.c文件和build文件夹

build文件夹中

 

复制到根目录

 

在根目录里, 写一个demo.py

  1. from hi import print_hi
  2. from hello import hello
  3. from bye import bye
  4. print_hi("K.D.")
  5. hello("LeBron")
  6. bye("Kobe")

 运行

  1. Hi, K.D.
  2. hello LeBron
  3. bye Kobe
  4. Process finished with exit code 0

 把hi.py,hello.py,bye.py删除,再执行demo.py,可以得到同样的结果

即  此时已经使用到了.so文件,而不是原来的.py文件

如果.py在不同文件夹中,则在不同文件夹里面执行类似操作。

待续。。

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/205869
推荐阅读
相关标签
  

闽ICP备14008679号