### Example Dockerfile for Python Environment Setup Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/deployment.md This Dockerfile demonstrates integrating CSnakes.Stage into a build process. It installs the tool, sets up a Python environment with dependencies, and copies necessary artifacts into the final image. ```dockerfile FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base USER $APP_UID WORKDIR /app EXPOSE 8080 EXPOSE 8081 FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build ARG BUILD_CONFIGURATION=Release WORKDIR /src COPY ["ExampleApp/ExampleApp.csproj", "ExampleApp/"] RUN dotnet restore "ExampleApp/ExampleApp.csproj" COPY . . WORKDIR "/src/ExampleApp" RUN dotnet build "./ExampleApp.csproj" -c $BUILD_CONFIGURATION -o /app/build FROM build AS publish ARG BUILD_CONFIGURATION=Release RUN dotnet publish "./ExampleApp.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false RUN dotnet tool install --global CSnakes.Stage ENV PATH="/root/.dotnet/tools:${PATH}" RUN setup-python --python 3.12 --venv /app/venv --pip-requirements /src/ExampleApp/requirements.txt --verbose FROM base AS final WORKDIR /app COPY --from=publish /app/publish . COPY --from=publish /root/.config/CSnakes /home/app/.config/CSnakes COPY --from=publish /app/venv /app/venv ENTRYPOINT ["dotnet", "ExampleApp.dll"] ``` -------------------------------- ### Example requirements.txt Source: https://github.com/tonybaloney/csnakes/blob/main/docs/advanced/troubleshooting.md A sample requirements.txt file listing Python packages and their versions. Ensure this file is present and correctly formatted for pip installation. ```text # requirements.txt numpy==1.24.3 pandas==2.0.3 scikit-learn==1.3.0 ``` -------------------------------- ### Install CSnakes via .NET CLI and Project Template Source: https://context7.com/tonybaloney/csnakes/llms.txt Install the CSnakes project template and create a new Python application. This is the fastest way to start. ```bash dotnet new install CSnakes.Templates mkdir MyApp && cd MyApp dotnet new pyapp --PythonVersion 3.12 --PackageManager uv dotnet run ``` -------------------------------- ### Install Multiple Packages at Runtime Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/environments.md Install several packages simultaneously by providing a list of package names to the InstallPackages method. Ensure the virtual environment and package installer are set up. ```csharp await installer.InstallPackages(new[] { "attrs==25.3.0", "requests==2.31.0" }); ``` -------------------------------- ### Clone and Setup CSnakes Repository Source: https://github.com/tonybaloney/csnakes/blob/main/docs/community/contributing.md Clone your fork of the CSnakes repository and set up the upstream remote. Ensure you have the correct .NET SDKs and Python installed. ```bash git clone https://github.com/yourusername/CSnakes.git cd CSnakes git remote add upstream https://github.com/tonybaloney/CSnakes.git ``` -------------------------------- ### Install CSnakes Templates Source: https://github.com/tonybaloney/csnakes/blob/main/docs/getting-started/quick-start.md Install the CSnakes templates package to enable project creation. ```bash dotnet new install CSnakes.Templates ``` -------------------------------- ### Download Python, Create Virtual Environment, and Install Dependencies Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/deployment.md This command downloads Python, sets up a virtual environment, and installs packages listed in a requirements.txt file. Ensure the requirements file path is correct. ```bash setup-python --python 3.12 --venv /app/my-venv --pip-requirements /src/requirements.txt ``` -------------------------------- ### Install a Single Package at Runtime Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/environments.md Use the IPythonPackageInstaller to install a specific package version at runtime. This requires the virtual environment and package installer to be configured. ```csharp var installer = serviceProvider.GetRequiredService(); await installer.InstallPackage("attrs==25.3.0"); ``` -------------------------------- ### Install and Use CSnakes.Stage CLI Tool Source: https://context7.com/tonybaloney/csnakes/llms.txt Install the CSnakes.Stage global CLI tool to manage Python installations and virtual environments during Docker image builds. ```bash # Install the tool dotnet tool install -g CSnakes.Stage # Download Python 3.12 setup-python --python 3.12 # Download Python, create venv, and install dependencies setup-python --python 3.12 --venv /app/.venv --pip-requirements /src/requirements.txt --verbose ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/environments.md Use `.WithUvInstaller()` to leverage uv for faster package installation from `requirements.txt` or `pyproject.toml`. This method requires `WithVirtualEnvironment()` and respects `UV_CACHE_DIR` and `UV_NO_CACHE` environment variables. ```csharp services .WithPython() .WithVirtualEnvironment(Path.Join(home, ".venv")) .WithUvInstaller("requirements.txt"); // Optional - give the name of the requirements file, or pyproject.toml ``` -------------------------------- ### Install Dependencies with pip Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/environments.md The `.WithPipInstaller()` method installs packages listed in a `requirements.txt` file. If no path is provided, it defaults to looking for `requirements.txt` in the virtual environment directory. ```csharp services .WithPython() .WithVirtualEnvironment(Path.Join(home, ".venv")) .WithPipInstaller(); // Optional - installs packages listed in requirements.txt on startup ``` -------------------------------- ### Install CSnakes.Stage .NET Global Tool Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/deployment.md Install the CSnakes.Stage tool globally using the .NET CLI. This is a prerequisite for using the setup-python command. ```bash dotnet tool install -g CSnakes.Stage ``` -------------------------------- ### Phi-3 Inference Demo Setup Source: https://github.com/tonybaloney/csnakes/blob/main/samples/simple/README.md This Python script demonstrates invoking a Small Language Model (Phi3) using the 'transformers' package and PyTorch. Ensure PyTorch is installed according to its official instructions. ```python # This file contains a demo of using the "transformers" package from hugging face and pytorch to invoke a Small Language Model (Phi3) and complete an input string. # This demo requires the "transformers" and "torch" packages to be installed in the Python environment. # PyTorch has special requirements and should be installed per the instructions on the [PyTorch website](https://pytorch.org/get-started/locally/). ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/tonybaloney/csnakes/blob/main/docs/examples/sample-projects.md Commands to set up a Python virtual environment and install project dependencies from a requirements.txt file. This is necessary for samples that utilize Python packages. ```bash # Create virtual environment python -m venv .venv .venv\Scripts\activate # Windows source .venv/bin/activate # Linux/macOS # Install requirements pip install -r requirements.txt ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/tonybaloney/csnakes/blob/main/docs/community/contributing.md Restore the necessary .NET project dependencies after cloning the repository. ```bash dotnet restore ``` -------------------------------- ### Python Package Installation Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Runtime/PublicAPI/net8.0/PublicAPI.Shipped.txt Provides methods for installing Python packages. You can install specific packages by name or install packages listed in a requirements file. ```APIDOC ## InstallPackages ### Description Installs a list of Python packages. ### Method `IPythonPackageInstaller.InstallPackages(string[] packages)` ### Parameters * **packages** (string[]) - Required - An array of package names to install. ### Returns A task that represents the asynchronous operation. ``` ```APIDOC ## InstallPackagesFromRequirements (Home Directory) ### Description Installs Python packages from a requirements file located in the specified home directory. ### Method `IPythonPackageInstaller.InstallPackagesFromRequirements(string home)` ### Parameters * **home** (string) - Required - The path to the home directory containing the requirements file. ### Returns A task that represents the asynchronous operation. ``` ```APIDOC ## InstallPackagesFromRequirements (Specific File) ### Description Installs Python packages from a specified requirements file. ### Method `IPythonPackageInstaller.InstallPackagesFromRequirements(string home, string file)` ### Parameters * **home** (string) - Required - The path to the home directory. * **file** (string) - Required - The name of the requirements file. ### Returns A task that represents the asynchronous operation. ``` -------------------------------- ### Install Python and Dependencies in Dockerfile Source: https://github.com/tonybaloney/csnakes/blob/main/docs/advanced/troubleshooting.md A Dockerfile snippet to set up a .NET 8.0 environment, install Python 3 and pip, and then install Python dependencies from requirements.txt. ```dockerfile FROM mcr.microsoft.com/dotnet/aspnet:8.0 RUN apt-get update && apt-get install -y python3 python3-pip COPY requirements.txt ./ RUN pip3 install -r requirements.txt ``` -------------------------------- ### Minimal Python Example for Reproduction Source: https://github.com/tonybaloney/csnakes/blob/main/docs/advanced/troubleshooting.md A simple Python function to demonstrate a minimal reproducible example. ```python # minimal_example.py def simple_function(value: int) -> int: return value * 2 ``` -------------------------------- ### Install CSnakes.Runtime via .NET CLI Source: https://github.com/tonybaloney/csnakes/blob/main/docs/getting-started/installation.md Installs the CSnakes.Runtime NuGet package using the .NET Command Line Interface. ```bash dotnet add package CSnakes.Runtime ``` -------------------------------- ### Dockerfile for AOT + Python Deployment Source: https://github.com/tonybaloney/csnakes/blob/main/docs/advanced/native-aot.md A Dockerfile example for deploying a .NET Native AOT application with Python. It includes steps for installing Python, copying project files, restoring dependencies, publishing the application, and setting the entry point. ```dockerfile # Dockerfile for AOT + Python FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base WORKDIR /app # Install Python RUN apt-get update && apt-get install -y python3 python3-pip FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /src # Copy project files COPY ["AOTConsoleApp.csproj", "."] COPY ["*.py", "."] RUN dotnet restore "AOTConsoleApp.csproj" # Copy source and build COPY . . RUN dotnet publish "AOTConsoleApp.csproj" -c Release -r linux-x64 -o /app/publish FROM base AS final WORKDIR /app COPY --from=build /app/publish . ENTRYPOINT ["./AOTConsoleApp"] ``` -------------------------------- ### Python Package Installation Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Runtime/PublicAPI/net9.0/PublicAPI.Shipped.txt Provides methods for installing Python packages, either individually or from a requirements file. ```APIDOC ## InstallPackages ### Description Installs a list of specified Python packages. ### Method `IPythonPackageInstaller.InstallPackages(string[] packages)` ### Parameters - **packages** (string[]) - Required - An array of package names to install. ### Returns A task representing the asynchronous installation operation. ``` ```APIDOC ## InstallPackagesFromRequirements (Home Directory) ### Description Installs Python packages listed in a requirements file located within the specified home directory. ### Method `IPythonPackageInstaller.InstallPackagesFromRequirements(string home)` ### Parameters - **home** (string) - Required - The path to the home directory containing the requirements file. ### Returns A task representing the asynchronous installation operation. ``` ```APIDOC ## InstallPackagesFromRequirements (Specific File) ### Description Installs Python packages from a specific requirements file. ### Method `IPythonPackageInstaller.InstallPackagesFromRequirements(string home, string file)` ### Parameters - **home** (string) - Required - The path to the home directory. - **file** (string) - Required - The name of the requirements file. ### Returns A task representing the asynchronous installation operation. ``` -------------------------------- ### Install Packages from Requirements File at Runtime Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/environments.md Install packages listed in a requirements file by using the InstallPackagesFromRequirements method. This is useful for managing dependencies dynamically. ```csharp await installer.InstallPackagesFromRequirements("requirements.txt"); ``` -------------------------------- ### IPythonPackageInstaller Methods Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Runtime/PublicAPI/net8.0/PublicAPI.Shipped.txt Interface for installing Python packages. ```APIDOC ## IPythonPackageInstaller.InstallPackage ### Description Installs a specified Python package. ### Parameters #### Query Parameters - **package** (`string!`) - Required - The name of the package to install. ### Returns `System.Threading.Tasks.Task!` - A task representing the asynchronous installation operation. ``` -------------------------------- ### Python Dictionary Examples Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/type-system.md Demonstrates Python functions returning dictionaries for word counts and user lookups. ```python def word_count(text: str) -> dict[str, int]: words = text.split() return {word: words.count(word) for word in set(words)} def user_lookup() -> dict[int, str]: return {1: "Alice", 2: "Bob", 3: "Charlie"} ``` -------------------------------- ### Install CSnakes.Runtime via Package Manager Console Source: https://github.com/tonybaloney/csnakes/blob/main/docs/getting-started/installation.md Installs the CSnakes.Runtime NuGet package using the Package Manager Console in Visual Studio. ```powershell Install-Package CSnakes.Runtime ``` -------------------------------- ### Configure Python with Virtual Environment and Pip Installer Source: https://github.com/tonybaloney/csnakes/blob/main/docs/advanced/troubleshooting.md Set up the Python environment to use a virtual environment and automatically install requirements from a requirements.txt file. This is useful for managing project dependencies. ```csharp builder.Services .WithPython() .WithHome(pythonHome) .WithVirtualEnvironment(Path.Combine(pythonHome, ".venv")) .WithPipInstaller() // Installs requirements.txt automatically .FromRedistributable(); ``` -------------------------------- ### Python Type Stub Example Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/type-system.md An example of a Python type stub file (.pyi) defining function signatures without implementation. ```python def create(name: str, count: int) -> list[str]: ... ``` -------------------------------- ### Python Tuple Examples Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/type-system.md Illustrates Python functions returning tuples for names, ages, and coordinates. ```python def get_name_age() -> tuple[str, int]: return ("Alice", 30) def get_coordinates() -> tuple[float, float, float]: return (12.34, 56.78, 90.12) ``` -------------------------------- ### PythonLocationMetadata Properties and Constructor Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Runtime/PublicAPI/net8.0/PublicAPI.Shipped.txt Metadata describing a Python installation location. ```APIDOC ## PythonLocationMetadata Constructor ### Description Initializes a new instance of the `PythonLocationMetadata` class. ### Parameters #### Request Body - **Folder** (`string!`) - Required - The root folder of the Python installation. - **Version** (`System.Version!`) - Required - The version of the Python installation. - **LibPythonPath** (`string!`) - Required - The path to the Python library. - **PythonPath** (`string!`) - Required - The Python path. - **PythonBinaryPath** (`string!`) - Required - The path to the Python binary. - **Debug** (`bool`) - Optional - Indicates if the Python installation is a debug build. Defaults to false. - **FreeThreaded** (`bool`) - Optional - Indicates if the Python installation is free-threaded. Defaults to false. ``` ```APIDOC ## PythonLocationMetadata.Clone ### Description Creates a clone of the `PythonLocationMetadata` object. ### Returns `CSnakes.Runtime.Locators.PythonLocationMetadata!` - A cloned instance of the metadata. ``` ```APIDOC ## PythonLocationMetadata.Debug.get ### Description Gets a value indicating whether the Python installation is a debug build. ### Returns `bool` - True if it's a debug build, false otherwise. ``` ```APIDOC ## PythonLocationMetadata.Debug.init ### Description Initializes the debug property for the Python installation. ``` ```APIDOC ## PythonLocationMetadata.Deconstruct ### Description Deconstructs the `PythonLocationMetadata` object into its constituent parts. ### Returns `void` - Assigns values to the output parameters: Folder, Version, LibPythonPath, PythonPath, PythonBinaryPath, Debug, FreeThreaded. ``` ```APIDOC ## PythonLocationMetadata.Equals ### Description Determines whether the specified `PythonLocationMetadata` is equal to the current object. ### Parameters #### Request Body - **other** (`CSnakes.Runtime.Locators.PythonLocationMetadata?`) - Optional - The `PythonLocationMetadata` to compare with the current object. ### Returns `bool` - True if the specified object is equal to the current object; otherwise, false. ``` ```APIDOC ## PythonLocationMetadata.Folder.get ### Description Gets the root folder of the Python installation. ### Returns `string!` - The path to the Python installation folder. ``` ```APIDOC ## PythonLocationMetadata.Folder.init ### Description Initializes the folder property for the Python installation. ``` ```APIDOC ## PythonLocationMetadata.FreeThreaded.get ### Description Gets a value indicating whether the Python installation is free-threaded. ### Returns `bool` - True if it's free-threaded, false otherwise. ``` ```APIDOC ## PythonLocationMetadata.FreeThreaded.init ### Description Initializes the free-threaded property for the Python installation. ``` ```APIDOC ## PythonLocationMetadata.LibPythonPath.get ### Description Gets the path to the Python library file (e.g., libpython.so, pythonXY.dll). ### Returns `string!` - The path to the Python library. ``` ```APIDOC ## PythonLocationMetadata.LibPythonPath.init ### Description Initializes the libpython path property for the Python installation. ``` ```APIDOC ## PythonLocationMetadata.PythonBinaryPath.get ### Description Gets the path to the Python binary executable. ### Returns `string!` - The path to the Python binary. ``` ```APIDOC ## PythonLocationMetadata.PythonBinaryPath.init ### Description Initializes the Python binary path property for the Python installation. ``` ```APIDOC ## PythonLocationMetadata.PythonPath.get ### Description Gets the Python path environment variable value. ### Returns `string!` - The Python path. ``` ```APIDOC ## PythonLocationMetadata.PythonPath.init ### Description Initializes the Python path property for the Python installation. ``` ```APIDOC ## PythonLocationMetadata.Version.get ### Description Gets the version of the Python installation. ### Returns `System.Version!` - The version of the Python installation. ``` ```APIDOC ## PythonLocationMetadata.Version.init ### Description Initializes the version property for the Python installation. ``` -------------------------------- ### ServiceCollectionExtensions.FromRedistributable Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Runtime/PublicAPI/net8.0/PublicAPI.Shipped.txt Configures the Python environment builder to use a redistributable Python installation. ```APIDOC ## CSnakes.Runtime.ServiceCollectionExtensions.FromRedistributable ### Description Configures the `IPythonEnvironmentBuilder` to initialize a Python environment using a redistributable Python distribution. Overloads allow specifying version, debug mode, free-threaded build, and timeout. ### Overloads 1. **FromRedistributable(builder, debug = false, timeout = 360)** - `builder` (IPythonEnvironmentBuilder!): The builder instance. - `debug` (bool, optional): Whether to use a debug build. Defaults to `false`. - `timeout` (int, optional): Timeout in seconds for the operation. Defaults to `360`. 2. **FromRedistributable(builder, version, debug = false, freeThreaded = false, timeout = 360)** - `builder` (IPythonEnvironmentBuilder!): The builder instance. - `version` (RedistributablePythonVersion): The specific redistributable Python version. - `debug` (bool, optional): Whether to use a debug build. Defaults to `false`. - `freeThreaded` (bool, optional): Whether to use a free-threaded build. Defaults to `false`. - `timeout` (int, optional): Timeout in seconds for the operation. Defaults to `360`. 3. **FromRedistributable(builder, version, debug = false, freeThreaded = false, timeout = 360)** - `builder` (IPythonEnvironmentBuilder!): The builder instance. - `version` (string!): The desired Python version string. - `debug` (bool, optional): Whether to use a debug build. Defaults to `false`. - `freeThreaded` (bool, optional): Whether to use a free-threaded build. Defaults to `false`. - `timeout` (int, optional): Timeout in seconds for the operation. Defaults to `360`. ### Returns (IPythonEnvironmentBuilder!) The configured builder instance. ``` -------------------------------- ### ServiceCollectionExtensions.FromFolder Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Runtime/PublicAPI/net8.0/PublicAPI.Shipped.txt Configures the Python environment builder to use a Python installation located in a specific folder. ```APIDOC ## CSnakes.Runtime.ServiceCollectionExtensions.FromFolder ### Description Configures the `IPythonEnvironmentBuilder` to initialize a Python environment from a specified folder containing the Python installation. ### Method `static CSnakes.Runtime.IPythonEnvironmentBuilder! FromFolder(this CSnakes.Runtime.IPythonEnvironmentBuilder! builder, string! folder, string! version)` ### Parameters - `builder` (IPythonEnvironmentBuilder!): The builder instance. - `folder` (string!): The path to the folder containing the Python installation. - `version` (string!): The expected version of the Python installation. ### Returns (IPythonEnvironmentBuilder!) The configured builder instance. ``` -------------------------------- ### Basic setup-python Command Syntax Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/deployment.md The fundamental command structure for setup-python. Use this to understand the required and optional parameters. ```bash setup-python --python [options] ``` -------------------------------- ### Python Named Logger Example Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/logging.md Python code demonstrating how to get and use a named logger, which can then be selectively captured by CSnakes. ```python import logging logger = logging.getLogger("csnakes_logger") logger.info("Only this logger will send back") ``` -------------------------------- ### Configure Python Runtime from Folder Source: https://github.com/tonybaloney/csnakes/blob/main/docs/advanced/troubleshooting.md Specify an explicit folder path for the Python runtime in C#. Use this when the Python installation is not automatically discoverable. ```csharp builder.Services .WithPython() .WithHome(pythonHome) .FromFolder(@"C:\Python312", "3.12"); ``` -------------------------------- ### Generate and Use C# Bindings for Python HTTP Client Source: https://context7.com/tonybaloney/csnakes/llms.txt Example of using generated C# bindings to interact with a Python HTTP client. The `http_client` package must be installed in the Python environment. ```csharp // Generated module (http_client package must be installed in the Python env): // public IReadOnlyDictionary Get(string url); // public IReadOnlyDictionary Post(string url, IReadOnlyDictionary data); // public IReadOnlyDictionary Delete(string url); var client = env.HttpClient(); var response = client.Get("https://httpbin.org/get"); Console.WriteLine(response["url"]); var body = new Dictionary { ["key"] = "value" }; // IReadOnlyDictionary is lazily marshalled — values converted only on access var postResponse = client.Post("https://httpbin.org/post", body); ``` -------------------------------- ### Build and Run Commands Source: https://github.com/tonybaloney/csnakes/blob/main/docs/getting-started/first-example.md Standard .NET CLI commands to build and run the C# application. ```bash dotnet build ``` ```bash dotnet run ``` -------------------------------- ### Locate Python via Windows Installer Source: https://github.com/tonybaloney/csnakes/blob/main/docs/advanced/additional-locators.md Finds the Python runtime on Windows, assuming it was installed from the official Python installer from python.org. ```csharp var pythonBuilder = services.WithPython() .FromWindowsInstaller("3.12"); ``` -------------------------------- ### View Template Help Source: https://github.com/tonybaloney/csnakes/blob/main/docs/getting-started/quick-start.md Display help information for the `pyapp` template to explore available options. ```bash dotnet new pyapp -h ``` -------------------------------- ### Minimal C# Program for Reproduction Source: https://github.com/tonybaloney/csnakes/blob/main/docs/advanced/troubleshooting.md A minimal C# program demonstrating how to integrate and use a Python function, useful for creating reproducible examples. ```csharp // Minimal C# program var builder = Host.CreateApplicationBuilder(); builder.Services .WithPython() .WithHome(".") .FromRedistributable(); var app = builder.Build(); var env = app.Services.GetRequiredService(); var module = env.MinimalExample(); var result = module.SimpleFunction(5); Console.WriteLine($"Result: {result}"); ``` -------------------------------- ### Locate Python via MacOS Installer Source: https://github.com/tonybaloney/csnakes/blob/main/docs/advanced/additional-locators.md Finds the Python runtime on macOS, assuming it was installed from the official Python installer from python.org. ```csharp var pythonBuilder = services.WithPython() .FromMacOSInstaller("3.12"); ``` -------------------------------- ### Compare Build Times: Regular vs. AOT Source: https://github.com/tonybaloney/csnakes/blob/main/docs/advanced/native-aot.md Demonstrates the difference in build times between a regular .NET build and a Native AOT publish command. AOT compilation typically takes longer. ```bash # Regular build dotnet build # ~5-10 seconds ``` ```bash # AOT build dotnet publish -r win-x64 # ~30-60 seconds ``` -------------------------------- ### Navigate to Sample Directory Source: https://github.com/tonybaloney/csnakes/blob/main/docs/examples/sample-projects.md Command to change the current directory to a specific sample project within the CSnakes samples directory. ```bash cd simple/QuickConsoleTest ``` -------------------------------- ### Python Package Installer Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Runtime/PublicAPI/net10.0/PublicAPI.Unshipped.txt Interfaces for installing Python packages, either from requirements files or individual packages. ```APIDOC ## InstallPackagesFromRequirements (file) ### Description Installs Python packages listed in a requirements file from the specified home directory. ### Method Signature CSnakes.Runtime.PackageManagement.IPythonPackageInstaller.InstallPackagesFromRequirements(string! home, string! file) -> System.Threading.Tasks.Task! ``` ```APIDOC ## InstallPackagesFromRequirements (home) ### Description Installs Python packages listed in the default requirements file (e.g., 'requirements.txt') from the specified home directory. ### Method Signature CSnakes.Runtime.PackageManagement.IPythonPackageInstaller.InstallPackagesFromRequirements(string! home) -> System.Threading.Tasks.Task! ``` ```APIDOC ## InstallPackage ### Description Installs a single Python package by its name. ### Method Signature CSnakes.Runtime.PackageManagement.IPythonPackageInstaller.InstallPackage(string! package) -> System.Threading.Tasks.Task! ``` ```APIDOC ## InstallPackages ### Description Installs multiple Python packages by their names. ### Method Signature CSnakes.Runtime.PackageManagement.IPythonPackageInstaller.InstallPackages(string![]! packages) -> System.Threading.Tasks.Task! ``` -------------------------------- ### Build and Test CSnakes Project Source: https://github.com/tonybaloney/csnakes/blob/main/docs/community/contributing.md Commands to build the entire solution, run all unit tests, and serve the documentation locally using MkDocs. ```bash dotnet build dotnet test mkdocs serve ``` -------------------------------- ### ServiceCollectionExtensions.FromMacOSInstallerLocator Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Runtime/PublicAPI/net8.0/PublicAPI.Shipped.txt Configures the Python environment builder to use a Python installation found via the macOS installer locator. ```APIDOC ## CSnakes.Runtime.ServiceCollectionExtensions.FromMacOSInstallerLocator ### Description Configures the `IPythonEnvironmentBuilder` to initialize a Python environment by locating it using the macOS installer locator mechanism. ### Method `static CSnakes.Runtime.IPythonEnvironmentBuilder! FromMacOSInstallerLocator(this CSnakes.Runtime.IPythonEnvironmentBuilder! builder, string! version, bool freeThreaded = false)` ### Parameters - `builder` (IPythonEnvironmentBuilder!): The builder instance. - `version` (string!): The desired Python version. - `freeThreaded` (bool, optional): Whether to use a free-threaded Python build. Defaults to `false`. ### Returns (IPythonEnvironmentBuilder!) The configured builder instance. ``` -------------------------------- ### Example Usage of TransformersSharp Pipelines Source: https://github.com/tonybaloney/csnakes/blob/main/docs/examples/projects-using-csnakes.md Demonstrates how to initialize and use various ML pipelines like text classification, text generation, and image classification within a C# application using the TransformersSharp library. ```csharp using TransformersSharp; // Text classification var classifier = new TextClassificationPipeline("cardiffnlp/twitter-roberta-base-sentiment-latest"); var result = classifier.Predict("I love using CSnakes with TransformersSharp!"); // Text generation var generator = new TextGenerationPipeline("gpt2"); var generated = generator.Generate("The future of AI is", maxLength: 50); // Image classification var imageClassifier = new ImageClassificationPipeline("google/vit-base-patch16-224"); var prediction = imageClassifier.Predict("path/to/image.jpg"); ``` -------------------------------- ### Configure Python Runtime with Redistributable Locator Source: https://github.com/tonybaloney/csnakes/blob/main/docs/advanced/troubleshooting.md Use this C# snippet to automatically download and configure the Python runtime. This is the recommended approach for setting up the Python environment. ```csharp builder.Services .WithPython() .WithHome(pythonHome) .FromRedistributable(); // Automatically downloads Python ``` -------------------------------- ### Update CSnakes Templates Source: https://github.com/tonybaloney/csnakes/blob/main/docs/getting-started/templates.md Check for and install updates for all installed .NET project templates, including CSnakes templates. ```bash dotnet new update ``` -------------------------------- ### Create a Console Application Source: https://github.com/tonybaloney/csnakes/blob/main/docs/getting-started/templates.md Use this command to create a basic console application with CSnakes integration. It sets up a project with example Python and C# files. ```bash dotnet new pyapp ``` -------------------------------- ### Install Specific CSnakes Template Version Source: https://github.com/tonybaloney/csnakes/blob/main/docs/getting-started/templates.md Install a specific version of the CSnakes project templates by appending the version number to the template name. ```bash dotnet new install CSnakes.Templates::1.0.1 ``` -------------------------------- ### Create User Dictionary Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/basic-usage.md Illustrates creating a user dictionary in Python. ```python def create_user(name: str, age: int) -> dict[str, str | int]: return {"name": name, "age": age, "id": hash(name)} ``` -------------------------------- ### Download Python and Create Virtual Environment Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/deployment.md This command downloads the specified Python version and creates a virtual environment at the given path. This is useful for isolating project dependencies. ```bash setup-python --python 3.12 --venv /app/my-venv ``` -------------------------------- ### Configure Python Virtual Environments and Package Management Source: https://context7.com/tonybaloney/csnakes/llms.txt Set up Python environments using venv with pip or uv, or Conda. Supports installing packages from requirements.txt on startup or runtime. ```csharp var home = Environment.CurrentDirectory; // venv + pip (installs from requirements.txt on startup) services.WithPython() .WithHome(home) .WithVirtualEnvironment(Path.Join(home, ".venv")) .FromRedistributable() .WithPipInstaller(); // looks for requirements.txt in .venv dir // venv + uv (10-100x faster than pip) services.WithPython() .WithHome(home) .WithVirtualEnvironment(Path.Join(home, ".venv")) .FromRedistributable() .WithUvInstaller("requirements.txt"); // Runtime package installation var installer = serviceProvider.GetRequiredService(); await installer.InstallPackage("attrs==25.3.0"); await installer.InstallPackages(new[] { "attrs==25.3.0", "requests==2.31.0" }); await installer.InstallPackagesFromRequirements("requirements.txt"); // Conda services.WithPython() .WithHome(home) .FromConda(@"C:\tools\miniconda3") .WithCondaEnvironment("my_data_env"); // Pre-create env manually: conda env create -n my_data_env -f environment.yml ``` -------------------------------- ### Install Python Packages with Pip Source: https://github.com/tonybaloney/csnakes/blob/main/docs/advanced/troubleshooting.md Manually install Python packages using pip within your virtual environment. This is useful for ensuring all project dependencies are met. ```bash # In your virtual environment pip install -r requirements.txt ``` -------------------------------- ### Warm up Python Environment on Startup Source: https://github.com/tonybaloney/csnakes/blob/main/docs/advanced/troubleshooting.md Initialize the Python environment during application startup to avoid slow initial calls. This involves creating a Python module instance and executing a simple function. ```csharp public class StartupService : IHostedService { private readonly IPythonEnvironment _python; public StartupService(IPythonEnvironment python) { _python = python; } public async Task StartAsync(CancellationToken cancellationToken) { // Warm up Python environment await Task.Run(() => { var module = _python.MyModule(); // Make a simple call to initialize everything module.WarmupFunction(); }, cancellationToken); } public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; } ``` -------------------------------- ### Initialize Python Environment in C# Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/basic-usage.md Configure the .NET host builder to include the Python environment using CSnakes. Use WithPython() and FromRedistributable() for setup. This makes the Python environment available via dependency injection. ```csharp using CSnakes.Runtime; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; var builder = Host.CreateApplicationBuilder(args); builder.Services .WithPython() .WithHome(Environment.CurrentDirectory) .FromRedistributable(); var app = builder.Build(); var env = app.Services.GetRequiredService(); ``` -------------------------------- ### Clone and Run CSnakes AOT Sample Project Source: https://github.com/tonybaloney/csnakes/blob/main/docs/advanced/native-aot.md Steps to clone the CSnakes repository, navigate to the AOT sample project, and run it using both normal .NET execution and Native AOT publishing. ```bash # Clone the repository git clone https://github.com/tonybaloney/CSnakes.git cd CSnakes/samples/simple/AOTConsoleApp ``` ```bash # Build and run normally dotnet run ``` ```bash # Publish as AOT dotnet publish -c Release -r win-x64 ``` ```bash # Run the AOT executable ./bin/Release/net8.0/win-x64/publish/AOTConsoleApp.exe ``` -------------------------------- ### PythonLocator Methods Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Runtime/PublicAPI/net8.0/PublicAPI.Shipped.txt Methods for locating Python installations on the system. ```APIDOC ## LocatePython ### Description Locates the Python executable and associated metadata on the system. ### Method `abstract` ### Returns `CSnakes.Runtime.Locators.PythonLocationMetadata!` - Metadata about the located Python installation. ``` ```APIDOC ## PythonLocator.Version.get ### Description Gets the version of the Python locator. ### Method `abstract` ### Returns `System.Version!` - The version of the Python locator. ``` -------------------------------- ### Python Locator Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Runtime/PublicAPI/net10.0/PublicAPI.Unshipped.txt Methods for locating and identifying Python installations and their components. ```APIDOC ## Version ### Description Gets the version of the Python locator. ### Method Signature abstract CSnakes.Runtime.Locators.PythonLocator.Version.get -> System.Version! ``` ```APIDOC ## LocatePython ### Description Locates the Python installation. ### Method Signature abstract CSnakes.Runtime.Locators.PythonLocator.LocatePython() -> CSnakes.Runtime.Locators.PythonLocationMetadata! ``` ```APIDOC ## GetPythonExecutablePath ### Description Gets the path to the Python executable within a specified folder. Allows specifying if the free-threaded version should be used. ### Method Signature virtual CSnakes.Runtime.Locators.PythonLocator.GetPythonExecutablePath(string! folder, bool freeThreaded = false) -> string! ``` ```APIDOC ## GetPythonPath ### Description Gets the path to the Python installation within a specified folder. Allows specifying if the free-threaded version should be used. ### Method Signature virtual CSnakes.Runtime.Locators.PythonLocator.GetPythonPath(string! folder, bool freeThreaded = false) -> string! ``` ```APIDOC ## LocatePythonInternal ### Description Internally locates the Python installation within a specified folder. Allows specifying if the free-threaded version should be used. ### Method Signature virtual CSnakes.Runtime.Locators.PythonLocator.LocatePythonInternal(string! folder, bool freeThreaded = false) -> CSnakes.Runtime.Locators.PythonLocationMetadata! ``` ```APIDOC ## GetLibPythonPath ### Description Gets the path to the libpython library within a specified folder. Allows specifying if the free-threaded version should be used. ### Method Signature virtual CSnakes.Runtime.Locators.PythonLocator.GetLibPythonPath(string! folder, bool freeThreaded = false) -> string! ``` -------------------------------- ### Register Python Runtime with Dependency Injection Source: https://context7.com/tonybaloney/csnakes/llms.txt Configure the Python runtime using `WithPython()`, `WithHome()`, and `FromRedistributable()` to automatically download and cache a Python environment. This requires no system Python installation. ```csharp using CSnakes.Runtime; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; var builder = Host.CreateApplicationBuilder(args); var home = Path.Join(Environment.CurrentDirectory); // folder containing .py files builder.Services .WithPython() .WithHome(home) .FromRedistributable("3.12"); // downloads Python 3.12 automatically var app = builder.Build(); var env = app.Services.GetRequiredService(); // env is now ready to invoke Python modules ``` -------------------------------- ### Python Locator Methods Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Runtime/PublicAPI/net9.0/PublicAPI.Shipped.txt Methods for locating and retrieving information about Python installations. ```APIDOC ## GetPythonExecutablePath ### Description Gets the path to the Python executable within a given folder. ### Method `virtual CSnakes.Runtime.Locators.PythonLocator.GetPythonExecutablePath(string! folder, bool freeThreaded = false) -> string!` ### Parameters #### Query Parameters - **folder** (string) - Required - The folder to search within. - **freeThreaded** (bool) - Optional - Whether to look for a free-threaded Python build. Defaults to false. ## GetPythonPath ### Description Gets the Python path (PYTHONPATH) within a given folder. ### Method `virtual CSnakes.Runtime.Locators.PythonLocator.GetPythonPath(string! folder, bool freeThreaded = false) -> string!` ### Parameters #### Query Parameters - **folder** (string) - Required - The folder to search within. - **freeThreaded** (bool) - Optional - Whether to look for a free-threaded Python build. Defaults to false. ## GetLibPythonPath ### Description Gets the path to the `libpython` shared library within a given folder. ### Method `virtual CSnakes.Runtime.Locators.PythonLocator.GetLibPythonPath(string! folder, bool freeThreaded = false) -> string!` ### Parameters #### Query Parameters - **folder** (string) - Required - The folder to search within. - **freeThreaded** (bool) - Optional - Whether to look for a free-threaded Python build. Defaults to false. ## LocatePythonInternal ### Description Internally locates Python and returns metadata about the found installation. ### Method `virtual CSnakes.Runtime.Locators.PythonLocator.LocatePythonInternal(string! folder, bool freeThreaded = false) -> CSnakes.Runtime.Locators.PythonLocationMetadata!` ### Parameters #### Query Parameters - **folder** (string) - Required - The folder to search within. - **freeThreaded** (bool) - Optional - Whether to look for a free-threaded Python build. Defaults to false. ``` -------------------------------- ### Configure Python Virtual Environment with venv and pip Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/environments.md Use `.WithVirtualEnvironment()` to specify the path to a venv environment. Optionally, use `.WithPipInstaller()` to automatically install packages from a requirements.txt file on startup. ```csharp services .WithPython() .WithVirtualEnvironment(Path.Join(home, ".venv")) // Python locators .WithPipInstaller(); // Optional - installs packages listed in requirements.txt on startup ``` -------------------------------- ### Python Location Metadata Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Runtime/PublicAPI/net8.0/PublicAPI.Shipped.txt Methods for locating and retrieving metadata about Python installations. ```APIDOC ## LocatePythonInternal ### Description Internally locates Python within a specified folder, with an option for free-threaded mode. ### Method `virtual CSnakes.Runtime.Locators.PythonLocator.LocatePythonInternal(string! folder, bool freeThreaded = false) -> CSnakes.Runtime.Locators.PythonLocationMetadata!` ## GetPythonExecutablePath ### Description Retrieves the path to the Python executable within a specified folder, with an option for free-threaded mode. ### Method `virtual CSnakes.Runtime.Locators.PythonLocator.GetPythonExecutablePath(string! folder, bool freeThreaded = false) -> string!` ## GetLibPythonPath ### Description Retrieves the path to the libpython library within a specified folder, with an option for free-threaded mode. ### Method `virtual CSnakes.Runtime.Locators.PythonLocator.GetLibPythonPath(string! folder, bool freeThreaded = false) -> string!` ## GetPythonPath ### Description Retrieves the Python path (PYTHONPATH) within a specified folder, with an option for free-threaded mode. ### Method `virtual CSnakes.Runtime.Locators.PythonLocator.GetPythonPath(string! folder, bool freeThreaded = false) -> string!` ``` -------------------------------- ### Specify Python Version with Redistributable Locator Source: https://github.com/tonybaloney/csnakes/blob/main/docs/advanced/additional-locators.md Automates Python installation by fetching and caching a compatible version. Defaults to Python 3.12, but can be configured for other versions. ```csharp var pythonBuilder = services.WithPython() .FromRedistributable("3.13"); ``` -------------------------------- ### PythonEnvironment Extensions Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Tests/PythonStaticGeneratorTests/FormatClassFromMethods.test_classes.approved.txt Provides an extension method to get an instance of the ITestClass from a PythonEnvironment. ```APIDOC ## Extension Method IPythonEnvironment.TestClass ### Description Gets an instance of the ITestClass interface, which allows interaction with the Python 'test' module. ### Method Signature ```csharp public static ITestClass TestClass(this IPythonEnvironment env) ``` ### Parameters #### Path Parameters * **env** (IPythonEnvironment) - Required - The Python environment instance. ``` -------------------------------- ### Create User Dictionary in C# Source: https://github.com/tonybaloney/csnakes/blob/main/docs/user-guide/basic-usage.md Shows how a user dictionary is created and accessed in C#. ```csharp var user = mathModule.CreateUser("Alice", 30); Console.WriteLine($"Name: {user["name"]}"); Console.WriteLine($"Age: {user["age"]}"); ``` -------------------------------- ### PyObject Enumeration and Representation Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Runtime/PublicAPI/net10.0/PublicAPI.Unshipped.txt Methods for converting `PyObject` to enumerables and getting its string representation. ```APIDOC ## As Enumerable (Generic) ### Description Converts the `PyObject` to a generic enumerable collection. ### Method `CSnakes.Runtime.Python.PyObject.AsEnumerable()` ### Returns `System.Collections.Generic.IEnumerable` - An enumerable collection of type T. ``` ```APIDOC ## As Enumerable (Generic with Importer) ### Description Converts the `PyObject` to a generic enumerable collection using a specified importer. ### Method `CSnakes.Runtime.Python.PyObject.AsEnumerable()` ### Returns `System.Collections.Generic.IEnumerable` - An enumerable collection of type T. ``` ```APIDOC ## Get Representation ### Description Gets the string representation of the `PyObject`. ### Method `virtual CSnakes.Runtime.Python.PyObject.GetRepr()` ### Returns `string` - The string representation of the `PyObject`. ``` -------------------------------- ### ServiceCollectionExtensions.FromNuGet Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Runtime/PublicAPI/net8.0/PublicAPI.Shipped.txt Configures the Python environment builder to use a Python installation obtained via NuGet. ```APIDOC ## CSnakes.Runtime.ServiceCollectionExtensions.FromNuGet ### Description Configures the `IPythonEnvironmentBuilder` to initialize a Python environment by downloading and using a specified Python version from a NuGet package. ### Method `static CSnakes.Runtime.IPythonEnvironmentBuilder! FromNuGet(this CSnakes.Runtime.IPythonEnvironmentBuilder! builder, string! version)` ### Parameters - `builder` (IPythonEnvironmentBuilder!): The builder instance. - `version` (string!): The desired Python version to install from NuGet. ### Returns (IPythonEnvironmentBuilder!) The configured builder instance. ``` -------------------------------- ### Python to C# Type Mappings for Function Signatures Source: https://context7.com/tonybaloney/csnakes/llms.txt Illustrates Python type hints and their corresponding C# generated signatures, showing conversions for lists, dictionaries, optionals, and unions. ```python # types_demo.py from typing import Optional, Generator def process_numbers(numbers: list[int]) -> list[str]: return [str(n * 2) for n in numbers] def word_count(text: str) -> dict[str, int]: words = text.split() return {w: words.count(w) for w in set(words)} def find_user(user_id: int) -> str | None: # Optional return return {1: "Alice", 2: "Bob"}.get(user_id) def process_data(data: int | str) -> str: # Union → overloads return f"got {type(data).__name__}: {data}" def safe_divide(a: float, b: float) -> float | None: return a / b if b != 0 else None ``` -------------------------------- ### ServiceCollectionExtensions.FromEnvironmentVariable Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Runtime/PublicAPI/net8.0/PublicAPI.Shipped.txt Configures the Python environment builder to use a Python installation specified by an environment variable. ```APIDOC ## CSnakes.Runtime.ServiceCollectionExtensions.FromEnvironmentVariable ### Description Configures the `IPythonEnvironmentBuilder` to initialize a Python environment by locating the Python executable via a specified environment variable. ### Method `static CSnakes.Runtime.IPythonEnvironmentBuilder! FromEnvironmentVariable(this CSnakes.Runtime.IPythonEnvironmentBuilder! builder, string! environmentVariable, string! version)` ### Parameters - `builder` (IPythonEnvironmentBuilder!): The builder instance. - `environmentVariable` (string!): The name of the environment variable that points to the Python installation. - `version` (string!): The expected version of the Python installation. ### Returns (IPythonEnvironmentBuilder!) The configured builder instance. ``` -------------------------------- ### IPythonEnvironmentBuilder Methods Source: https://github.com/tonybaloney/csnakes/blob/main/src/CSnakes.Runtime/PublicAPI/net8.0/PublicAPI.Shipped.txt Interface for building and configuring Python environments. ```APIDOC ## IPythonEnvironmentBuilder.DisableSignalHandlers ### Description Disables signal handlers for the Python environment. ### Returns `CSnakes.Runtime.IPythonEnvironmentBuilder!` - The builder instance for chaining. ``` ```APIDOC ## IPythonEnvironmentBuilder.GetOptions ### Description Retrieves the current configuration options for the Python environment builder. ### Returns `CSnakes.Runtime.PythonEnvironmentOptions!` - The current environment options. ``` ```APIDOC ## IPythonEnvironmentBuilder.Services.get ### Description Gets the service collection used for dependency injection in the Python environment. ### Returns `Microsoft.Extensions.DependencyInjection.IServiceCollection!` - The service collection. ``` ```APIDOC ## IPythonEnvironmentBuilder.WithCondaEnvironment ### Description Configures the builder to use a Conda environment. ### Parameters #### Query Parameters - **name** (`string!`) - Required - The name of the Conda environment. - **environmentSpecPath** (`string?`) - Optional - Path to the environment specification file. - **ensureEnvironment** (`bool`) - Optional - Whether to ensure the environment exists. - **pythonVersion** (`string?`) - Optional - The desired Python version. ### Returns `CSnakes.Runtime.IPythonEnvironmentBuilder!` - The builder instance for chaining. ``` ```APIDOC ## IPythonEnvironmentBuilder.WithHome ### Description Configures the builder to use a specific Python home directory. ### Parameters #### Query Parameters - **home** (`string!`) - Required - The path to the Python home directory. ### Returns `CSnakes.Runtime.IPythonEnvironmentBuilder!` - The builder instance for chaining. ``` ```APIDOC ## IPythonEnvironmentBuilder.WithVirtualEnvironment ### Description Configures the builder to use a virtual environment. ### Parameters #### Query Parameters - **path** (`string!`) - Required - The path to the virtual environment. - **ensureEnvironment** (`bool`) - Optional - Whether to ensure the environment exists. Defaults to true. ### Returns `CSnakes.Runtime.IPythonEnvironmentBuilder!` - The builder instance for chaining. ```