DEV Community

Cover image for Python Inside .NET
Morteza Jangjoo
Morteza Jangjoo

Posted on

Python Inside .NET

Running Python Inside .NET 9 — A Complete Guide Using Python.NET

Integrating Python with .NET unlocks a powerful hybrid environment where you can leverage Python’s rich ecosystem (AI, ML, data processing) directly inside a .NET application.
In this guide, you'll learn how to run Python code, import Python modules, and call Python functions inside a .NET 9 application using Python.NET — with full source code.


Why Use Python Inside .NET?

  • Reuse existing Python scripts or ML models
  • Access libraries such as NumPy, Pandas, Scikit-learn, etc.
  • Extend .NET applications with data science capabilities
  • No need for IPC or microservices — run Python inline

Prerequisites

Before starting:

1. Install Python

Python 3.10 or 3.11 recommended.

2. Install dependencies

pip install numpy
Enter fullscreen mode Exit fullscreen mode

3. Create a .NET 9 Console Project

dotnet new console -n PyNetIntegration
cd PyNetIntegration
Enter fullscreen mode Exit fullscreen mode

4. Install Python.NET package

dotnet add package Python.Runtime
Enter fullscreen mode Exit fullscreen mode

How Python.NET Works

Python.NET embeds the CPython runtime directly inside your .NET application.

This means:

  • You can call Python code from C#
  • Import Python modules (even third-party)
  • Exchange objects between .NET ↔ Python
  • Run Python functions line-by-line or execute entire scripts

Example 1: Run Python Inline Code

Program.cs

using Python.Runtime;

class Program
{
    static void Main()
    {
        PythonEngine.Initialize();

        using (Py.GIL())
        {
            dynamic math = Py.Import("math");
            double result = math.sqrt(144);

            Console.WriteLine($"Python sqrt(144) = {result}");
        }

        PythonEngine.Shutdown();
    }
}
Enter fullscreen mode Exit fullscreen mode

✔ Works instantly
✔ No Python files needed
✔ Calls CPython directly


Example 2: Import a Python Module (Custom .py File)

Create file: /scripts/utils.py

def add(a, b):
    return a + b

def multiply(a, b):
    return a * b
Enter fullscreen mode Exit fullscreen mode

Updated Program.cs

using Python.Runtime;

class Program
{
    static void Main()
    {
        PythonEngine.Initialize();
        using (Py.GIL())
        {
            dynamic sys = Py.Import("sys");
            sys.path.append("scripts");

            dynamic utils = Py.Import("utils");
            Console.WriteLine(utils.add(10, 20));
            Console.WriteLine(utils.multiply(5, 4));
        }
        PythonEngine.Shutdown();
    }
}
Enter fullscreen mode Exit fullscreen mode

Example 3: Using NumPy Inside .NET

using Python.Runtime;

class Program
{
    static void Main()
    {
        PythonEngine.Initialize();

        using (Py.GIL())
        {
            dynamic np = Py.Import("numpy");
            dynamic arr = np.array(new int[] { 1, 2, 3, 4 });
            dynamic squared = np.square(arr);

            Console.WriteLine(squared);
        }

        PythonEngine.Shutdown();
    }
}
Enter fullscreen mode Exit fullscreen mode

Data Exchange: Python ↔ .NET

Passing .NET data to Python

var list = new List<int> { 1, 2, 3 };
dynamic npList = new PyList(list.Select(i => new PyInt(i)).ToArray());
Enter fullscreen mode Exit fullscreen mode

Returning Python values to .NET

int x = (int)pyValue.As<int>();
Enter fullscreen mode Exit fullscreen mode

Folder Structure (recommended)

PyNetIntegration/
│── Program.cs
│── PyNetIntegration.csproj
└── scripts/
    └── utils.py
Enter fullscreen mode Exit fullscreen mode

When Should You Use Python.NET?

Use Python.NET when:

✓ You want to call Python inline
✓ You need NumPy/Pandas in your .NET app
✓ You need maximum speed (direct CPython runtime)

Avoid Python.NET when:

✗ You want full cross-platform runtime isolation
✗ You need Python and .NET to run separately → Use gRPC
✗ You're deploying to serverless (Azure Functions, AWS Lambda)


Full Source Code (Copy-paste ready)

Here is the full minimal project:

PyNetIntegration.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Python.Runtime" Version="3.0.1" />
  </ItemGroup>
</Project>
Enter fullscreen mode Exit fullscreen mode

Program.cs

using Python.Runtime;

class Program
{
    static void Main()
    {
        PythonEngine.Initialize();
        using (Py.GIL())
        {
            dynamic math = Py.Import("math");
            Console.WriteLine(math.sqrt(169));
        }
        PythonEngine.Shutdown();
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Python.NET provides a powerful and direct way to run Python inside .NET applications.
With just a few lines of code, you can:

  • Embed Python
  • Run scripts
  • Load modules
  • Exchange data
  • Use scientific libraries

This hybrid approach is perfect for AI, ML, automation, financial analysis, or any system where both ecosystems shine together.


Top comments (0)