Friday, February 15, 2008

Python.NET 2.0 for .NET SP1

In a recent post I showed how to compile and install Python.NET 2.0 alpha 2. Unfortunately, if you are using .NET 2.0 SP 1, the instructions won't produce a fully-functional build [1]. That's because some changes in SP1 broke the latest Python.NET code. However, Nicolas Lelong figured out the solution and posted a simple patch to the Python.NET mailing list. The patch is only necessary if you are using .NET 2.0 SP 1, but non-SP 1 systems can use it as well.


I've recompiled the binaries myself and posted them here.

To verify that the patch works correctly, try running the following code.

import clr
from System.Drawing import Color
from System.Windows.Forms import Form, Button, Label, BorderStyle, DockStyle

count = 0

def onclick(sender, args):
    global count
    count += 1
    l.Text = 'You clicked the {%s} button %d times' % (sender.Text, count)

if __name__ == '__main__':
    f = Form()
    f.Text = 'Hello WinForms!'
    f.Width = 500

    l = Label()
    l.Text = 'This is a label'

    b = Button()
    b.Text = 'Click Me!'
    b.Click += onclick

    # Layout:
    l.Dock = DockStyle.Top
    b.Dock = DockStyle.Top


If you don't see any weird errors [2], then everything should be fine.

[1]Specifically, delegates won't work. That means, for example, that you won't be able to use Python functions to handle button clicks in a GUI.

If you are using an unpatched Python.NET with .NET SP1, you would see an error like this:

System.TypeInitializationException: The type initializer for 'Python.Runtime.CodeGenerator' threw an exception.

No comments: