build_all_to_so.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import os
  2. import re
  3. from setuptools import setup
  4. from setuptools.extension import Extension
  5. from Cython.Build import cythonize
  6. def build_current_dir():
  7. current_dir = os.path.dirname(os.path.abspath(__file__))
  8. # 要排除的 .py 文件(编译脚本、__init__.py 等)
  9. exclude_files = {"build_all_to_so.py", "__init__.py"}
  10. # 获取当前目录下所有可编译的 .py 文件
  11. py_files = [
  12. f for f in os.listdir(current_dir)
  13. if f.endswith(".py") and f not in exclude_files
  14. ]
  15. if not py_files:
  16. print("❗ 当前目录下没有需要编译的 .py 文件。")
  17. return
  18. # 创建 Extension 对象列表
  19. extensions = [
  20. Extension(
  21. name=os.path.splitext(f)[0],
  22. sources=[os.path.join(current_dir, f)]
  23. )
  24. for f in py_files
  25. ]
  26. try:
  27. setup(
  28. script_args=["build_ext", "--inplace"],
  29. ext_modules=cythonize(
  30. extensions,
  31. compiler_directives={"language_level": 3},
  32. ),
  33. )
  34. print("✅ 编译完成")
  35. except Exception as e:
  36. print("❌ 编译出错:", e)
  37. # 可选:删除生成的中间 .c 文件
  38. for f in py_files:
  39. c_file = os.path.join(current_dir, f.replace(".py", ".c"))
  40. if os.path.exists(c_file):
  41. os.remove(c_file)
  42. def rename_so_files():
  43. current_dir = os.path.dirname(os.path.abspath(__file__))
  44. pattern = re.compile(r"^(?P<name>.+?)\.cpython-[\d]+-[\w-]+\.so$")
  45. for f in os.listdir(current_dir):
  46. if f.endswith(".so"):
  47. m = pattern.match(f)
  48. if m:
  49. new_name = m.group("name") + ".so"
  50. old_path = os.path.join(current_dir, f)
  51. new_path = os.path.join(current_dir, new_name)
  52. print(f"Rename: {f} -> {new_name}")
  53. os.rename(old_path, new_path)
  54. if __name__ == "__main__":
  55. build_current_dir()
  56. rename_so_files()