Tag: PyTools

IronPython: A Quick WinForms Introduction

IronPython: A Quick WinForms Introduction

Background

A few months ago I wrote up an article on using PyTools, Visual Studio, and Python all together. I received some much appreciated positive feedback for it, but really for me it was about exploring. I had dabbled with Python a few years back and hadn’t really touched it much since. I spend the bulk of my programming time in Visual Studio, so it was a great opportunity to try and bridge that gap.

I had an individual contact me via the Dev Leader Facebook group that had come across my original article. However, he wanted a little bit more out of it. Since I had my initial exploring out of the way, I figured it was probably worth trying to come up with a semi-useful example. I could get two birds with one stone here–Help out at least one person, and get another blog post written up!

The request was really around taking the output from a Python script and being able to display it in a WinForm application. I took it one step further and created an application that either lets you choose a Python script from your file system or let you type in a basic script directly on the form. There isn’t any fancy editor tools on the form, but someone could easily take this application and extend it into a little Python editor if they wanted to.

Leveraging IronPython

In my original PyTools article, I mention how to get IronPython installed into your Visual Studio project. In Visual Studio 2012 (and likely a very similar approach for other versions of Visual Studio), the following steps should get you setup with IronPython in your project:

  • Open an existing project or start a new one.
  • Make sure your project is set to be at least .NET 4.0
    • Right click on the project within your solution explorer and select “Properties”
    • Switch to the “Application” tab.
    • Under “Target framework”, select  “.NET Framework 4.0”.
  • Right click on the project within your solution explorer and select “Manage NuGet Packages…”.
  • In the “Search Online” text field on the top right, search for “IronPython”.
  • Select “IronPython” from within the search results and press the “Install” button.
  • Follow the instructions, and you should be good to go!

Now that we have IronPython in a project, we’ll need to actually look at some code that gets us up and running with executing Python code from within C#. If you followed my original post, you’ll know that it’s pretty simple:


var py = Python.CreateEngine();
py.Execute("your python code here");

And there you have it. If it seems easy, that’s because it is. But what about the part about getting the output from Python? What if I wanted to print something to the console in Python and see what it spits out? After all, that’s the goal I was setting out to accomplish with this article. If you try the following code, you’ll notice you see a whole lot of nothing:


var py = Python.CreateEngine();
py.Execute("print('I wish I could see this in the console...')");

What gives? How are we supposed to see the output from IronPython? Well, it all has to do with setting the output Stream of the IronPython engine. It has a nice little method for letting you specify what stream to output to:


var py = Python.CreateEngine();
py.Runtime.IO.SetOutput(yourStreamInstanceHere);

In this example, I wanted to output the stream directly into my own TextBox. To accomplish this, I wrote up my own little stream wrapper that takes in a TextBox and appends the stream contents directly to the Text property of the TextBox. Here’s what my stream implementation looks like:


private class ScriptOutputStream : Stream
{
  #region Fields
  private readonly TextBox _control;
  #endregion

  #region Constructors
  public ScriptOutputStream(TextBox control)
  {
    _control = control;
  }
  #endregion

  #region Properties
  public override bool CanRead
  {
    get { return false; }
  }

  public override bool CanSeek
  {
    get { return false; }
  }

  public override bool CanWrite
  {
    get { return true; }
  }

  public override long Length
  {
    get { throw new NotImplementedException(); }
  }

  public override long Position
  {
    get { throw new NotImplementedException(); }
    set { throw new NotImplementedException(); }
  }
  #endregion

  #region Exposed Members
  public override void Flush()
  {
  }

  public override int Read(byte[] buffer, int offset, int count)
  {
    throw new NotImplementedException();
  }

  public override long Seek(long offset, SeekOrigin origin)
  {
    throw new NotImplementedException();
  }

  public override void SetLength(long value)
  {
    throw new NotImplementedException();
  }

  public override void Write(byte[] buffer, int offset, int count)
  {
    _control.Text += Encoding.GetEncoding(1252).GetString(buffer, offset, count);
  }
  #endregion
}

Now while this isn’t pretty, it serves one purpose: Use the stream API to allow binary data to be appended to a TextBox. The magic is happening inside of the Write() method where I take the binary data that IronPython will be providing to us, convert it to a string via code page 1252 encoding, and then append that directly to the control’s Text property. In order to use this, we just need to set it up on our IronPython engine:


