DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Building Cross-Platform Apps: A Complete Guide With .NET Core
  • Logfire: Uncomplicated Observability for Python Applications
  • Zero to AI Hero, Part 3: Unleashing the Power of Agents in Semantic Kernel
  • Zero to AI Hero, Part 2: Understanding Plugins in Semantic Kernel, A Deep Dive With Examples

Trending

  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • How to Convert XLS to XLSX in Java
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  1. DZone
  2. Coding
  3. Languages
  4. A Simple Union Between .NET Core and Python

A Simple Union Between .NET Core and Python

Let's take a look at Python for .NET, a package that allows you to take advantage of Python installed on the running machine from within your .NET Core applications.

By 
Nick Cosentino user avatar
Nick Cosentino
·
Jan. 28, 23 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
3.3K Views

Join the DZone community and get the full member experience.

Join For Free

Python is a powerful and versatile programming language that has become increasingly popular. For many, it’s one of the very first programming languages they pick up when getting started. Some of the highest traffic posts on my blog many years after they were written look at using C# and Python together. Today we’re going to explore how you can use Python from inside a C# .NET Core application with much more modern approaches than my original articles. Enter Pythonnet!

Pythonnet Package and Getting Started

We’re going to be looking at Python for .NET in order to accomplish this goal. This library allows you to take advantage of Python installed on the running machine from within your .NET Core applications. You must configure it to point at the corresponding Python DLL that you’d like to use, and after a couple of lines of initialization you’re off to the races!

Example 1: Hello World With Pythonnet

To get started, you’ll need to install the pythonnet package from NuGet. Once you’ve done that, you can use the following code to run a Python script from your C# code:

using Python.Runtime;

internal sealed class Program
{
    private static void Main(string[] args)
    {
        // NOTE: set this based on your python install. this will resolve from
        // your PATH environment variable as well.
        Runtime.PythonDLL = "python310.dll";

        PythonEngine.Initialize();
        using (Py.GIL())
        {
            using var scope = Py.CreateScope();
            scope.Exec("print('Hello World from Python!')");
        }
    }
}

This code sets our python DLL path on the Runtime, which will be a necessary step. Don’t forget to do this! We must then call PythonEngine.Initialize() and Py.GIL(), which we will want to dispose of later, so consider a using statement. We can ask the static Py class to create a scope for us to use, and then leverage the Exec method in order to execute some Python code. In this example, we’re calling the Exec method to run a simple Python script that prints “Hello World from Python!” to the console.

Example 2: A Pythonnet Calculator!

You can also use the Python C API to call Python functions directly from C# code. To do this, you’ll need to create a C# wrapper for the Python function you want to call. Here’s an example of how you might create a wrapper for a Python function that takes two integers as arguments and returns their sum:

using System;
using Python.Runtime;

internal sealed class Program
{
    private static void Main(string[] args)
    {
        // NOTE: set this based on your python install. this will resolve from
        // your PATH environment variable as well.
        Runtime.PythonDLL = "python310.dll";
        PythonEngine.Initialize();

        using (Py.GIL())
        {
            // NOTE: this doesn't validate input
            Console.WriteLine("Enter first integer:");
            var firstInt = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter second integer:");
            var secondInt = int.Parse(Console.ReadLine());

            using dynamic scope = Py.CreateScope();
            scope.Exec("def add(a, b): return a + b");

            var sum = scope.add(firstInt, secondInt);
            Console.WriteLine($"Sum: {sum}");
        }
    }
}

In this example, we’re using the Exec method to define a Python function called “add” that takes two integers as arguments and returns their sum. Thanks to the dynamic keyword in C#, we are able to make an assumption that our scope object has a method called “add” directly on it. Finally, we use C# code directly to call the “add” method just like as if it was inside of C#. The return type assigned to the “sum” variable in C# is also dynamic, but you could declare this variable as an integer and it will compile properly with this type as well.

What’s Next?

You can see more examples by checking out the full article on my blog! What sorts of applications would you build that need to call Python code from C#?

applications Python (language) C# (programming language) .NET

Published at DZone with permission of Nick Cosentino. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Building Cross-Platform Apps: A Complete Guide With .NET Core
  • Logfire: Uncomplicated Observability for Python Applications
  • Zero to AI Hero, Part 3: Unleashing the Power of Agents in Semantic Kernel
  • Zero to AI Hero, Part 2: Understanding Plugins in Semantic Kernel, A Deep Dive With Examples

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!