Tag: project

Python, Visual Studio, and C#… So. Sweet.

Python, Visual Studio, and C#

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:

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:

Python Tools - Visual Studio Extensions and Updates

Installing Python Tools for Visual Studio is pretty easy. Make sure you’re searching online and search for “Python Tools”.

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:

Verify Python in Visual Studio

To verify that Python is now available in Visual Studio, check under the installed templates. It should be under “Other Languages”.

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:

IronPython Dependencies in Visual Studio

Add the IronPython and Microsoft.Scripting dependencies through the solution explorer in Visual Studio.

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();
                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...");

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!");

            var py = Python.CreateEngine();
            catch (Exception ex)
                Console.WriteLine("Oops! We couldn't execute the script because of an exception: " + ex.Message);

            Console.WriteLine("Press enter to exit...");

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:

Add new Python script in Visual Studio

In the “Add New Item” dialog, select “Text File” and rename it to “script.py”.

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!


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:

Cookie Cutters For Projects


When you’re starting work on a new project or organizing a team to accomplish a goal, there’s often a foundation that needs to be established:

  • How is your team structured?
  • What software should we use to help us?
  • How do we set goals?
  • How do we measure our progress
  • … the list goes on.

It’s a common challenge that’s met by anyone organizing a team or setting off to work on something. So do you copy what worked for someone else by using a cookie cutter approach, or do you wing it and see what happens? My approach when faced with two extremes is usually to aim somewhere in the middle.


Cookie Cutters

Being a copy-cat and using cookie cutters has some benefits. If something worked for some all-star teams at big successful companies, then why re-invent the wheel? They’ve proven that they have a process that works!

Look at a successful company that’s the same size as yours. Look at a team that’s completed a project that has a lot of parallels to what you’re going to be working on. How did they structure their team? Did they split off into smaller sub teams? Did they have daily meetings to discuss progress? Weekly? Monthly? Are they using some sort of software to assist them in their work? Maybe it’s a ticket tracking software, or some CRM to aid with customer interaction. If it worked for them, why wouldn’t it work for you?

The answer to that is because you aren’t them, you’re not working on the same project, and despite all the parallels you might see, your environment is different.


From Scratch

Okay okay… So if we can’t copy people, then let’s just do it all from scratch. Start your project tomorrow by holding a meeting and seeing who wants to work on what. Let people just start tackling parts of the project. Have someone create some software that will help you in accomplishing your goal (after all, you don’t want to copy someone else and use some well-established software). And now that you’ve all set off on working on parts of the project, you should probably just meet whenever you need to. Probably not best to schedule anything, because you don’t even know if you need to meet!

So, that sounds pretty sketchy, right? Clearly doing everything from scratch doesn’t seem ideal… Why re-invent the wheel on things that have been proven to work? Where’s the happy medium?


The Happy Medium

The truth is there are aspects to tackling a challenge with a team that have been proven to work. There are processes out there that teams have used successfully, software that has improved team efficiency, and strategies for gauging progress that have been used effectively. So when do you copy and when do you work from scratch?

My personal recommendation is to evaluate your options from the start. Look at what other successful companies are doing. Do they use a waterfall approach to developing products, or are they agile? Are they using particular software products for tracking progress, managing projects, interacting with customers, and/or automating processes? Make a list of those too. How often do they meet with other team members? Why are they meeting at those intervals? What are the pros and cons?

After you come up with your options, start gauging how they might apply to you. Your customer requirements are set in stone for your enormous project? Maybe a waterfall approach is better than being agile. Everyone on your team has success using Git and bad experiences using subversion for their source code… So maybe you start with that. Maybe tasks are changing pretty frequently and it’d be helpful to have frequent updates from team members, so you meet briefly every day for updates. Look at your options and think of why certain ones might be good for you.

Start with something. Try it out. There’s no guarantee you’re going to be right the first time you try things out. Actually, it’s likely you’ll do it wrong. But so what? Find out what works. Find out what doesn’t. Then figure out why something didn’t work, and swap that process for something else. Swap that software for something that fits your needs better. Change what doesn’t work and you’ll converge to a rock solid foundation. But don’t fix what isn’t broken. If your daily meetings have been working well for everyone, then why bother arbitrarily switching them to weekly? If it works, then use it.



Regardless of your approach to getting your challenge completed, I think one thing is important: Have flexibility in your foundation until you find what works. Don’t use certain things because other people say to. Use what you think might work best after you’ve evaluated your options, and then once you’ve had it in place for some time, change what doesn’t work. Use the cookie cutters as a source of information and inspiration for why you might want to try something, but don’t let your entire foundation be built from one big cookie cutter. Use lots of little cookie cutters to make your foundation for overcoming your challenge the best it can be for your team and not someone else’s.

  • Nick Cosentino

    Nick Cosentino

    I work as a team lead of software engineering at Magnet Forensics (http://www.magnetforensics.com). I'm into powerlifting, bodybuilding, and blogging about leadership/development topics over at http://www.devleader.ca.

    Verified Services

    View Full Profile →

  • Copyright © 1996-2010 Dev Leader. All rights reserved.
    Jarrah theme by Templates Next | Powered by WordPress