var py = Python.CreateEngine();
py.Runtime.IO.SetOutput(new ScriptOutputStream(txtYourTextBoxInstance), Encoding.GetEncoding(1252));

Now, any time you output to the console in IronPython you’ll get your console output directly in your TextBox! The ScriptOutputStream implementation and calling SetOutput() are really the key points in getting output from IronPython.

The Application at a Glance

I wanted to take this example a little bit further than the initial request. I didn’t just want to show that I could take the IronPython output and put it in a form control, I wanted to demonstrate being able to pick the Python code to run too!

Firstly, you’re able to browse for Python scripts using the default radio button. Just type in the path to your script or use the browse button:

IronPython - Run script from file

Enter a path or browse for your script. Press “Run Script” to see the output of your script in the bottom TextBox.

Next, press “Run Script”, and you’re off! This simply uses a StreamReader to get the contents of the file and then once in the contents are stored in a string, they are passed into the IronPython engine’s Execute() method. As you might have guessed, my “helloworld.py” script just contains a single line that prints out “Hello, World!”. Nothing too fancy in there!

Let’s try running a script that we type into the input TextBox instead. There’s some basic error handling so if your script doesn’t execute, I’ll print out the exception and the stack trace to go along with it. In this case, I tried executing a Python script that was just “asd”. Clearly, this is invalid and shouldn’t run:

python_error_asd

Python interpreted the input we provided but, as expected, could not find a definition for “asd”.

That should be along the lines of what we expected–The script isn’t valid, and IronPython tells us why. What other errors can we see? Well, the IronPython engine will also let you know if you have bad syntax:

python_error_bad_syntax

Python interpreted the script, but found a syntax error in our silly input.

Finally, if we want to see some working Python we can do some console printing. Let’s try a little HelloWorld-esque script:

python_pass_hello_world

Python interpreted our simple Hello World script.

Summary

This sample was pretty short but that just demonstrates how easy it is! Passing in a script from C# into the IronPython is straight forward, but getting the output from IronPython is a bit trickier. If you’re not familiar with the different parts of the IronPython engine, it can be difficult to find the things you need to get this working. With a simple custom stream implementation we’re able to get the output from IronPython easily. All we had to do was create our own stream implementation and pass it into the SetOutput() method that’s available via the IronPython engine class. Now we can easily hook the output of our Python scripts!

As always, all of the source for you to try this out is available online:

Some next steps might include:

  • Creating your own Python IDE. Figure out some nice text-editing features and you can run Python scripts right from your application.
  • Creating a test script dashboard. Do you write test scripts for other applications in Python? Why not have a dashboard that can report on the results of these scripts?
  • Add in some game scripting! Sure, you could have done this with IronPython alone, but maybe now you can skip the WinForms part of this and just make your own stream wrapper for getting script output. Cook up some simple scripts in a scripting engine and voila! You can easily pass information into Python and get the results back out.

Let me know in the comments if you come up with some other cool ideas for how you can leverage this!


Movember Prep – Weekly Article Dump

MoMagnets - Magnet Forensics' Movember Team

Movember Preparation

You might think we’re a bit early on this one, but at Magnet Forensics we’re going to take Movember to a whole new level this year. If you’re not familiar with Movember, you may want to head over here and get a rundown of the history of it. Movember started in Australia between a group of people who wanted to (somewhat jokingly) bring the moustache back into style. The next year they started getting people to grow mo’s for causes. Now people participate in Movember to raise awareness for men’s health, and it’s bigger than ever.

Our team members of MoMagnets have started discussing the various styles of mo’s that they’ll grow this year. It looks like there’s going to be some intra-team competition to grow the best mo. The top contenders? It’s looking like:

Matthew Chang - Movember

Matthew “The Chang” “Changarang” Chang sporting a well-groomed black moustache. Although it’s a standard ‘stache, the care put into keeping this beauty mo in tip-top shape is obvious. Can he do it again for this Movember?

Cameron Sapp - Movember

Cameron Sapp showing off a rock solid handle bar mo. The bars on this ‘stache are so impressive that it almost gives the illusion that this mo is taller than it is wide. Wait… is it?!

Check out the MoMagnets page and keep track of us! Please contribute what you can to help raise awareness for men’s health.

