Updated on 22 Sep 2025 by Admin

Bridging the Gap – Using Python.NET to Connect Python and .NET

In the previous article, we discussed why you may need to integrate your Python model with a .NET application and explored the two ways to bridge the gap between both. In this article, we will get our hands dirty and learn how to use Python.NET with a real example. Python.NET is a powerful library that allows you to directly embed Python objects into your .NET applications, allowing C# to call Python methods and objects as if they were written in the same language.

In this tutorial, we will go through the entire process, starting from setting up the environments, creating a model, and integrating it into a simple console application in C#.


Prerequisites

Before getting started, ensure you have the following installed on your system:

  • .NET SDK (Version 6 or later)
  • Python (Version 3.7 or later, must match the bitness of your .NET application (32 or 64 bit))

Setting Up the Environment

To get started, let's ensure our environment is ready:

  1. Install Python: Go to https://www.python.org/downloads/ and install the latest version. Make sure the bitness of your Python interpreter matches the .NET application.
  2. Install .NET: Install the .NET SDK version 6 or higher.
  3. Install Python.NET and scikit-learn: Open your Python IDE and go to terminal. Run the following command to install the necessary packages:

pip install pythonnet scikit-learn

scikit-learn: This is a powerful Python library widely used for machine learning applications. It serves as a simple and efficient tool for predictive data analysis built on NumPy, SciPy, and matplotlib. We will use the functions in this library to train our model and predict the sentiments behind the statements.


Creating the Python Model

In this tutorial, we will create a simple Python model and train it on a small set of data to identify the sentiments based on the statements. We'll also define a function inside the script to be called from C# to get a prediction.

  1. Create a new python project and name it as sentiments_model.py.
  2. Now, copy and paste the following code into it:

# sentiment_model.py

import os
import pickle
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression


def train_and_save_model():
    """
    Trains a simple sentiment analysis model and saves it.
    """
    print("Training model...")

    # A simple dataset for demonstration
    texts = ["I love this product", "This is terrible", "It's a great day", "I am very disappointed"]
    labels = ["positive", "negative", "positive", "negative"]

    # Vectorize the text data
    vectorizer = CountVectorizer()
    X = vectorizer.fit_transform(texts)

    # Train a logistic regression model
    model = LogisticRegression()
    model.fit(X, labels)

    # Save the vectorizer and model for later use
    with open("vectorizer.pkl", "wb") as f:
        pickle.dump(vectorizer, f)
    with open("model.pkl", "wb") as f:
        pickle.dump(model, f)

    print("Model training complete. Files saved.")


def predict_sentiment(text):
    """
    Loads the saved model and predicts the sentiment of a given text.
    """
    # Check if model files exist
    if not os.path.exists("vectorizer.pkl") or not os.path.exists("model.pkl"):
        print("Model files not found. Training and saving a new model...")
        train_and_save_model()

    # Load the saved model and vectorizer
    with open("vectorizer.pkl", "rb") as f:
        vectorizer = pickle.load(f)
    with open("model.pkl", "rb") as f:
        model = pickle.load(f)

    # Predict the sentiment of the input text
    X_new = vectorizer.transform([text])
    prediction = model.predict(X_new)

    return prediction[0]


if __name__ == '__main__':
    # This block is for testing the script directly in Python
    train_and_save_model()
    test_text = "This is a stupid product"
    sentiment = predict_sentiment(test_text)
    print(f"The sentiment of '{test_text}' is: {sentiment}")

To check if the model is working as expected or not, you can run the above script directly in your Python IDE. It will also generate the model.pkl and vectorizer.pkl files.


Building the .NET Application

Let's create a new console application in C#. You can either create the application using the terminal or use Visual Studio or any other IDE. If you are using an IDE, simply create a new Console Application from the File menu. I’ll create the project directly through the Command Prompt.

  1. Launch your Terminal or Command Prompt.
  2. Run the following command to create the project:

dotnet new console -o DotNetPythonApp

  1. Go to the project directory by running the following command:

cd DotNetPythonApp

  1. Install Python.NET NuGet package:

dotnet add package Python.NET

Note: When using an IDE, install the package directly by searching for it in the NuGet Package library.

  1. Now, go to the location where you stored your Python project and copy the sentiments_model.py, model.pkl, and vectorizer.pkl files into the DotNetPythonApp directory.

Writing the Integration Code

Now, we are all set to combine our Python model and .NET app. To do so, open the Program.cs file and paste the following code into it:


// Program.cs

using System;
using System.IO;
using Python.Runtime;

class Program
{
    static void Main(string[] args)
    {
        // Set the Python DLL. This is crucial for Python.NET to find the correct
        // Python installation. Replace the path with the location of your pythonXX.dll.
        Runtime.PythonDLL = @"C:\\Users\\raoha\\AppData\\Local\\Programs\\Python\\Python312\\python312.dll";

        // Initialize the Python engine. This must be called before any other Python.NET API.
        PythonEngine.Initialize();

        try
        {
            // The 'using (Py.GIL())' block acquires the Global Interpreter Lock (GIL),
            // which is necessary for thread-safe access to the Python interpreter.
            using (Py.GIL())
            {
                // Define the directory where the Python module is located.
                // This assumes the 'sentiment_model' folder is in the same directory as the C# executable.
                string pythonModulePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sentiment_model");

                // Add the directory of your Python module to the search path.
                // This allows the Python interpreter to find your sentiment_model.py file.
                dynamic sys = Py.Import("sys");
                PyObject pyPath = sys.path;
                pyPath.GetAttr("insert").Invoke(new PyInt(0), new PyString(pythonModulePath));

                // Import the Python module.
                dynamic sentimentModel = Py.Import("sentiment_model");

                // Define the text we want to analyze.
                string testText = "This is an amazing and fantastic movie!";
                Console.WriteLine($"\nCalling Python function to analyze: \"{testText}\"");

                // Call the Python function and get the result.
                string sentiment = sentimentModel.predict_sentiment(testText).ToString();

                Console.WriteLine($"Python AI Prediction: {sentiment}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
            Console.WriteLine($"Please ensure your Python path is correct and dependencies are installed.");
        }
    }
}

Note: Before running the code, ensure to replace β€œYOUR_PYTHON_INSTALLATION_PATH” with your actual Python path.


Run the Project

To run the project, simply run the following command:


dotnet run

If everything is set up correctly, your application will start the Python engine, execute the model, and print the sentiment. In the next article, we will dive deeper into advanced Python.NET concepts.


You need to login to post a comment.

Sharpen Your Skills with These Next Guides