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:
[csharp]
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();
}
}
}
[/csharp]
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:
[csharp]
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();
}
}
}
[/csharp]
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:
[python]
print(‘Look at this python code go!’)
[/python]
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:
- http://stackoverflow.com/questions/1394488/embedding-ironpython-2-in-c-sharp-what-is-the-replacement-for-defaultmodule-gl
- http://blogs.msdn.com/b/charlie/archive/2009/10/25/hosting-ironpython-in-a-c-4-0-program.aspx
Source code for these projects is available at the following locations:
Pingback: Python, Visual Studio, and C#… So. Sweet. has been posted at Dev Leader | Nick's Blog
Pingback: Movember Prep - Weekly Article Dump | Dev Leader
Pingback: Dynamic Programming with Python and C# | Dev Leader
This article also appears on CodeProject:
http://www.codeproject.com/Articles/657698/Python-Visual-Studio-and-Csharp-So-Sweet
Pingback: v6.2 of IEF from Magnet Forensics! - Weekly Article Dump « Dev Leader Dev Leader
Pingback: Dynamic Programming with Python and C# « Dev Leader Dev Leader
Pingback: Movember Prep - Weekly Article Dump « Dev Leader Dev Leader
Pingback: IronPython: A Quick WinForms Introduction « Dev Leader Dev Leader
Is it possible to create a true windows application using only python and .net? The examples I’ve seen all use the console to demonstrate a ‘hello world’ application.
Or does one have to start with c# and then add python to make windows apps?
Thanks!
Thanks for the question Ben. To make a windows form app using *JUST* strictly Python and .NET, sure, it’s entirely possible. If you have Python installed on a system, you can always just launch a new process pointed at Python scripts.
If you’re cool with IronPython like I was showing in this example, then it’s even easier (in my opinion). Here I showed a console application, but check out my other post on this stuff:
https://www.devleader.ca/2014/04/07/ironpython-quick-winforms-introduction/
In this example, I built up a WinForm application that uses IronPython. The point is, it’s not restricted to just console applications. If you want to get Python actually doing some of the UI work, I think things would start to get interesting there… I don’t want to say it’s impossible (it probably just needs a handle for where to render to) but I haven’t ventured into that territory.
Let me know if that helps!
Hi Nick,
I have MSVS2010 Ultimate, but following your guide, no Python Tools are retrieved searching online. Do you know if I necessarily have to have a later version than 2010?
I googled it and came across the following page, but the download link is basically a MSVS download. I am not sure if I should go ahead and download this:
https://www.visualstudio.com/en-us/features/python-vs.aspx
Please let me know what you think…
Thanks,
H
Hey there!
I don’t want to leave you hanging or anything, but I’m not positive. I think I recall reading that Microsoft has done a better integration of Python and Visual Studio in more recent times. So perhaps that’s totally replaced the original integration I wrote about.
The only thing I can’t really advise is whether or not that particular download will be compatible with your product. However, I do think you’re probably on the right track!
With that said, I’d say it’s worth a check. 🙂
Good day,
first of all thanks for your incredible and useful post.
There is problem when I use “import numpy” in my python script file. although the package has been installed on python 2.7 I got error “can not find module numpy”.
Would you please help me.
Thanks
Hello.
Is it at all possible to include libraries like numpy and matplotlib in your script when using IronPython? I keep getting “cannot find module X” errors and would really like to find a way to be able to use this capabilities.
Any help would be greatly appreciated.
Can we add a python project as part of same solution along with C# project?
Also, can I call python function from C# code, where py script is in py project and C# code in another project. But, both are in same solution. (am unable to add py project as reference)