py 编译so

what

so 是c 编译的python 可执行文件

py 文件编译成so 即 py>c>so

 

代码

#!/usr/bin/env python
# -*- coding: utf-8 -*
# FileName: run ;
# Author: renoyuan
# e_mail: renoyuan@foxmail.com
# Date: 2021/12/23
# coding:utf-8
from distutils.core import setup
from Cython.Build import cythonize
import os
import shutil
'''
该文件的执行需要的在Terminal中输入 python compile_run.py build_ext --inplace
使用Cpython 编译python文件,关键函数编译成pyd文件(相当于dll)
'''


def gen_py_paths(root_path: str = "."):
   """
  编译 py 文件 并返回
  """
   return_path = []
   for root_, dirs_, files_ in os.walk(root_path, topdown=False):
       py_paths_ = []
       for file in files_:
           file_path: str = os.path.join(root_, file)
           if "compile_run.py" in file_path or "__init__.py" in file_path:
               continue
           elif file_path.endswith(".py"):
               py_paths_.append(os.path.join(root_, file))
       print("py_paths_", py_paths_)
       try:
           setup(
               name="zj table ocr",
               ext_modules=cythonize(py_paths_, language_level=3),
          )
       except Exception as e:
           print(e)
           continue
       return_path.extend(py_paths_)
   return return_path


py_paths = gen_py_paths()


'''
1、将编译后的pyd文件的命名更改成与原py文件一致
2、删除编译后得到的c文件和原py文件
'''
print("——————", os.getcwd(), "——————")
new_files = []
for root, dirs, files in os.walk(".", topdown=False):
   for name in files:
       if "compile_run.py" in name:
           continue
       elif name.endswith((".pyd", ".so", ".c")):
           new_files.append(os.path.join(root, name))


print("new_files", new_files)

for fi in new_files:
   if fi.__contains__(".pyd"):
       re_name = fi.split(".")[0] + ".pyd"
       print(re_name)
       os.rename(fi, re_name)
   elif fi.__contains__(".so"):
       re_name = fi.split(".")[0] + ".so"
       print(re_name)
       os.rename(fi, re_name)
   elif fi.__contains__(".c") or fi in py_paths:  # 删除py 和c 文件
       os.remove(fi)
       # if(fi in key_funs):
       #     os.remove(key_funs[key_funs.index(fi)])
   elif fi.__contains__("build"):
       shutil.rmtree("build")

 

命令

放在需要执行的同级目录下执行 这个代码会删掉原文件需要先做好备份

python compile_run.py build_ext --inplace

 

原文地址:https://www.cnblogs.com/renoyuan/p/15733578.html