Click here to Skip to main content
15,301,291 members
Articles / General Programming
Technical Blog
Posted 23 Sep 2013


35 bookmarked

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

Rate me:
Please Sign up or sign in to vote.
4.97/5 (20 votes)
23 Sep 2013CPOL9 min read
Python, Visual Studio, and C#

Image 1

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 experience 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:

Image 2

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:

Image 3

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)
                   "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 inputs 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)
                   "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 “”.

It should look a little something like this:

Image 5

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

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 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:

The source code for these projects is available at the following locations:

The post Python, Visual Studio, and C#… So. Sweet. appeared first on Dev Leader.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Nick Cosentino
Team Leader Magnet Forensics
Canada Canada
I graduated from the University of Waterloo for Computer Engineering and I'm fortunate enough to work as a Team Lead of Software Engineering at Magnet Forensics. As a team lead, I'm often looking to encourage better coding standards, creative approaches to problem solving, and ensure that good clean code makes it into the code base. I want my team to produce top-notch code, but I want to make sure that we're all learning to become better developers along the way.


Comments and Discussions

QuestionIs this convert Python code to C# code too? Pin
Member 1331189115-Jul-17 22:04
MemberMember 1331189115-Jul-17 22:04 
QuestionThanks for the article great, one question Pin
Member 132192696-Jun-17 20:01
MemberMember 132192696-Jun-17 20:01 
QuestionPython Script consisting of nltk packages. Pin
Poonam Goje2-May-17 0:24
MemberPoonam Goje2-May-17 0:24 
QuestionThanks Pin
Aldonis5510-May-16 2:29
MemberAldonis5510-May-16 2:29 
Questionintegrating an external python script in my wpfapplication in visual studio 2013 Pin
Member 1232985627-Mar-16 11:41
MemberMember 1232985627-Mar-16 11:41 
GeneralMy vote of 5 Pin
Mahsa Hassankashi14-Aug-15 4:06
MemberMahsa Hassankashi14-Aug-15 4:06 
Questioniron pyhton pip installation. Pin
nikunj mange24-May-15 23:10
Membernikunj mange24-May-15 23:10 
QuestionPython + .net Widgets Pin
blipton30-Oct-14 18:15
Memberblipton30-Oct-14 18:15 
AnswerRe: Python + .net Widgets Pin
Nick Cosentino30-Oct-14 18:28
MemberNick Cosentino30-Oct-14 18:28 
QuestionGreat examples - still I have a question Pin
Member 701715417-May-14 3:37
MemberMember 701715417-May-14 3:37 
AnswerRe: Great examples - still I have a question Pin
Nick Cosentino17-May-14 4:13
MemberNick Cosentino17-May-14 4:13 
QuestionExample on a Windows application Pin
Lalo9262726-Feb-14 10:18
MemberLalo9262726-Feb-14 10:18 
AnswerRe: Example on a Windows application Pin
Nick Cosentino26-Feb-14 14:33
MemberNick Cosentino26-Feb-14 14:33 
GeneralRe: Example on a Windows application Pin
Lalo9262727-Feb-14 4:11
MemberLalo9262727-Feb-14 4:11 
GeneralRe: Example on a Windows application Pin
Nick Cosentino27-Feb-14 11:15
MemberNick Cosentino27-Feb-14 11:15 
GeneralRe: Example on a Windows application Pin
Lalo926276-Mar-14 13:23
MemberLalo926276-Mar-14 13:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.