Articles

  • Python, Visual Studio, and C#… So. Sweet.: First one on the list this week is the post I put out on Monday about using Python, C#, and Visual Studio all together. It’s definitely for the developers out there, but for those of you who aren’t programmers, it’s still interesting to see how PyTools and IronPython have bridged a gap between C# and Visual Studio. I was pretty happy with the number of people who responded on social media and thought that it was a good read. The tweets actually led me to find a related post by Scott Hanselman from earlier this year (that I wish I saw sooner). My article has also received some pretty good visibility at Code Project which I’m excited about. Feel free to check it out over there too (people seem more likely to engage in discussion at Code Project versus on my blog)!
  • Want To Build A Business? Lead With Trust: David Hassell wrote an article that really hit home with me. Having a successful business means crafting a team and culture built upon trust. It needs to be the foundation of your team. Having high levels of trust makes everything else in the business come together more easily, but lacking trust can really make everything fall apart. Teams need to trust their leaders, and leaders need to trust their team members–it goes both ways.
  • Amazon CEO Jeff Bezos Had His Top Execs Read These Three Books: John Fortt discusses his interview with Amazon CEO Jeff Bezos. Now while I don’t read as much as I should (and I’m consciously trying to get better at it), I thought this little list of books might be great to keep my eye out for:
  • Confidence ‘boosts pupils’ academic success: I thought this article was a great find. It’s primarily around research that’s shown confidence plays a big role in students’ success, but I believe it applies outside of the realm of formal education. As a leader or mentor, I think it’s incredibly important to instill confidence. You want your team members to know you trust them with what they’re doing. They need to know they can make mistakes and learn without having to be punished for doing so. Having that confidence is going to be what makes them successful.
  • Leadership Lessons From LEGO: What do leadership and Lego have in common? A whole lot according to John Kotter. Consider innovation (get creative with those bricks!), overcoming challenges (can’t find that piece you were looking for?), team work (building things with friends is way more fun), and quality (it’s as good as you make it). It was an unexpected article for me to stumble upon, but I thought the parallels were interesting!
  • The Four Most Powerful Lessons in Management: Joel Peterson has some great points on being a successful leader or manager. Among them, putting actions behind your words, bring the right people on board (noticing a trend with having the right people yet?), and having a meaningful mission.
  • What is a Thought Leader?: I found myself asking this question at one point, which is why I wanted to share Daniel Tunkelang‘s article. It seems straight forward really. It’s important to have an area of expertise in the ideas you want to share, and it’s important that the things you’re sharing have meaning. In my case with Dev Leader, I certainly haven’t mastered leadership and programming, but I’m sharing the ideas that I’m hoping will some day get me there.
  • 17 Things You Should Never Say to Your Boss: This was definitely a great read. At first, I started thinking “How could anyone in their right mind say these things to their boss”? But then I realized I had actually heard some of these things (or similar things) and it really got me thinking. Dave Kerpen has put together a great list, and although it’s humourous, it’s still something important to watch out for. Just in it for the money? Not your role? Some people need to get a grip or find something else to do in their career.
  • Why These Happiness “Boosters” Might Actually Make You Feel Worse: Gretchen Rubin shares some ideas on why certain things we do to make us happier may actually be counter-productive. One interesting one I thought was the idea of your attitude shaping your behaviour may actually be your behaviour shaping your attitude. On weekends I often hang around in a pair of shorts until I have to head out of my condo. If I got in the habit of being prepped to leave the house and be productive from the beginning of the day, would I find that I’m actually more productive? Worth trying!
  • What Makes Developers Really Great: Deane Barker shares his experience with a software developer that was giving off some bad vibes. So what’s a good developer? Is it just someone who can code? Do they need to know all the latest and best languages, dream in code, and have four computer science degrees? It certainly helps (and I don’t think many would dismiss it), but the one thing that’s really important is their attitude and ability to work in their team. Check out the comments on that blog post. If you’re working on a team and you can’t fit in the team, you’ll bring the whole team down. This means if you’re all soft skills and no hard skills, you can’t contribute squat. If you’re all hard skills and no soft skills, you’re going to be a road block to your team. You need to have both to be a really great developer.

Remember to check out the MoMagnets page! We’d really appreciate it. Follow Dev Leader on social media outlets to get these updates through the week.

Nick Cosentino – LinkedIn
Nick Cosentino – Twitter
Dev Leader – Facebook
Dev Leader – Google+

You can also check out Dev Leader on FlipBoard.


  • 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