Python.NET

3.0.5 · active · verified Fri Apr 10

Python.NET (pythonnet) is a package that provides nearly seamless integration between Python and the .NET Framework, .NET Core, and Mono runtime on Windows, Linux, and macOS. It allows Python programmers to script .NET applications or build entire applications using .NET services and components written in any CLR-targeting language (C#, VB.NET, F#, C++/CLI). The current version is 3.0.5 and it maintains an active release cadence with support for recent Python and .NET versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the .NET runtime, add a reference to a .NET assembly, and then import and use .NET types and objects directly from Python. It explicitly handles potential runtime loading issues by trying different runtime types.

import pythonnet

# It's crucial to load the .NET runtime explicitly before importing 'clr'.
# Options: "coreclr" (modern cross-platform .NET), "netfx" (Windows .NET Framework), "mono" (Linux/macOS Mono).
# The choice depends on your OS and installed .NET environment.
# For this example, we'll try 'coreclr' first, then 'netfx' as a common fallback for Windows.

try:
    pythonnet.load("coreclr") # For .NET Core / .NET 5+ SDK installed
except RuntimeError:
    print("Could not load 'coreclr'. Trying 'netfx' (Windows only).")
    try:
        pythonnet.load("netfx") # For .NET Framework on Windows
    except RuntimeError:
        print("Could not load 'netfx'. Trying 'mono' (Linux/macOS fallback).")
        try:
            pythonnet.load("mono") # For Mono runtime
        except RuntimeError:
            print("Failed to load any .NET runtime. Ensure a compatible .NET SDK or Mono is installed.")
            import sys; sys.exit(1)

import clr
# Explicitly add a reference to a .NET assembly. 'System' is fundamental.
clr.AddReference("System")

# Now you can import types from the .NET System namespace
from System import DateTime
from System import Environment

print(f"Current Date and Time from .NET: {DateTime.Now}")
print(f".NET OS Version: {Environment.OSVersion.VersionString}")

# Example of creating a .NET object
from System.Collections.Generic import List
my_list = List[str]()
my_list.Add("Hello")
my_list.Add(".NET")

print(f"Items in .NET List: {', '.join(my_list)}")

view raw JSON →