Algorithm-Gossip(4) 三色棋(Three_Color_Flag)

前言

This Series aritcles are all based on the book 《经典算法大全》; 对于该书的所有案例进行一个探究和拓展,并且用python和C++进行实现; 目的是熟悉常用算法过程中的技巧和逻辑拓展。

提出问题

Algorithm Gossip: 三色棋(Three_Color_Flag)

假设数组里面有若干个3种数 (1,2,3)要大的数靠后,小的数靠前,每次只能调换两个数,问怎么移动让次数最少。

原题目:绳子上有三种三色的旗, “蓝白红”按照这个顺序分离,每次换两个旗。方案让最小换的次数。

分析和解释

在一条绳子上移动,在程式中也就意味只能使用一个阵列,而不使用其它的阵列来作辅助,问
题的解法很简单,您可以自己想像一下在移动旗子,从绳子开头进行,遇到蓝色往前移,遇到
白色留在中间,遇到红色往后移,如下所示:
只是要让移动次数最少的话,就要有些技巧:
- 如果图中W所在的位置为白色,则W+1,表示未处理的部份移至至白色群组。
- 如果W部份为蓝色,则B与W的元素对调,而B与W必须各+1,表示两个群组都多了一个元素 。
- 如果W所在的位置是红色,则将W与R交换,但R要减1,表示未处理的部份减1。
注意B、W、R并不是三色旗的个数,它们只是一个移动的指标;什幺时候移动结束呢?一开始
时未处理的R指标会是等于旗子的总数,当R的索引数减至少于W的索引数时,表示接下来的旗
子就都是红色了,此时就可以结束移动

代码

c/c++ 实现

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BLUE 'b'
#define WHITE 'w'
#define RED 'r'
#define SWAP(x,y) { char temp; \
temp = color[x]; \
color[x] = color[y]; \
color[y] = temp; }
int main()
{
    char color[] = {'r', 'w', 'b', 'w', 'w','b', 'r', 'b', 'w', 'r', '\0'};
    int wFlag = 0;
    int bFlag = 0;
    int rFlag = strlen(color) - 1;
    int i;
    for(i = 0; i < strlen(color); i++)
        printf("%c ", color[i]);
    printf("\n");
    while(wFlag <= rFlag) {
        if(color[wFlag] == WHITE)
            wFlag++;
        else if(color[wFlag] == BLUE)
        {
            SWAP(bFlag,wFlag);
            bFlag++; wFlag++;
        }else
        {
            while(wFlag < rFlag && color[rFlag] == RED)
                rFlag--;
            SWAP(rFlag,wFlag);
            rFlag--;
        }
    }
    for(i = 0; i < strlen(color); i++)
        printf("%c ", color[i]);
    printf("\n");
    return 0;
}

python 实现

def printc(color):
    for i in range(len(color)):
        print(color[i],end = "")
    print()

color = ['r', 'w', 'b', 'w', 'w','b', 'r', 'b', 'w', 'r']
wFlag = 0;
bFlag = 0;
rFlag = len(color) - 1

printc(color)

while(wFlag <= rFlag):
    if(color[wFlag] == 'w'):
        wFlag+=1;
    elif(color[wFlag] == 'b'):
        color[bFlag],color[wFlag] = color[wFlag],color[bFlag] 
        bFlag+=1; wFlag+=1;
    else:
        while(wFlag < rFlag and color[rFlag] == 'r'):
            rFlag-=1
        color[rFlag],color[wFlag] = color[wFlag],color[rFlag] 
        rFlag-=1;

printc(color)

拓展和关联

有兴趣的可以尝试下,是不是最优解,用动态规划验证下。

后记

可以向dp状态转变。/后面再深究。

参考书籍

  • 《经典算法大全》
  • 维基百科
使用setup加密脚本成为pyd文件,代码如下:#!/usr/bin/env python # -*- coding: utf-8 -*- import os from pathlib import Path from Cython.Build import cythonize from setuptools import setup, Extension # 配置:指定要编译的根目录和相对包名 current_folder = Path(__file__).parent.absolute() root_dir = current_folder / "src" / "isc_agent_kit" if not os.path.exists(root_dir): raise Extension("当前脚本必须放置在 src 同级目录 !!!") package_name = "isc_agent_kit" # 对应的 Python 包路径 def get_extensions(root_dir, package_name): extensions = [] for root, _, files in os.walk(root_dir): for file in files: if file.endswith(".py"): file_path = os.path.join(root, file) rel_path = os.path.relpath(file_path, root_dir) # 正确处理:先 splitext 拿到无扩展名的路径,再替换 / module_name = os.path.splitext(rel_path)[0].replace(os.sep, ".") full_module_name = f"{package_name}.{module_name}" extensions.append( Extension( name=full_module_name, sources=[file_path], ) ) return extensions extensions = get_extensions(root_dir, package_name) setup( ext_modules=cythonize( extensions, compiler_directives={ 'language_level': 3, 'embedsignature': True, 'binding': True, }, ), options={'build_ext': {'inplace': True}}, ) 执行报错如下:(base) (.venv) PS D:\agent_frame_work\iscp-algorithm-foundation-ai> python setup.py build_ext --inplace Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\auth\_soa_auth.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\auth\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\autogen_extention\react_agent.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\autogen_extention\_agent_common.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\autogen_extention\_data_analysis_agent.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\autogen_extention\_smolagents_adapter.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\autogen_extention\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\config_utils\_config.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\config_utils\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\_common.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\_csv.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\_excel.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\_json.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\_request.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\_text.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\_yaml.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\_zip.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\log\_his_log.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\log\_langfuse_log.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\log\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\memory\_autogen_agent_state.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\memory\_postgre_checkpointer.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\memory\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\model_client\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\model_client\_autogen\_client.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\model_client\_autogen\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\model_client\_common\_common.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\model_client\_common\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\model_client\_langgraph\_client.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\model_client\_langgraph\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\postprocess_tools\_string_process.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\postprocess_tools\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\push_welink\push_welink.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\push_welink\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\query_rewrite\query_rewrite.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\query_rewrite\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\resource\setting.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\resource\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\s3\_hot_update_download.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\s3\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\self_awareness\agent_capability.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\self_awareness\self_awareness.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\self_awareness\__init__.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\vo\param.py because it changed. Compiling D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\vo\__init__.py because it changed. [ 1/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\__init__.py [ 2/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\auth\__init__.py [ 3/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\auth\_soa_auth.py [ 4/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\autogen_extention\__init__.py [ 5/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\autogen_extention\_agent_common.py [ 6/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\autogen_extention\_data_analysis_agent.py [ 7/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\autogen_extention\_smolagents_adapter.py [ 8/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\autogen_extention\react_agent.py [ 9/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\config_utils\__init__.py [10/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\config_utils\_config.py [11/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\__init__.py [12/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\_common.py [13/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\_csv.py [14/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\_excel.py [15/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\_json.py [16/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\_request.py [17/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\_text.py [18/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\_yaml.py [19/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\io_utils\_zip.py [20/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\log\__init__.py [21/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\log\_his_log.py [22/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\log\_langfuse_log.py [23/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\memory\__init__.py [24/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\memory\_autogen_agent_state.py [25/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\memory\_postgre_checkpointer.py [26/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\model_client\__init__.py [27/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\model_client\_autogen\__init__.py [28/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\model_client\_autogen\_client.py [29/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\model_client\_common\__init__.py [30/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\model_client\_common\_common.py [31/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\model_client\_langgraph\__init__.py [32/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\model_client\_langgraph\_client.py [33/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\postprocess_tools\__init__.py [34/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\postprocess_tools\_string_process.py [35/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\push_welink\__init__.py [36/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\push_welink\push_welink.py [37/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\query_rewrite\__init__.py [38/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\query_rewrite\query_rewrite.py [39/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\resource\__init__.py [40/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\resource\setting.py [41/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\s3\__init__.py [42/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\s3\_hot_update_download.py [43/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\self_awareness\__init__.py [44/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\self_awareness\agent_capability.py [45/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\self_awareness\self_awareness.py [46/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\vo\__init__.py [47/47] Cythonizing D:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\vo\param.py running build_ext building 'isc_agent_kit.__init__' extension creating build creating build\temp.win-amd64-3.11 creating build\temp.win-amd64-3.11\Release creating build\temp.win-amd64-3.11\Release\agent_frame_work creating build\temp.win-amd64-3.11\Release\agent_frame_work\iscp-algorithm-foundation-ai creating build\temp.win-amd64-3.11\Release\agent_frame_work\iscp-algorithm-foundation-ai\src creating build\temp.win-amd64-3.11\Release\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit D:\app\vsstudio\app\VC\Tools\MSVC\14.44.35207\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -ID:\agent_frame_work\iscp-algorithm-foundation-ai\.venv\include -IC:\Users\zwx1453293\AppData\Local\Programs\Python\Python311\include -IC:\Users\zwx1453293\AppData\Local\Programs\Python\Python311\Include -ID:\app\vsstudio\app\VC\Tools\MSVC\14.44.35207\include -ID:\app\vsstudio\app\VC\Auxiliary\VS\include -IC:\Program Files (x86)\Windows Kits\10\include\10.0.26100.0\ucrt -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.26100.0\\um -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.26100.0\\shared -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.26100.0\\winrt -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.26100.0\\cppwinrt /TcD:\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\__init__.c /Fobuild\temp.win-amd64-3.11\Release\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\__init__.obj __init__.c creating D:\agent_frame_work\iscp-algorithm-foundation-ai\build\lib.win-amd64-3.11 creating D:\agent_frame_work\iscp-algorithm-foundation-ai\build\lib.win-amd64-3.11\isc_agent_kit D:\app\vsstudio\app\VC\Tools\MSVC\14.44.35207\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:D:\agent_frame_work\iscp-algorithm-foundation-ai\.venv\libs /LIBPATH:C:\Users\zwx1453293\AppData\Local\Programs\Python\Python311\libs /LIBPATH:C:\Users\zwx1453293\AppData\Local\Programs\Python\Python311 /LIBPATH:D:\agent_frame_work\iscp-algorithm-foundation-ai\.venv\PCbuild\amd64 /LIBPATH:D:\app\vsstudio\app\VC\Tools\MSVC\14.44.35207\lib\x64 /LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.26100.0\ucrt\x64 /LIBPATH:C:\Program Files (x86)\Windows Kits\10\\lib\10.0.26100.0\\um\x64 /EXPORT:PyInit___init__ build\temp.win-amd64-3.11\Release\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\__init__.obj /OUT:build\lib.win-amd64-3.11\isc_agent_kit\__init__.cp311-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.11\Release\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\__init__.cp311-win_amd64.lib LINK : error LNK2001: 无法解析的外部符号 PyInit___init__ build\temp.win-amd64-3.11\Release\agent_frame_work\iscp-algorithm-foundation-ai\src\isc_agent_kit\__init__.cp311-win_amd64.lib : fatal error LNK1120: 1 个无法解析的外部命令 error: command 'D:\\app\\vsstudio\\app\\VC\\Tools\\MSVC\\14.44.35207\\bin\\HostX86\\x64\\link.exe' failed with exit code 1120
最新发布
11-13
你遇到的错误是使用 Cython 将 Python 脚本编译为 `.pyd` 文件时常见的链接错误: ``` LINK : error LNK2001: 无法解析的外部符号 PyInit___init__ fatal error LNK1120: 1 个无法解析的外部命令 ``` 这个错误的核心原因是:**Cython 无法为 `__init__.py` 文件生成有效的模块初始化函数 `PyInit___init__`,因为模块名 `__init__` 是非法或冲突的。** --- ### 🔍 错误原因分析 当你把 `__init__.py` 作为 Cython 编译目标时: - Cython 会尝试将其编译成一个名为 `__init__` 的扩展模块。 - C 扩展模块要求有唯一的初始化函数,例如 `PyInit_mymodule`。 - 但 `__init__` 是 Python 包机制中的特殊文件,其模块名在包内被视为“当前包”,而不能作为一个独立的可导入扩展模块存在。 - 更严重的是,`PyInit___init__` 这个函数名在 Windows MSVC 链接器中会导致命名冲突或不被正确识别。 > ⚠️ **结论:不能将 `__init__.py` 编译为 `.pyd`!它是包的元数据文件,不是普通模块。** --- ### ✅ 解决方案 #### ✅ 方案一:【推荐】排除所有 `__init__.py` 文件不参与编译 修改你的 `get_extensions` 函数,跳过 `__init__.py` 文件: ```python def get_extensions(root_dir, package_name): extensions = [] for root, _, files in os.walk(root_dir): for file in files: if file.endswith(".py") and file != "__init__.py": # 跳过 __init__.py file_path = os.path.join(root, file) rel_path = os.path.relpath(file_path, root_dir) module_name = os.path.splitext(rel_path)[0].replace(os.sep, ".") full_module_name = f"{package_name}.{module_name}" extensions.append( Extension( name=full_module_name, sources=[file_path], ) ) return extensions ``` 这样就不会尝试编译任何 `__init__.py`,避免了 `PyInit___init__` 的链接错误。 --- #### ✅ 方案二:保留 `__init__.py` 但保持为纯 Python(推荐做法) 即使你不加密 `__init__.py`,它仍然可以正常导入已编译的子模块。只要其他 `.py` 模块变成了 `.pyd`,就能实现大部分代码保护。 结构示例: ``` isc_agent_kit/ ├── __init__.py ← 纯 Python(明文) ├── auth/ │ ├── __init__.py ← 跳过(纯 Python 或空) │ └── _soa_auth.py ← 已编译为 .pyd └── autogen_extention/ └── react_agent.py ← 已编译为 .pyd ``` ✅ `__init__.py` 中仍可安全地 `from .auth import _soa_auth` —— 只要 `.pyd` 在对应位置即可。 --- #### ✅ 方案三:额外加固(可选)—— 使用空 `__init__.py` + 单独主入口 如果你希望进一步隐藏逻辑,可以把核心逻辑移到某个 `.py` 文件中(如 `core.py`),然后只暴露接口在 `__init__.py` 中,并且不清除 `__init__.py`。 --- ### 🛠 其他建议优化 1. **确保 `.pyd` 输出路径正确并覆盖原 `.py`** - 添加清理步骤,删除旧 `.py` 和 `.c` 文件。 - 或设置构建后移动 `.pyd` 到源目录,并删除 `.py`。 2. **添加异常处理和日志** ```python if not root_dir.exists(): raise FileNotFoundError(f"未找到源目录: {root_dir}") ``` 3. **使用 `setuptools.setup` 的 `package_data` 或自定义命令自动化部署** 4. **考虑使用 `cython --embed` 对主脚本加密(如果是可执行脚本)** --- ### ✅ 最终修复后的关键代码片段 ```python def get_extensions(root_dir, package_name): extensions = [] for root, _, files in os.walk(root_dir): for file in files: if file.endswith(".py") and file != "__init__.py": # 关键:跳过 __init__.py file_path = Path(root) / file rel_path = file_path.relative_to(root_dir) module_name = ".".join(rel_path.with_suffix("").parts) full_module_name = f"{package_name}.{module_name}" extensions.append( Extension( name=full_module_name, sources=[str(file_path)], ) ) return extensions ``` 然后运行: ```bash python setup.py build_ext --inplace ``` 你将会看到所有非 `__init__.py` 的文件成功编译为 `.pyd`,不再报错。 --- ### ❌ 不要做什么? - ❌ 不要试图编译 `__init__.py`、`setup.py` 或测试文件。 - ❌ 不要用中文路径或带空格/特殊字符的路径。 - ❌ 不要在没有安装 Visual Studio Build Tools 的情况下尝试编译(你已有,没问题)。 --- ### ✅ 验证是否成功 编译完成后,在 `isc_agent_kit/` 目录下应看到类似: ``` _soa_auth.cp311-win_amd64.pyd react_agent.cp311-win_amd64.pyd ... ``` 并且可以在 Python 中正常导入: ```python from isc_agent_kit.auth import _soa_auth ``` ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值