Skip to main content

Command Palette

Search for a command to run...

How to Run Python Code Inside .NET: A Complete, Practical Guide

Integrating Python with .NET 8/9 using Python.NET, Process Execution, and gRPC

Published
4 min read
How to Run Python Code Inside .NET: A Complete, Practical Guide
M

Morteza Jangjoo, Senior .NET Backend Developer with 15+ years of experience in C#, ASP.NET Core, SQL Server, and Microservices. Skilled in building scalable, high-performance systems.

Modern .NET applications often need to use Python libraries — especially in machine learning, statistics, data science, financial modeling, NLP, and optimization. But Python and .NET run on different runtimes, making the integration a bit tricky.

In this guide, you’ll learn all effective ways to run Python inside .NET, including:

  • Running Python directly inside .NET using Python.NET

  • Executing Python scripts via Process

  • Connecting .NET to Python using gRPC microservices

  • Passing arrays, receiving return values, managing GIL, and embedding models

This article is designed for developers building AI-powered backend services, financial engines, trading systems, dashboards, and analytics tools.


1. Using Python.NET (Best Method for Direct Integration)

Python.NET is the most powerful and direct solution.
It allows .NET to:

  • import Python modules

  • call Python functions

  • use NumPy, Pandas, SciPy, TensorFlow, and other libraries

  • exchange objects between Python and C#

Install the package

dotnet add package Python.Runtime

Initialize Python inside .NET

Before making any Python call, you must point Python.NET to the correct Python DLL:

Environment.SetEnvironmentVariable(
    "PYTHONNET_PYDLL",
    @"C:\Users\YourUser\AppData\Local\Programs\Python\Python312\python312.dll"
);

PythonEngine.Initialize();

Example: Calling a Python Function from .NET

Python file (stats.py)

# stats.py
import numpy as np

def calculate_stats(values):
    arr = np.array(values)
    return float(arr.mean()), float(arr.std())

Save this file inside your project, e.g.:

/PythonScripts/stats.py

C# Code (Program.cs)

using Python.Runtime;

class Program
{
    static void Main()
    {
        Environment.SetEnvironmentVariable(
            "PYTHONNET_PYDLL",
            @"C:\Path\To\Python312\python312.dll"
        );

        PythonEngine.Initialize();

        using (Py.GIL())
        {
            dynamic sys = Py.Import("sys");
            sys.path.append(@"C:\MyProject\PythonScripts");

            dynamic statsModule = Py.Import("stats");

            double[] values = { 1.0, 2.0, 3.0, 4.0 };
            dynamic np = Py.Import("numpy");
            var valuesArray = np.array(values);

            var result = statsModule.calculate_stats(valuesArray);

            Console.WriteLine($"Mean: {result[0]}, Std: {result[1]}");
        }

        PythonEngine.Shutdown();
    }
}

Advantages of Python.NET

FeatureDescription
Real-time integrationCall Python functions directly from C#
Full ecosystemNumPy, SciPy, Pandas, ML libraries supported
Data exchangeEasily pass arrays, lists, strings, and return complex results
PerformanceMuch faster than invoking Python via CLI

2. Running Python Using System.Diagnostics.Process

This is the simplest method.
Useful for:

  • lightweight tasks

  • calling a Python script and returning text output

  • automation and tooling


Example

Python script (sum.py):

# sum.py
import sys

a = int(sys.argv[1])
b = int(sys.argv[2])
print(a + b)

C# code:

using System.Diagnostics;

var psi = new ProcessStartInfo
{
    FileName = "python",
    Arguments = "sum.py 10 20",
    RedirectStandardOutput = true,
    UseShellExecute = false
};

var process = Process.Start(psi);
string output = process.StandardOutput.ReadToEnd();
Console.WriteLine("Result: " + output);

Advantages of Process-Based Execution

  • Works on Windows, Linux, macOS

  • No special library needed

  • Perfect for small scripts or automation

Limitations

  • Data exchange is via stdin/stdout

  • Not suitable for heavy ML or frequently called functions


3. Using gRPC (Best for AI, NLP, ML Models)

When the Python side runs heavy workloads (AI inference, financial ML models, NLP pipelines), running Python inside .NET is not ideal.
Instead, Python becomes a microservice, and .NET communicates via gRPC.


Architecture

.NET API  <== gRPC ==>  Python Service (FastAPI or gRPC Python)

Benefits

  • Scalable

  • Clean separation

  • Python can run in its own environment

  • Ideal for AI/ML workloads


Example proto file:

syntax = "proto3";

service MLService {
  rpc Predict (PredictRequest) returns (PredictResponse);
}

message PredictRequest {
  repeated double values = 1;
}

message PredictResponse {
  double result = 1;
}

Use case:

  • Python loads TensorFlow/PyTorch model

  • .NET sends data

  • Python returns predictions via gRPC

This is the industry standard for ML-driven .NET applications.


4. When to Use Each Method

TaskBest Method
Call simple Python scriptsProcess
Run NumPy/Pandas directlyPython.NET
Use Python models inside .NETPython.NET
Run AI/ML models in productiongRPC
High-performance distributed MLgRPC
Heavy statistical analysisPython.NET or microservice

Conclusion

Running Python inside .NET is not only possible — it’s powerful, flexible, and production-ready.
Depending on your requirements, you can choose between:

  • Python.NET (deep integration, recommended for scientific computing)

  • Process execution (simple, cross-platform)

  • gRPC microservices (best for AI/ML workloads in production)

Using these methods, .NET developers can take full advantage of the Python ecosystem while keeping the robustness and scalability of .NET.