Python.NET is a library that provides interoperability between Python and C# in .NET applications.
With Python.NET, we can easily invoke Python code from C# and use Python libraries and access resources from the Python ecosystem directly in .NET applications.
This capability is particularly useful for integrating advanced Python functionalities, such as machine learning and data analysis, into applications developed with .NET.
Features of Python.NET:
- Complete Interoperability: Allows calling Python code from C# and vice versa, facilitating the integration of both technologies.
- Access to Python Libraries: Allows direct use of Python libraries in .NET applications.
- Support for Data Types: Automatically handles conversion between Python and C# data types.
- Execution of Python Scripts: Allows executing Python scripts and using their results in C# applications.
Interoperability can impact performance, especially if frequent calls are made between C# and Python. In other words, don’t expect fast programs (Python is very slow, and with the interop, even worse).
For more information, documentation, and additional examples, visit the official Python.NET repository on GitHub. Here you will find all the resources you need to start integrating Python into your C# applications.
Installing Python.NET
To add Python.NET to your project, use the NuGet package manager. Open the terminal or the Visual Studio package manager console and run the following command:
Install-Package Pythonnet
Alternatively, through the NuGet interface in Visual Studio, search for Pythonnet
and install it in your project.
How to Use Python.NET
Initial Setup
To start using Python.NET in your C# project, you need to initialize the Python environment and configure the Python interpreter. Here’s an example of how to do this:
using Python.Runtime;
// replace with the version of Python you have installed
Runtime.PythonDLL = "python312.dll";
PythonEngine.Initialize();
using (Py.GIL())
{
dynamic np = Py.Import("numpy");
Console.WriteLine(np.cos(np.pi * 2));
dynamic sin = np.sin;
Console.WriteLine(sin(5));
double c = (double)(np.cos(5) + sin(5));
Console.WriteLine(c);
dynamic a = np.array(new List<float> { 1, 2, 3 });
Console.WriteLine(a.dtype);
dynamic b = np.array(new List<float> { 6, 5, 4 }, dtype: np.int32);
Console.WriteLine(b.dtype);
Console.WriteLine(a * b);
Console.ReadKey();
}
In this example, we initialize the Python environment, import the NumPy library, create an array, and display its content in the console.
Calling Python Functions from C#
You can call functions defined in Python scripts from C# using Python.NET. Here’s an example of how to do this:
- Define a function in a Python script. Create a file in your project solution, for example
example.py
. There we insert our functions.
def add(a, b):
return a + b
In Visual Studio / file properties, set the “Copy to Output Directory” option to “Copy Always”.
- Call the function from C#: Now we can call our function by importing the module we created.
using Python.Runtime;
Runtime.PythonDLL = "python312.dll";
PythonEngine.Initialize();
using (Py.GIL()) // Acquire the GIL
{
dynamic pyScript = Py.Import("example");
dynamic result = pyScript.add(10, 20);
Console.WriteLine($"Result of the addition: {result}");
}
In this example, we import the Python script and call the add
function passing two arguments. The result is displayed in the console.