Python and .NET playing together!

* * * * * 1 votes

Intro

Lately my head has been up in the clouds playing around with a few languages, Python, C#, and Java (we'll get into Java later) as I usually do for fun and I thought how fun would it be to mix them!

Of course this is nothing new. There have been interpreters to mix and match them all you like for some time now and in this blog we'll focus on Python and .NET for now.

IronPython

IronPython is an implementation of the Python interpreter written completely in .NET. Being that it is written in .NET you can access all the .NET libraries with the interpreter and run it on any platform.

To run IronPython on any other than MS Windows (*nix, Mac, etc) you will need to install Mono. Mono provides the necessary software to run and develop .NET software on other platforms.

Note: The Mac package of Mono comes with IronPython. If you are on *nix you can probably find a package for your distro or have to compile it for yourself. If you are on MS Windows you can get the latest .NET run time from your Windows Update.

It takes two to tangle!

So after all that babble lets get started! Out of all the .NET languages I am currently most familiar with C# so I'm going to be taking some C# examples and showing you how to do them with Python using the IronPython interpreter which is invoked via the ipy command.

We'll start first with the ever so boring "Hello World" program.

In C# we would do something like this:

using System;
 
public class HelloWorld
{
	public static void Main()
	{
		Console.WriteLine("Hello Richard!");
	}
}

The above code should be extremely obvious, if not I suggest some polishing up of your C# skills.

Now with Python, I'm going to write the same exact thing (minus wrapping it in a class since its unnecessary with Python at this point) and I'm going to output "Hello Richard" using the same C# libraries:

from System import *
 
Console.WriteLine("Hello Richard")

That's it! An extremely simple 2 lines! Not bad huh? Of course that was cool but not something so useful.

All we've done was imported the System library into the current name space. We could have also done import System but then we would have had to write the whole System.Console.WriteLine() command. In some cases that might be useful if you don't want certain things to conflict.

Now lets do something a little more cool like interacting with a DLL created completely in .NET. If you want to know how to create a DLL file yourself then Google it but for now I'm going to take one already made.

For this example I'm going to use the MySQL .NET Connector and query some junk from my database.

Here would be the C# way (borrowed from here):

using System;
using System.Data;
using MySql.Data.MySqlClient;
 
public class Test
{
	public static void Main(string[] args)
	{
		string connectionString =
			"Server=localhost;" +
			"Database=test;" +
			"User ID=myuserid;" +
			"Password=mypassword;" +
			"Pooling=false";
 
		IDbConnection dbcon;
		dbcon = new MySqlConnection(connectionString);
		dbcon.Open();
		IDbCommand dbcmd = dbcon.CreateCommand();
		// requires a table to be created named employee
		// with columns firstname and lastname
		// such as,
		//        CREATE TABLE employee (
		//           firstname varchar(32),
		//           lastname varchar(32));
		string sql =
			"SELECT firstname, lastname " +
			"FROM employee";
		dbcmd.CommandText = sql;
		IDataReader reader = dbcmd.ExecuteReader();
		while(reader.Read()) {
			string FirstName = (string) reader["firstname"];
			string LastName = (string) reader["lastname"];
			Console.WriteLine("Name: " +
				FirstName + " " + LastName);
		}
		// clean up
		reader.Close();
		reader = null;
		dbcmd.Dispose();
		dbcmd = null;
		dbcon.Close();
		dbcon = null;
	}
}

Now, lets do this the Python way with the same rules as the last example; using the same C# libraries.

import clr
clr.AddReferenceToFile("MySql.Data.dll") # MySql.Data.dll must be located in the same directory as this script
 
from System import *;
from MySql.Data.MySqlClient import *;
 
connStr = (
	"Server=localhost;"
	"Database=test;"
	"User ID=myuserid;"
	"Password=mypassword;"
	"Pooling=false"
)
 
conn = MySqlConnection(connStr)
conn.Open()
cmd = conn.CreateCommand()
"""
requires a table to be created named employee
with columns firstname and lastname
such as,
   CREATE TABLE employee (
      firstname varchar(32),
      lastname varchar(32));
"""
sql = "SELECT firstname, lastname FROM employee"
cmd.CommandText = sql
reader = cmd.ExecuteReader()
while reader.Read():
	firstName = reader["firstname"]
	lastName = reader["lastname"]
	Console.WriteLine("Name: %s %s" % (firstName, lastName));
 
# clean up
reader.Close()
reader = None
cmd.Dispose()
cmd = None
conn.Close()
conn = None

And walla! You have to admit, that is pretty awesome! We've got the power of simplicity from Python along with the power of .NET at our finger tips!

You can also import libs that you've gac'd (installed via gacutil) by replacing line 2 with clr.AddReference("MySql.Data") which might be more useful in some cases.

Conclusion

There's so much we can do with this such as prototype, making simple test cases, or even utilities for your .NET application. I've found this lots of fun and hope you do too. Stay tuned and keep your eyes peeled for another article on roasting the same blend of code with Jython!

Be sure to also take a look at these other links that might interest you as well!

Share/Save/Bookmark

One Response to “Python and .NET playing together!”

  1. Daniel Says:

    I read similar article also named Python and .NET playing together!, and it was completely different. Personally, I agree with you more, because this article makes a little bit more sense for me

Leave a Reply