如何在 C# 建置流程中原生管理 Python 依賴項
How to Manage Python Dependencies Natively inside C# Build Pipelines
DotNetPip 是開源 MSBuild 整合工具,可在標準 `.csproj` 建置目標中直接處理 Python 依賴項,並在執行 `dotnet build` 時還原 Python 環境及 pip 套件。它亦會將該環境提供給 C# 執行階段,讓用戶無須手動編寫外部環境設定指令碼。
Python has a massive ecosystem of AI, machine learning, and data science libraries like PyTorch, NumPy, and Transformers. While libraries like PythonNET allow us to call Python from C#, managing the underlying environment setup can be tedious:
- Installing CPython runtimes across different target environments
- Restoring
pippackages and virtual environments - Managing module search paths (
sys.path) and native.dll/.sobinaries
To streamline this workflow, I built DotNetPip, an open-source MSBuild integration that handles Python dependency resolution directly inside your standard .csproj build target.
How It Works
Instead of running external environment setup scripts, you declare your Python packages directly inside your project file:
<ItemGroup>
<PythonPackage Include="numpy" Version="1.26.4"/>
<PythonPackage Include="transformers" Version="4.38.0"/>
</ItemGroup>
When you run dotnet build, custom MSBuild tasks trigger behind the scenes to:
Ensure the Python environment and pip dependencies are restored.
Expose the environment in-process to your C# runtime.
Getting Started
- Add the DotNetPip package from NuGet:
dotnet add package DotNetPip - Declare your required Python dependencies in your .csproj.
- Run
dotnet build
The goal is to make using Python's AI/ML ecosystem feel like a first-class citizen inside the .NET toolchain without manual sidecar scripts.
Links & Resources
GitHub Repository: https://github.com/jaime-olivares/DotNetPip
Feedback, edge cases, and contributions are welcome!
來源:DEV Community · dev.to