Python in C# Using IronPython

16 May
C# calling Python

C# calling Python

I am better at Python than C# and when I couldn’t do something in C#, I would use:

System.Diagnostics.Process.Start(“DoItInPython.py”);

I had seen some posts about IronPython but always ignored them – to my own detriment. IronPython is the solution! You can call Python from C# or C# from Python. That means I can use System.Windows.Forms in my Python code.

Reading a post from MSDN, I put together this example that onClick() of button1 it passes the string from the textbox to a python function that just adds “Hello: ” to it. The python function is in name.py:

def printName(name):
return “Hello: “+name

The C# using IronPython:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
var ipy = Python.CreateRuntime();
dynamic test = ipy.UseFile(@”C:\Documents and Settings\user\Desktop\name.py”);
MessageBox.Show(test.printName(textBox1.Text.ToString()));
}
}
}

You can go the other way too. Read the documentation for IronPython.net for more information than I will give here. Here is a Python script using a Windows Form.

Python calling System.Windows.Forms.MessageBox.Show()

Python calling System.Windows.Forms.MessageBox.Show()

You can see it took me a minute to get it working using my own DLL. Here is how to use a System DLL:

import clr

clr.AddReference(“System.Windows.Forms”)

import System.Windows.Forms as f

f.MessageBox.Show(“Hello From Python!”)

This will popup a MessageBox. Simple, right? I have a DLL on my desktop I wrote. As you can see in my screenshot above, I got it to come in almost the same way – just use AddReferenceToFileAndPath(“C:\desktop\yourname.dll”). Here is the full code to call the method MyName() – yourname is the namespace, Name is the class and myName is a method:

import clr

clr.AddReferenceToFileAndPath(“C:\desktop\yourname.dll”)

import yourname as n

a=n.Name()

a.myName(“Paul”)

Ouputs: ‘Hello:  Paul’

Now I can use Python in C# and Windows DLLs in Python. I’m positive this will come in handy.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: