Python & C# – Background

Let’s clear the air. Using Python and C# together isn’t anything new. If you’ve used one of these languages and at least heard of the other, then you’ve probably heard of IronPython. IronPython lets you use both C# and Python together. Pretty legit. If you haven’t tried it out yet, hopefully your brain is starting to whir and fizzle thinking about the possibilities.

My development experiences is primarily in C# and before that it was VB .NET (So I’m pretty attached to the whole .NET framework… We’re basically best friends at this point). However, pretty early in my career (my first co-op at Engenuity Corporation, really) I was introduced to Python. I had never really used a dynamic or implicitly typed language, so it was quite an adventure and learning experience.

Unfortunately, aside from my time at EngCorp, I hadn’t really had a use to continue on with Python development. Lately, I’ve had a spark of curiosity. I’m comfortable with C#, sure, but is that enough? There’s lots of great programming languages out there! It’s hard for me to break out of my comfort zone though. I’m used to C# and the awesomeness of Visual Studio, so how could I ever break free from these two things?

Well… I don’t have to yet.

Python Tools for Visual Studio

This was a nice little treasure to stumble upon:

Free/OSS Python Tools for VS 2.0 RC is out! See it: http://t.co/K4eBQE2dqv – then download it: http://t.co/lbiViGC8lF — VisualStudio (@VisualStudio) September 10, 2013

But I didn’t really know what it was all about. I had heard of IronPython, and I knew I could use Python with C# together, so what exactly is “Python Tools“?

After I watched the video that the Visual Studio team tweeted out, I was captivated. Did this mean I could revisit python without having to leave the comfort of my favourite IDE? You bet. First thing I did after watching this video (and yes, I somehow managed to hold back the excitement and wait until the video was done) was fire up Visual Studio. I run with Visual Studio 2012 (the dark theme too) so in my screenshots that’s what you’ll be seeing. Once Visual Studio has loaded:

Go to the “Tools” menu at the top of the IDE.

Select the “Extensions and Updates…” menu item.

You should see the “Extensions and Updates” dialog window now.

You’re going to want to search for “Python Tools” after you’ve selected the “Online” option on the left side of the dialog. It should look something like this:

After you’ve followed all of the installation instructions, it’s time to make sure the installation worked. Simple enough!

Go to the “File” menu at the top of the IDE.

Go to the “New” menu item.

Select the “Project…” menu item.

You should now see the “New Project” dialog

To ensure Python is now available, try seeing if you have Python project templates available:

Hopefully it’s there. If not, or if you have any other install questions, I highly recommend you refer to the official site and follow along there. This is what got me up and running with my current machine, but if your setup is slightly different you should definitely follow their instructions. That’s it! You have Python Tools! But what else would make your C#, Python, and Visual Studio experience EVEN BETTER? The answer to that question is of course IronPython. Head on over to this page and get yourself setup with the latest cut of IronPython. Once that’s setup, you should have all the fancy tools you need!

Print to Console – Your First C#/Python Application

I’m sure you feel the excitement building. I’ll start by saying the code is all available online, so even though I’ll have snippets and pictures here, you can download all of the source and follow along that way if you want. Otherwise, I’ll do my best to walk you through how I set things up! This application is going to be pretty simple. It’s a tiny bit bigger than a “Hello World” application, with the difference being that you tell Python what you want to print to the console. Easy-peasy, right?

First up, let’s make a new C# console project.

From Visual Studio, go to the “File” menu at the top of the IDE.

Select the “New” menu item.

Select the “Project” menu item.

You should see the “New Project” dialog.

Select the “Visual C#” template on the left of the dialog.

Select “Console Application”.

In the framework dropdown at the top of the dialog, select .NET 4.5

Fill in the details for where you want to save your project.

Press “OK”! And we’re off!

Now that you have a console application you’re going to want to add in all the dependencies we need. If you look at the project in your solution explorer, you’re going to want to add the following dependencies:

If you’re having trouble getting the dependencies set up, remember you can always download the source projects I’ve put together. Now that you have all the necessary dependencies, here’s the source for our little application:

