Demonstrations of embedding Python scripts in C# applications using IronPython, with examples of data exchange and interop.
This repository shows how to integrate Python scripts directly into C# applications using IronPython. Two primary examples illustrate different use cases.
Add IronPython to your C# project via NuGet:
Install-Package IronPython -Version 2.7.10
File: getting_a_list.cs
This example demonstrates:
- Executing Python code from C# that generates a list of squared numbers
- Retrieving variables from the executed Python script
- Converting Python lists to C# collections
Highlights:
- Python script uses list comprehension to create
x_squared - List is retrieved in C# and converted to a C# List
- Values are printed from C# side
File: calling_cs_function_example.cs
This example demonstrates:
- Executing Python code from C#
- Using C# functions within Python scripts
- Retrieving variables created in Python
Highlights:
- Python script uses C# function
log()(alternative to Python'sprint) - Python calls custom C# function
custom_add() - Variables created in Python (
x,y) are accessed from C# side
- Data Exchange — Pass data between Python and C#
- Function Interop — Call C# functions from Python
- Embedded Scripts — Define Python code as strings in C#
- Create a new C# console application in Visual Studio
- Install IronPython via NuGet:
Install-Package IronPython -Version 2.7.10 - Copy one of the example files into your project
- Build and run
Each example follows this pattern:
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
// Create Python engine
var engine = Python.CreateEngine();
// Execute Python code as string
engine.Execute(@"
# Python code here
");
// Access variables from C#
var result = engine.GetVariable("variable_name");- Engine Layer — IronPython runtime that interprets Python code
- Scope Layer — Variable namespace where Python variables live
- Interop Layer — Bridges between C# objects and Python code
- IronPython 2.7.10 — Install via NuGet
- .NET Framework — 4.0 or higher
Copyright © [Author Name]