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

43 Responses 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

  2. Adogippill Says:

    thank you, dude

  3. apenIbiarape Says:

    thats it, bro

  4. USA casino slots Says:

    USA casino slots…

    River Belle online casino….

  5. 1 hour casino Says:

    1 hour casino…

    Las Vegas USA casino….

  6. Free spin casinos Says:

    Free spin casinos…

    Yukon gold slots….

  7. Royal casino codes Says:

    Royal casino codes…

    DaVincis Gold casino….

  8. Microgaming bonus codes Says:

    Microgaming bonus codes…

    Super party jackpot….

  9. USA online slots Says:

    USA online slots…

    Virtual casino coupon code….

  10. 1 hour free play Says:

    1 hour free play…

    Free bankroll no deposit….

  11. Big dollar casino Says:

    Big dollar casino…

    Casino spins for USA….

  12. Free money casino Says:

    Free money casino…

    Download bingo star….

  13. Club USA casino Says:

    Club USA casino…

    How to win at slots in Vegas….

  14. English harbour casino Says:

    English harbour casino…

    Bodog bonus chips….

  15. Bet royal casino Says:

    Bet royal casino…

    Free spins video slots….

  16. All slots casino Says:

    All slots casino…

    Flash casino bonus….

  17. USA no deposit casinos Says:

    USA no deposit casinos…

    Lucky coin casino….

  18. Free Vegas slots Says:

    Free Vegas slots…

    Slots royale code….

  19. No registration slots Says:

    No registration slots…

    Casino roulette 777….

  20. 32 Vegas Casino bonus Says:

    32 Vegas Casino bonus…

    Jupiter club casino bonus….

  21. US free bonus casino Says:

    US free bonus casino…

    Carribean gold casino….

  22. Free spin slot games Says:

    Free spin slot games…

    Cirrus casino bonus code….

  23. Instant play slots Says:

    Instant play slots…

    Intercasino promotion code….

  24. Bella Vegas casino Says:

    Bella Vegas casino…

    Golden casino coupons….

  25. US casinos no deposit Says:

    US casinos no deposit…

    Zodiac online casino….

  26. Club player no deposit Says:

    Club player no deposit…

    Royal dice no deposit code….

  27. US free slot casino Says:

    US free slot casino…

    Golden casino code….

  28. USA no deposit casino Says:

    USA no deposit casino…

    Caribbean gold casino….

  29. New microgaming casinos Says:

    New microgaming casinos…

    Eurogrand casino bonus….

  30. Low deposit casino Says:

    Low deposit casino…

    Vegas wild casino….

  31. Flash casino slots Says:

    Flash casino slots…

    Bodog coupon codes….

  32. RTG no deposit bonus codes Says:

    RTG no deposit bonus codes…

    Online casino match bonus….

  33. US slots promotions Says:

    US slots promotions…

    Prism casino code….

  34. Casino bonus list Says:

    Casino bonus list…

    Super party jackpot….

  35. No download slot games Says:

    No download slot games…

    Lucky emperor coupons….

  36. USA 1 hour free casino Says:

    USA 1 hour free casino…

    Maple casino bonus….

  37. Casino instant play Says:

    Casino instant play…

    1 hour free play casino….

  38. Free flash casinos Says:

    Free flash casinos…

    Super jackpot party….

  39. No download casino slots Says:

    No download casino slots…

    Golden reef casino bonus….

  40. RTG casino code Says:

    RTG casino code…

    Prism casino codes….

  41. US slots promotions Says:

    US slots promotions…

    Lucky emperor code….

  42. Sign up casino bonus Says:

    Sign up casino bonus…

    Sign up bingo bonus….

  43. Free slot games Says:

    Free slot games…

    Bella Vegas casino coupon….

Leave a Reply

You must be logged in to post a comment.