using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using IronPython.Hosting; namespace PrintToConsole { internal class Program { private static void Main() { Console.WriteLine("What would you like to print from python?"); var input = Console.ReadLine(); var py = Python.CreateEngine(); try { py.Execute("print('From Python: " + input + "')"); } catch (Exception ex) { Console.WriteLine("Oops! We couldn't print your message because of an exception: " + ex.Message); } Console.WriteLine("Press enter to exit..."); Console.ReadLine(); } } }

Let’s walk through what this code is doing:

First we’re getting input from the user. This is some pretty basic C# stuff, but we’re simply printing a message to the console and taking in the text the user enters before they press enter.

Next, we create a Python engine instance. This is the class that’s going to be responsible for executing python for us!

The code that exists within the try block tells our engine instance to execute some python code. The print() method that you see being passed to the engine is the syntax since Python 3.0. The parameter that we’re passing into the print() method is a python string… but we’re sticking our user input inside of it as well! It’s also important to note that we’re building up a C# string that contains all of the Python code that will be executed and passing that to the engine.

I have a catch block here to catch any unexpected problems. Can you think of any? What happens if your user input some text with a single quote?

The last part of the application just asks the user to press enter when they are all done.

Simple! There’s your first C# + Python application! You can see the source for the whole thing over here.

Run External Script

So this is great: you can now run some python code from within C#. Totally awesome. But what about all those python scripts you have written up already? Do you need to start copying and pasting them into C# code files and start to try and format them nicely? The answer is no, thankfully! Let’s start by following the exact same steps as outlined in the first example. You should be able to set up a new .NET 4.5 C# console project and add in all the same dependencies. Once you have that put together, you can use the following source code:

using System; using System.Collections.Generic; using System.Text; using IronPython.Hosting; namespace RunExternalScript { internal class Program { private static void Main(string[] args) { Console.WriteLine("Press enter to execute the python script!"); Console.ReadLine(); var py = Python.CreateEngine(); try { py.ExecuteFile("script.py"); } catch (Exception ex) { Console.WriteLine("Oops! We couldn't execute the script because of an exception: " + ex.Message); } Console.WriteLine("Press enter to exit..."); Console.ReadLine(); } } }

This script looks similar, right? Before I explain what it does, let’s add in the Python script that you’ll be executing from this console application.

Right click on your project in the solution explorer.

Select the “Add” menu item from the context menu.

Select the “New Item…” menu item.

You should see the “Add New Item” dialog.

You’ll want to add a new text file called “script.py”.

It should look a little something like this:

The next really important step is to ensure that this script gets copied to the output directory. To do this, select your newly added script file in the solution explorer and change the “Copy to Output Directory” setting to “Copy Always”. Now when you build your project, you should see your script.py file get copied to the build directory. Woo! You can put any python code you want inside of the script file, but I started with something simple:

print('Look at this python code go!')

Okay, so back to the C# code now. This example looks much like the first example.

Wait for the user to press enter before executing the Python script. Just to make sure they’re ready!

Create our engine instance, just like in the first example.

In the try block, we tell the engine to execute our script file. Because we had the file copy to the output directory, we can just use a relative path to the file here.

Again, we’ve wrapped the whole thing inside of a try/catch to ensure any mistakes you have in your python script get caught. Try putting some erroneous Python code in the script file and running. What happens?

Finally, make sure the user is content with the output and wait for them to press Enter before exiting.

Look how easy that was! Now you can choose to execute Python code generated in C# OR execute external Python scripts!

Summary

It’s awesome to see that you expressed an interest in trying to marry these two languages together inside of a powerful IDE. We’re only breaking through the surface here, and admittedly I’m still quite new to integrating Python and C# together. I need to re-familiarize myself with Python, but I can already see there is a ton of potential for writing some really cool applications this way.

In the near future, I’ll be discussing how the dynamic keyword in C# can actually allow you to create classes in Python and use them right inside of C#… Dynamically!

Both of these pages were helpful in getting me up and running with C# and Python together:

Source code for these projects is available at the following locations: