Iron python windows console что это

Содержание

Поговорим про IronPython

Расскажем об интересном проекте IronPython. Описание звучит так: «IronPython — это реализация языка программирования Python с открытым исходным кодом, которая тесно интегрирована с .NET Framework. IronPython может использовать библиотеки .NET Framework и Python, а другие языки .NET могут также легко использовать код Python».

Для начала установим все необходимое. Для работы с данным проектом нам понадобиться Visual Studio (мы используем 2019,. Net Framework необходим не ниже 4.5,. Net Core 2.0 или 2.1). Установить можно через менеджер Nuget Install-Package IronPython Install-Package IronPython.StdLib. Текущая, на момент написания статьи, версия – 2.7.10.

Для начала создадим приложение Windows Forms и добавим туда все, что требуется:

В этот раз не будем пытаться решать сложных проблем, придумаем что-нибудь простое и одновременно показывающее взаимодействие Python и C#. Пусть нам необходимо сложить 2 числа (и мы по каким-то причинам не хотим делать эту операцию обыкновенным способом «в столбик» или с помощью калькулятора). Для этого добавим на нашу форму 3 TextBox-а, пару Label-ов и один Button. Должно получиться примерно так:

В первые два текстовых поля мы будем вводить наши значения, а в третьем пусть отображается наш результат.

Определим две переменные:

Стоит отметить, что все, что будет взаимодействовать с IronPython, должно быть «public».

Существует несколько методов для работы со скриптами в Ironpython:

Нам больше всего нравится способ ExecuteFile(), его и будем использовать. Для этого в метод инициализации формы добавим следующее:

Для того, чтобы выполнить какой-нибудь скрипт, добавим в код метода обработки кнопки следующий код:

В указанном выше коде выполняется построчно следующее:

Ну и сам Python-файл с функцией содержит код:

Проверим, как работает наш «вычислитель»:

Верно! У нас получилось написать простейшее приложение с применением этой технологии. Кажется, мы решили «детскую» задачку – написали простейший калькулятор, который умеет только складывать два числа. Но разве не с простых «детских» задач начинается изучение чего-то нового?!Это неплохая возможность в изучении с использованием уже знакомых инструментов. С помощью IronPython можно не только интерпретировать некоторый код, но и проводить некоторые параллели при изучении Python. К примеру, код на C#:

Будет эквивалентен следующему коду на IronPython:

Есть некоторое сходство, верно?!

Источник

IronPython: что это за программа? Установка, настройка и описание

Характеристика IronPython по сравнению с CPython

Точные характеристики производительности IronPython, если сравнивать с CPython (это эталонная реализация языка программирования Python), будут зависеть от конкретного использования конкретного синтаксиса. В целом IronPython по производительности чуть хуже, чем CPython. Это доказано большим количеством тестов, сделанных с использованием скрипта PyStone.

Установка Iron P ython

В целом установка Iron P ython — дело не хитрое. Будут небольшие различия в зависимости от того, какую операционную систему вы используете.

Установка Iron P ython в Linux

Установка Iron P ython в Linux довольно проста и умести тся в несколько простых шагов:

Установка Iron P ython MacOS

Здесь тоже все просто. Сама установка займет пару минут и всего несколько шагов:

Установка IronPython в Windows

Здесь всего 2 шага отделяет вас от программирования на этом языке:

Так что это за программа IronPython, для чего использовать?

Использовать или нет IronPyt h on — зависит только от вашего желания и необходимости конкретно в этом языке.

Мы будем очень благодарны

если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.

Источник

IronPython

Для начала создадим приложение Windows Forms и добавим туда все, что требуется:

В этот раз не будем пытаться решать сложных проблем, придумаем что-нибудь простое и одновременно показывающее взаимодействие Python и C#. Пусть нам необходимо сложить 2 числа (и мы по каким-то причинам не хотим делать эту операцию обыкновенным способом «в столбик» или с помощью калькулятора). Для этого добавим на нашу форму 3 TextBox-а, пару Label-ов и один Button. Должно получиться примерно так:

В первые два текстовых поля мы будем вводить наши значения, а в третьем пусть отображается наш результат.

Определим две переменные:

Стоит отметить, что все, что будет взаимодействовать с IronPython, должно быть “public”.

Существует несколько методов для работы со скриптами в Ironpython:

Мне больше всего нравится способ ExecuteFile(), его и будем использовать. Для этого в метод инициализации формы добавим следующее:

Для того, чтобы выполнить какой-нибудь скрипт, добавим в код метода обработки кнопки следующий код:

В указанном выше коде выполняется построчно следующее:

Ну и сам Python-файл с функцией содержит код:

Проверим, как работает наш «вычислитель»:

Верно! У нас получилось написать простейшее приложение с применением этой технологии. Кажется, мы решили «детскую» задачку – написали простейший калькулятор, который умеет только складывать два числа. Но разве не с простых «детских» задач начинается изучение чего-то нового?! Лично для себя я вижу неплохую возможность в изучении с использованием уже знакомых мне инструментов. С помощью IronPython можно не только интерпретировать некоторый код, но и проводить некоторые параллели при изучении Python. К примеру, код на C#:

Будет эквивалентен следующему коду на IronPython:

Есть некоторое сходство, верно?!

Источник

Перейдем непосредствено к кодированию.
Для начала, рассмотрим интерфейс тестового приложения «Notepad».


В меню «Сервис» и разместим пункт «Макросы». Для примера рассмотрим простейший вариант формирования списка макросов — в каталоге с программой создадим папку «Macroses» файлы из этой папки станут пунктами меню.

internal class MacrosToolStripMenuItem : ToolStripMenuItem
<
public MacrosToolStripMenuItem( string FileName) : base (FileName) < >
public string MacrosFileName < get ; set ; >
>

MacrosToolStripMenuItem — класс-наследник от ToolStripMenuItem отличающийся только свойством MacrosFileName

Для начала, создадим макрос, который просмотрит текст в textBox’е и найдет все e-mail адреса вида «vpupkin@mail.ru». В папке Macroses создаем файл SaveEmail.py, запускаем приложение — и смотрим, что в меню Макросы появился пункт SaveEmail.

Теперь собственно ключевой момент — выполнение IPy скрипта и доступ его к интерфейсу. Добавляем к проекту ссылку на сборку IronPython.dll. И создаем класс MacroRunner — выполняющий скрипт.

public class MacroRunner
<
public static Form CurrentForm;

public string FileName

try
<
pyEngine.ExecuteFile(FileName);
>
catch (Exception exc)
<
MessageBox.Show(exc.Message);
>
>
>

Ключевой момент — подключение к выполняющей среде IPy текущей сборки — для доступа к форме. Когда сборка подключена, в IPy скрипте появится возможность использовать классы пространства имен Notepad. Так же, через LoadAssebmly можно добавить и другие необходимые сборки — типа System.Windows.Forms — чтобы работать с формами.
Класс готов, теперь модифицируем обработчик клика на пунктах подменю Макросы

protected void macroToolStripMenuItem_Click( object sender, EventArgs e)
<
MacrosToolStripMenuItem item = sender as MacrosToolStripMenuItem;

MacroRunner runner = new MacroRunner() < FileName = item.MacrosFileName >;
MacroRunner.CurrentForm = this ;
runner.Execute();
>

Здесь следует отметить следующий момент — чтобы передать в IPy-скрипт форму, из которой собственно вызывается макрос — используется статическое поле CurrentForm. В скрипте форма будет доступна как Notepad.MacroRunner.CurrentForm. В идеале, скрипт, разумеется, не должен иметь полного доступа к интерфейсу формы — а должен пользоватся только предоставленным API — и ограничиваться только им. Но сейчас этим заморачиваться не будем — и просто сделаем textBox открытым (Modifier = Public). Ну и кроме текстового поля, разрешим скрипту доступ к пункту меню Сервис (Modifier = Public).

Работа с формой закончена, собираем проект и открываем файл SaveEmail.py — теперь работаем только с макросами.

Итак, первый макрос — SaveEmail.py:

Т.к. сборка подключена к среде выполнения — то доступно пространство имен Notepad — в котором объявлены классы приложения. Как раз сейчас потребуется статический метод класса MacroRunner — чтобы получить доступ к активной форме (еще раз оговорюсь — что правильнее было бы предоставить не прямой доступ, а через класс-посредник — которые ограничит доступ определенным API). Ну а дальше все просто — получаем текст, регулярным выражением вытаскиваем email — и сохраняем их в файл в текущем каталоге.

Можно запустить приложение, ввести произвольный текст, содежащий email — и убедиться, что после того, как макрос отработал — в папке с выполняемой программой появился файл emails.txt.

Теперь еще один пример, что может сделать макрос — чуть интереснее предыдущего. Итак, создаем в папке Macroses файл UIModifier.py. Как можно догадаться по названию — макрос будет изменять элементы интерфейса приложения. Конкретно — добавит новый пункт в меню Сервис. Для того, чтобы можно было работать с элементами управления WinForms необходимо в среде выполнения IPy подключить сборку System.Windows.Forms. Это можно сделать в момент запуска скрипта из приложения — добавить еще один вызов LoadAssembly. Но мы решили — никаких перекомпиляций, пусть IronPython обходится своими силами. Ну что ж, силы есть :). Чтобы подключить сборку используется метод AddReference класса clr.

from Notepad import *
main = MacroRunner.CurrentForm

import clr
clr.AddReference( «System.Windows.Forms» )
from System.Windows.Forms import *

def pyHello(s,e):
MessageBox.Show( «Hello from IPy!» )

item = ToolStripMenuItem()
item.Name = «pybtn»
item.Text = «Python created!»
item.Click += pyHello

Все просто — получаем текущую форму, подключаем сборку System.Windows.Forms и импортируем из пространства имен System.Windows.Forms все — пригодится.
pyHello — простенький обработчик события — при щелчке на созданном пункте меню — будет выводится сообщение.

Запускаем приложение, выполняем макрос. Смотрим пункт меню Сервис:


При щелчке на пункт меню «Python сreated!» появится стандартный MessageBox — собственно, чего и добивались.

Источник

Introduction

Some of the exercises in this tutorial require prerequisites. The prerequisites to successfully complete the whole tutorial are:

This tutorial assumes that the IronPython distribution was uncompressed into the directory C:\IronPython. Please note that your individual setup may vary.

This tutorial also assumes that you will launch the IronPython console (c:\ironpython\ipy.exe) from the tutorial directory. When the tutorials direct you to start the IronPython console from the tutorial directory, you should change to the tutorial directory (>cd c:\ironpython\tutorial) and launch the console with the tutorial as your working directory (>..\ipy.exe).

Tutorial 1: Basic IronPython

Estimated time to complete this tutorial: 30 minutes

The exercises in this tutorial are:

Exercise 1: The IronPython interactive console

In this exercise, you will start the IronPython interactive interpreter and perform simple tasks to become acquainted with the IronPython environment.

If you are familiar with using the Python interactive console, the import statement and exploring the Python interactive environment using dir() function and __doc__ attribute, you can skip this exercise.

Task 1: IronPython console

Start the IronPython console from the tutorial directory by changing to the tutorial directory (>cd c:\ironpython\tutorial) and launching the console c:\ironpython\ipy.exe executable (>..\ipy.exe). This is how you should always launch the console for the tutorials, but from now on, we’ll just direct you to «start the IronPython console from the tutorial directory».

Execute simple statements listed below. After each statement IronPython prints the result, if any, and awaits more input. (The input line starting with «for» requires an extra return or enter key press because the interpreter prompts for more statements in the ‘for’ loop.)

for i in range(3): print i

After this step, the console window will contain the following text:

>>> for i in range(3): print i

IronPython console supports multi-line statements, often used by function definitions. IronPython prompts for additional lines of multi-line statements using:

Unlike C# or Java, where blocks of code are grouped by curly brackets «<. >«, blocks of code in Python are grouped based on their level of indentation. Every new block of code must be indented one more level than the previous block of code. Blocks of code are used for function and class definitions as well as ‘if’ statements and loops.

Define the «add» function (note, you need to enter spaces before the ‘return’ statement):

def add(a, b):
return a + b

To complete the function definition, press Enter once more at this point

After this step, the console contents will be:

>>> def add(a, b):
. return a + b
.
>>> add(3, 2)

To exit the IronPython interactive console, type Ctrl+Z and Enter (alternatively, press F6 followed by Enter).

Task 2: Built-in modules and interactive exploration

Start the IronPython console from the tutorial directory (see Introduction for details).

Using the built-in dir() function, list the contents of the IronPython environment:

The output in the console window will be:

[‘__builtins__’, ‘__doc__’, ‘__name__’]
>>>

IronPython comes with several built-in modules, the most frequently used one being «sys». Import «sys» module using the «import» statement:

The Python import statement is similar to the «using» statement of C# or «Imports» statement of Visual Basic. The important difference is that the C# and VB statements bring the names from the imported namespace into to the global namespace to be accessed directly. Python’s import doesn’t do that. To access the names or attributes in an imported module, prefix the names with the module’s name:

Use the dir() function to explore the environment:

The environment (global namespace) has changed, now it contains the «sys» module:

[‘__builtins__’, ‘__doc__’, ‘__name__’, ‘sys’]
>>>

Use the dir() function to explore the contents of the «sys» module:

Print the values of some of the «sys» module attributes:

Task 3: External Python modules

This task uses the module «first.py» located in the Tutorial folder.

Import the «first.py» module located in the Tutorial (because you launched ipy.exe from the Tutorial directory, «first» will be found on your sys.path):

Explore the module «first» using dir() function:

[‘__builtins__’, ‘__doc__’, ‘__file__’, ‘__name__’, ‘add’, ‘factorial’, ‘hi’]

Print the documentation for the «add» and «factorial» functions, using __doc__ attribute:

Call the methods in the «first» module and print the contents of the «hi» attribute

The expected output is:

‘Hello from IronPython!’

Exit the IronPython Interactive console (Ctrl+Z or F6 followed by Enter)

Start the IronPython console from the tutorial directory (see Introduction for details).

Explore the System.Environment class and access some of its properties:

The expected output of these commands is as follows (with some ellipsis for convenience):

Microsoft Windows NT 5.2.3790 Service Pack 1

from System.Math import *

Now you can call Math methods without having to specify the namespace and class name prefix:

The expected output is:

>>> from System.Math import *

[‘Abs’, ‘Acos’, ‘Asin’, ‘Atan’, ‘Atan2’, ‘BigMul’, ‘Ceiling’, ‘Cos’, ‘Cosh’, ‘DivRem’, ‘E’, ‘Equals’, ‘Exp’, ‘Floor’, ‘GetHashCode’, ‘GetType’, ‘IEEERemainder’, ‘Log’, ‘Log10’, ‘Max’, ‘Min’, ‘PI’, ‘Pow’, ‘Round’, ‘Sign’, ‘Sin’, ‘Sinh’, ‘Sqrt’, ‘System’, ‘Tan’, ‘Tanh’, ‘ToString’, ‘Truncate’, ‘__builtins__’, ‘__doc__’, ‘__name__’]

Import the contents of the «System.Collections» namespace into the global namespace:

from System.Collections import *

Create instance of the Hashtable class and explore the instance using dir():

Insert a few elements into the hash table:

The output of this step will be:

>>> h[«a»] = «IronPython»
>>> h[«b»] = «Tutorial»

for e in h: print e.Key, «:», e.Value

The expected output in the console is (the input line starting with «for» requires an extra return or enter key press because the interpreter prompts for more statements in the ‘for’ loop.):

>>> for e in h: print e.Key, «:», e.Value

a : IronPython
b : Tutorial

You can initialize the collection classes by passing in the Python built-in list or tuple data types as arguments. You can create a Python list by specifying the list of elements in square brackets: [1,2,3]. You create tuples by specifying elements in the parentheses: (1,2,3).

for i in l: print i

The expected output is:

>>> l = ArrayList([1,2,3])
>>> for i in l: print i

>>> s = Stack((1,2,3))
>>> while s.Count: s.Pop()

Task 3: Generics

Import the Generic collections from the System.Collections.Generic namespace

from System.Collections.Generic import *

Add string values into the list. Since we created list of string, adding string is possible:

Try adding objects of types other than string:

Obviously, adding non-strings will fail with type error:

Traceback (most recent call last):
.

ValueError: The value «3» is not of type «System.String» and cannot be used in this generic collection.

Parameter name: value

Enumerate the generic collection:

for i in l: print i

The output will be:

>>> for i in l: print i

Exit the IronPython Interactive console (Ctrl+Z or F6 followed by Enter)

clr.AddReferenceToFile adds reference to the assembly specified by its file name. This function will load the assembly from the file regardless of the assembly version. As a result, it doesn’t guarantee that the correct assembly version is being loaded. To guarantee that correct assembly version is being loaded, use clr.AddReferenceByName. Moreover, AddReferenceToFile requires that the assembly be located in a directory listed in sys.path.

clr.AddReferenceToFileAndPath provides similar functionality to AddReferenceToFile. The difference is that it accepts absolute path and before loading the assembly, AddReferenceToFileAndPath adds the file path into sys.path.

clr.AddReferenceByName adds reference to the assembly specified by its full assembly name, for example: ‘System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’.

clr.AddReferenceByPartialName adds reference to the assembly by specifying a partial assembly name. This function cannot guarantee that the correct version of the assembly is being loaded. Use clr.AddReferenceByName to add reference to specific version of the assembly.

Start the IronPython console from the tutorial directory (see Introduction for details).

To import System.Xml, the reference to the assembly containing the Xml components must be first added to IronPython. Add reference to System.Xml using the following code (you can enter «clr.References» before and after the call to clr.AddReference to see it change if you want):

from System.Xml import *

Note that the clr.AddReference function accepts either System.Reflection.Assembly object or string as a parameter. The string parameter can be a full assembly name, a partial assembly name, or a file name. For more control over the assembly references, use the appropriate functions described above.

For example, consider the following alternatives for the statement clr.AddReference(«System.Xml») above:

clr.AddReferenceByName(‘System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’)

Load the XML file «Releases.xml» into the XmlDocument. The xml file contains the release dates of all versions of IronPython between 0.7 and 0.9.4. For direct viewing, the Releases.xml file is located in «Releases.xml»

We can now query the document. Query for all released versions of IronPython using the query below:

for e in n: print e.Value

The output in the console window will be:

>>> n = d.SelectNodes(«//@Version»)
>>> for e in n: print e.Value

(Optional) Import the «xmlutil.py» module located in the Tutorial directory and use the function provided in the module to walk the contents of the Xml document:

for e in xmlutil.Walk(d): print e.Name, e.Value

The Walk function is a generator (a Python function that contains a «yield» statement). As the Walk function executes, it returns (yields) the XML nodes one by one to the caller who iterates over the generator. The source for the Walk function is:

if hasattr(xml, «Attributes»):
attrs = xml.Attributes
if attrs:
for attr in attrs:

for child in xml:
for c in Walk(child):

Exit the IronPython Interactive console (Ctrl+Z or F6 followed by Enter)

This task requires the Mapack.dll library for linear algebra computations. The library is not part of the IronPython distribution. See prerequisites for download details.

Start the IronPython console from the tutorial directory (see Introduction for details).

Use the clr.AddReferenceToFile function to load the Matrix library «Mapack.dll»:

from Mapack import *

The expected output will be:

>>> import clr
>>> clr.AddReferenceToFile(«Mapack.dll»)
>>> from Mapack import *
>>> dir()

[‘CholeskyDecomposition’, ‘EigenvalueDecomposition’, ‘LuDecomposition’, ‘Matrix’, ‘QrDecomposition’, ‘SingularValueDecomposition’, ‘__builtins__’, ‘__doc__’, ‘__name__’, ‘clr’, ‘sys’]

Create instance of Matrix class:

Oops, bad arguments for the constructor. In the next step you’ll learn the way to discover the constructors available.

>>> m = Matrix()
Traceback (most recent call last):
at

TypeError: Matrix() takes at least 1 argument (0 given)

Using the __doc__ attribute, find out information about Matrix constructors:

__new__(int, int)
__new__(int, int, float)
__new__(System.Double[][])

>>> m = Matrix(2, 2, 1.2)
>>> n = Matrix(2,1)
>>> n[0,0] = 4
>>> print m

Make simple calculations with the matrices:

The expected output of this step is:

Exit the IronPython Interactive console (Ctrl+Z or F6 followed by Enter)

Exercise 4: Obtaining and Using Python Standard Library

In this exercise, you will obtain Python and point IronPython at the Python standard library.

Task 1: Configuring IronPython to use the Python standard library

Download the latest Python installer from http://www.python.org/download/ and install Python. The rest of this exercise will assume you used defaults (and installed to c:\python24, for example).

Create a file named «site.py» and place it into your IronPython «Lib» directory. There might be one there already, so you can just edit it. The «site.py» file is executed every time you run IronPython. To tell IronPython where the Python standard library is, you can add the «lib» directory of Python to IronPython’s path. To do so, put the following code into IronPython’s «site.py» file (replace c:\python24\lib with your actual path to the Python lib directory):

Start the IronPython console from the tutorial directory (see Introduction for details).

Now you can use the Python standard library from IronPython, for example to get the current working directory (output uses assumed location of your IronPython installation):

In this tutorial you performed the following exercises.

Tutorial 2: Advanced IronPython

This tutorial will focus on creating delegates, handling events in IronPython, and creating Windows applications using Windows Forms and the new Windows Presentation Foundation (formerly known as Avalon).

Estimated time to complete this tutorial: 25 minutes

The objective of this tutorial is to learn how to create delegates and handle events using IronPython, and to use that knowledge to build working Windows applications using Windows Forms and Windows Presentation Foundation.

Exercise 1: Events and Delegates

Task 1: File System Watcher

Start the IronPython console from the tutorial directory (see Introduction for details).

Import the contents of System.IO into the global namespace:

from System.IO import *

Create instance of the FileSystemWatcher class and set Path property to watch over the current directory:

Create the function to handle the events. Because we don’t know yet what arguments the delegate will have, let’s accept any number of arguments (the *arg notation):

def handle(*args): print args

Register the event handler for the ‘Changed’, ‘Created’, and ‘Deleted’ events:

Enable the watcher to raise events:

Open the Tutorial folder and create a file. An easy way to create the file is to right-click with the mouse and select «New\Text Document». The file watcher will raise the «Created» event.

You can then open the file in Notepad, type in any text, and save the file. This raises the «Changed» event. Then finish by deleting the file to see the «Deleted» event get raised.

At the end of this step, the output in the command window will be similar to the following:

(System.IO.FileSystemWatcher, )
(System.IO.FileSystemWatcher, )
(System.IO.FileSystemWatcher, )
(System.IO.FileSystemWatcher, )

In the next task, we will create an improved event handler. For now, remove the current event handler from the file watcher events:

(Optional) You can try step 7 again to see that the events, while they are still being raised, are not being handled by the Python «handler» function.

Task 2: Improving the event handler

In the previous task, step 7 we can see that the types of the parameters passed to all three events were the same:

Use dir() to explore the event arguments class to find what information the event contains:

The output in the console window will be:

[‘ChangeType’, ‘Empty’, ‘Equals’, ‘Finalize’, ‘FullPath’, ‘GetHashCode’, ‘GetType’, ‘MakeDynamicType’, ‘MemberwiseClone’, ‘Name’, ‘Reduce’, ‘ReferenceEquals’, ‘ToString’, ‘__class__’, ‘__doc__’, ‘__init__’, ‘__module__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’]

Now with more knowledge of the event argument properties, we can create a better event handler that will print ChangeType and FullPath properties of the event argument object:

def handle(w, a): print a.ChangeType, a.FullPath

Register the new event handler for the ‘Changed’, ‘Created’ and ‘Deleted’ events:

Make sure the raising of the events is enabled:

Open the Tutorial folder again and create a new file («Created» event), edit the file in Notepad and save it («Changed» event) and finish by deleting the file («Deleted» event).

At the end of this step, the output in the command window will be similar to the following:

Remove the event handler from the file watcher events:

Exit the IronPython Interactive console (Ctrl+Z or F6, followed by Enter).

Task 3: Defining events in Python

Finally let’s look at how we can get event handler syntax from Python code:

To create an event:

We’ll define a class that has an event for

class MyClass(object):
OnNewInstance,_NewInstance= pyevent.make_event()
def __new__(cls):
res = object.__new__(object)
MyClass._NewInstance(res)

def NewInst(x): print ‘new inst: ‘, x

Just like with CLR events you can also remove event handlers:

Exercise 2: Windows Forms

To interactively develop Windows applications, IronPython must be initialized for that purpose. By default, the Python console executes on one thread only. While this thread awaits text input in the console window, the Windows application being dynamically created from the console is not able to process Windows messages. Therefore, the application does not repaint itself or handle input to the UI.

In this exercise, you will create simple Windows Forms applications dynamically from the IronPython interactive console.

Task 1: Simple Windows Forms application

Start the IronPython console from the tutorial directory (see Introduction for details).

Initialize Windows Forms by loading the winforms module/script:

Python modules get automatically initialized (executed) upon import so the Windows Forms initialization code has executed as part of the import statement.

Import the contents of the System.Windows.Forms and System.Drawing namespaces into the global namespace:

from System.Windows.Forms import *

from System.Drawing import *

Create an instance of the Form class and display it:

You may need to alt-tab or look for the running application since it may not have popped to the top level on your desktop.

Now set the form Text property:

f.Text = «My First Interactive Application»

To bring the application alive, let’s focus on the Click event of the form. Create an event handler for the Click event and click on the form to receive the event. Then remove the event handler

def click(*args): print args

Click on the form to receive the event..

The output will be similar to:

>>> (System.Windows.Forms.Form, Text: My First Interactive Application, )

Now remove the click handler because we’re going to further develop it.

Use dir() function to explore the MouseEventArgs

Knowing the contents of the MouseEventArgs, create an improved event handler for the Click event:

def click(f, a):
l = Label(Text = «Hello»)
l.Location = a.Location
f.Controls.Add(l)

Register the event handler:

Now clicking on the form with the mouse will add «Hello» labels. We can also access the controls we just added via mouse clicks and change them

for i in f.Controls: i.Font = Font(«Verdana», 15)

for i in f.Controls: i.Text = «Hi»

After a few moments of clicking, the form will get quite crowded, so we can clear it out:

Exit the IronPython Interactive console (Ctrl+Z or F6 followed by Enter)

The standalone version of this script is located in wfdemo.py in the Tutorial directory.

Exercise 3: Windows Presentation Foundation (Avalon)

This exercise requires Windows Presentation Foundation installed. Please see prerequisites for more information.

Just like Windows Forms, the Windows Presentation Foundation also requires initialization to support interactive development. The initialization code is available in the «Tutorial\avalon.py» file.

In this exercise, you will interactively create simple interactive Windows Presentation Foundation application.

Task 1: Simple Avalon Application

Start the IronPython console from the tutorial directory (see Introduction for details).

Initialize Windows Presentation Foundation:

from avalon import *

Create Avalon window, display it, and set some of its properties:

You may need to alt-tab or look for the running application since it may not have popped to the top level on your desktop. Now, let’s do more.

w.Title = «My Avalon Application»

By setting the window property to «size to content», the window shrinks.

Let’s add the content now:

w.Content.Text = «Hello IronPython!»

Remove the window content:

Task 2: Avalon calculator

If you are continuing from the Task 1, proceed to step 2. Otherwise, please follow the steps 1-3 from the Task 1.

Windows Presentation Foundation uses the XAML format to describe the graphical layout and basic behaviors of UI. Load the «calc.xaml» and display the resulting content:

If you flowed into this task from Task 1, then w.SizeToContent may have been reset to manual, but in either case, you may need to manually drag the window’s border down and to the right to see the calculator UI.

Let’s walk the calculator’s object model (function Walk is defined in the avalon.py file)

for n in Walk(w): print n

Using Python’s list comprehension syntax we can capture all buttons in the calculator:

[ n for n in Walk(w) if isinstance(n, Button) ]

The console printed the list of all buttons. To save the button list object in a variable, use the interpreter’s «_» variable, which always holds the last non-None value result printed by the console:

At this point we can make changes to all the buttons, for example, change the colors and fonts:

for b in buttons: b.FontSize *= 2

for b in buttons: b.Foreground = SolidColorBrush(Colors.Blue)

To bring the calculator alive, we need to provide event handlers for each button. These can be imported from the calculator.py file:

The calculator module contains the Calculator class that will be responsible for tracking the expression as it is being built by the calculator. To bring the calculator alive (that is, register event handlers for the UI), enter:

At this point you can click on the calculator buttons and evaluate expressions.

Feel free to explore the calculator.py script file (located in Tutorial directory). The point of interest is the Calculator.__init__ method:

def __init__(self, controls): (1)
self.expression = «» (2)
(3)
for i in controls: (4)
if isinstance(i, Button): (5)
if hasattr(self, «on_» + i.Name): (6)
i.Click += getattr(self, «on_» + i.Name) (7)
elif isinstance(i, TextBox): (8)
if i.Name == «Result»: (9)
self.result = i (10)
self.result.Text = self.expression (11)

The second point of interest is the on_Equals method, especially the highlighted line. Python has a built-in function, «eval», which evaluates an expression passed as a string and returns the resulting value. Calculator uses «eval» to evaluate the calculator expressions. The «str» function will then convert the value into a string for display.

def on_Equals(self, b, e):
try:

self.result.Text = result
self.expression = result
except:
self.result.Text = » >»
self.expression = «»

Exit the IronPython Interactive console (Ctrl+Z or F6 followed by Enter)

IronPython provides very easy way to develop live applications in a dynamic and exploratory way. Both Windows Forms and Windows Presentation Foundation (Avalon) applications can be easily developed this way with minimal setup. The advantage is that changes are visible immediately and modifications are happening to live system and don’t require recompilation.

In this tutorial you performed the following exercises:

Tutorial 3: IronPython and COM interoperability

Estimated time to complete this tutorial: 20 minutes

The objective of this tutorial is to explore COM interoperability from IronPython.

Exercise 1: Merlin the Wizard

In this exercise, you will create a COM interop assembly and use it to drive the COM object from IronPython.

Task 1: Creating COM interop assemblies

Open the «SDK Command Prompt» or «Visual Studio 2005 Command Prompt» from the start menu.

Type library imported to AgentServerObjects.dll

When you are done exploring the AgentServerObjects.dll, close the ildasm tool. Copy AgentServerObjects.dll to the tutorial directory, and then close the Windows command prompt.

Task 2: Using COM objects from IronPython

Start the IronPython console from the tutorial directory (see Introduction for details).

Using the «AddReferenceToFile» function in the clr module, add a reference to the AgentServerObjects.dll:

Import the contents of the AgentServerObjects namespace and explore the contents using dir():

from AgentServerObjects import *

Create instance of the AgentServerClass and explore its contents:

The output in the console window will be:

>>> a = AgentServerClass()
>>> dir(a)

[‘CreateObjRef’, ‘Equals’, ‘GetCharacter’, ‘GetHashCode’, ‘GetLifetimeService’, ‘GetSuspended’, ‘GetType’, ‘InitializeLifetimeService’, ‘Load’, ‘MemberwiseClone’, ‘Register’, ‘ToString’, ‘Unload’, ‘Unregister’, ‘__class__’, ‘__init__’, ‘__module__’, ‘__new__’]

Explore the parameters of the Load method on AgentServerClass:

‘(int, int) Load(object, vLoadKey)\r\n’

The Load methods have an input parameter (name of the character to load) and two output parameters. When calling this method, IronPython will turn the two output parameters into multiple return values.

Call GetCharacter method on the AgentServerClass instance to get the actual character, display the character and have him think about IronPython Tutorial:

Merlin has a lot of animations he can play. Get list of all the animations by calling the GetAnimationNames method. Play one of the animations, «Read», by calling the Play method:

for n in c.GetAnimationNames(): print n

(Optional) To call a series of animations, we could call c.Play(animation_name) for each animation. Python’s lamda functions can simplify this process. We can create global functions and assign them names based on the animation name:

for n in c.GetAnimationNames(): globals()[n] = lambda name=n: c.Play(name)

At this point we can have Merlin play animations simply by
calling a function from global namespace:

Stop Merlin’s animations, hide him, and exit IronPython console

Exercise 2: Use Word for Spell Checking

In this exercise you will create an instance of Microsoft Word and use it to check word spellings.

Task 1: Accessing Word and Checking Spelling

Start the IronPython console from the tutorial directory (see Introduction for details).

Import clr module and add a reference to the Word COM interop assembly. Also, import System so that we can use a special value from it later.

clr.AddReferenceByPartialName(«Microsoft.Office.Interop.Word»)
from Microsoft.Office.Interop.Word import ApplicationClass

Start an instance of Word as a COM server running. You won’t see it show up since it is hidden, but you can see it in the Windows Task Manager by typing ctrl-shift-escape and looking for the WINWORD.EXE process.

Define the following function to check the spelling. We have to build up an argument list so that we can supply the 12 optional arguments we do not care about (System.Type.Missing). We get the answer by taking the first (at index zero) of a few return values (out parameters in COM interop). Remember to indent the lines of the function’s body extra spaces, and you have to hit an extra return or enter to complete the function’s definition.

def check_word (word):
args = [word] + [System.Type.Missing]*12
return w.CheckSpelling(*args)[0]

You can try that out on a couple of words, but now lets define a function that will suggest corrections for us. First, we need to add a document so that we can call GetSpellingSuggestions(), which gives a nice error message if you try to call it with no documents opened.

The function we’ll define builds an argument list just like check_word() did to supply several unneeded optional arguments. The first result of several return values from GetSpellingSuggestions() is a collection of items, each of which is a correction suggestion. We use a Python list comprehension to iterate through the COM collection object and call the Name property on each item object in the collection. Each item’s Name property is a string that Word is suggesting as a correct spelling.

def suggestions (word):
args = [word] + [System.Type.Missing]*13
res_objects = w.GetSpellingSuggestions(*args)[0]
return [x.Name for x in res_objects]

Now, let’s shut down Word and exit the IronPython console. When you enter the next line and hit return, if you are watching the Windows Task Manager, you will see the WINWORD.EXE process go away.

Task 2: Use Windows Form Dialog to Correct Spelling

In this task you will use an example already written that is very similar to what you did in Task 1, but it demonstrates two additional features. It uses a Python standard module to register a clean up function so that when the IronPython console terminates, the Word process is closed. The example also has a function, correct_word, that uses a Windows Form as a dialog to let users select a correct word to return.

Start the IronPython console from the tutorial directory (see Introduction for details).

Call spellcheck.correct_word on a correctly spelled word, and you’ll see the function returns the word.

Call spellcheck.correct_word on a misspelled word, and a Windows Form similar to Word’s spelling correction dialog appears. You can pick from the list and click the Replace button, double click a word in the suggestions list, enter custom text and click the Use Custom button, click an Ignore button to return the misspelled word, and so on.

Open the spellcheck.py file to see the code for the the Windows Form as well as the functions.

In this tutorial you performed the following exercises.

Then, from IronPython you loaded the interop assembly, created an instance of the COM object, and instructed Merlin to play different animations.

You also used Word to check the spelling of words, learned how to supply missing optional arguments, and inspected code that builds a Windows Form and uses it as a dialog.

Tutorial 4: Debugging IronPython program

This tutorial will walk you through very simple debug session, debugging a Python script using Microsoft CLR Debugger. See using Visual Studio if you have a Visual Studio SKU and consider skipping this exercise.

Estimated time to complete this tutorial: 10 minutes

The objective of this tutorial is debugging simple Python script using Microsoft CLR Debugger.

Exercise 1: Debugging IronPython program

In this exercise, you will step through a simple Python script in the Microsoft CLR Debugger.

Task 1: Debugging IronPython program using Microsoft CLR Debugger

Launch Microsoft CLR Debugger.

For Program, browse to the ipy.exe (located in the installaton directory)

For Arguments, type in debugging.py

Change Working directory to the Tutorial directory

From Menu, select File / Open / File. Browse to the Tutorial directory and select two files to open:

Place breakpoint at the following line of the debugging.py file (Place cursor on the line and pres F9):

IronPython will compile the debugging.py file and start executing it. You will hit the breakpoint at the line 3.

Note: If you get poor performance starting the debugging session, exit the debugger, open the Windows Explorer and delete the following directory:

Pressing F11, step through the execution of the program, explore variables (even change the values of the variables in the watch window) and explore the call stack.

End the debugging session and exit the debugger.

In this tutorial you performed the following exercises.

In this tutorial, you walked through the simple debug session of IronPython program. You used Microsoft CLR Debugger, placed breakpoints and stepped through the Python program execution.

Tutorial 5: Extending IronPython

Estimated time to complete this tutorial: 25- 60 minutes

Exercise 1: Extending using C#

In this exercise you will use C# language to build a class that supports enumeration, custom operators and delegates and you will use that class from IronPython. It’s worth noting that as Python does not contain protected class members, that these members get promoted to public class members when imported into Python. Private class members, however, will be invisible to Python when imported.

Open the «SDK Command Prompt» or «Visual Studio 2005 Command Prompt» from the start menu.

Open the «csextend.cs» file in notepad. The file is initially empty

Add using clauses at the beginning of the file:

using System;
using System.Collections;

Define a simple class:

public class Simple <
private int data;

public Simple(int data) <
this.data = data;
>

public override string ToString() <
return String.Format(«Simple «, data);
>
>

Switch back to the SDK Command Prompt window and build the code using available csx.bat (C# extension):

Start the IronPython console from the tutorial directory (see Introduction for details).

Load the dll that you just built (csextend.dll) into IronPython. Then explore the Simple class using built-in dir() function:

You will see following output:

>>> import clr
>>> clr.AddReferenceToFile(«csextend.dll»)
>>> import Simple
>>> dir(Simple)

[‘Equals’, ‘GetHashCode’, ‘GetType’, ‘ToString’, ‘__new__’, ‘__repr__’]

Create instance of the Simple class:

IronPython will output:

>>> s = Simple(10)
>>> print s

You have just explored all the functionality currently available in the Simple class. Exit IronPython and return back to the C# code to add more functionality.

Task 2: Making the object enumerable

In Notepad, add more functionality to the Simple class.

First, inherit the Simple class from IEnumerable and implement GetEnumerator() method. Use the C#’s new «yield return» statement:

public class Simple : IEnumerable <

private int data;
public Simple(int data) <
this.data = data;
>
public override string ToString() <
return String.Format(«Simple «, data);
>

public IEnumerator GetEnumerator() <
for (int i = 0; i >> import clr
>>> clr.AddReferenceToFile(«csextend.dll»)
>>> import Simple
>>> dir(Simple)
[‘Equals’, ‘GetEnumerator’, ‘GetHashCode’, ‘GetType’, ‘ToString’, ‘__new__’, ‘__repr__’]
>>> s = Simple(10)

>>> for i in s: print i

Simple
Simple
Simple
Simple
Simple
Simple
Simple
Simple
Simple
Simple

Notice that the dir() function now returned the GetEnumerator method.

Exit IronPython and return back to the C# code to add more functionality.

Task 3: Adding custom operator

Add the operator + method:

using System;
using System.Collections;

public class Simple : IEnumerable <
private int data;
public Simple(int data) <
this.data = data;
>
public override string ToString() <
return String.Format(«Simple «, data);
>
public IEnumerator GetEnumerator() <
for (int i = 0; i >> import clr
>>> clr.AddReferenceToFile(«csextend.dll»)
>>> import Simple
>>> dir(Simple)
[‘Equals’, ‘GetEnumerator’, ‘GetHashCode’, ‘GetType’, ‘ToString’, ‘__add__’, ‘__new__’, ‘__radd__’, ‘__repr__’]
>>> a = Simple(10)
>>> b = Simple(20)

Exit IronPython and return back to the C# code to add more functionality.

Task 4: Adding delegate

Add the definition of the delegate to the top of the C# source file:

using System;
using System.Collections;

public delegate int Transformer(int input);

Add «Transform» method to the Simple class that takes the delegate as a parameter and invokes the delegate:

using System;
using System.Collections;

public delegate int Transformer(int input);

public class Simple : IEnumerable <
private int data;
public Simple(int data) <
this.data = data;
>

public override string ToString() <
return String.Format(«Simple «, data);
>

public IEnumerator GetEnumerator() <
for (int i = 0; i >> import clr
>>> clr.AddReferenceToFile(«csextend.dll»)
>>> import Simple
>>> a = Simple(10)

>>> def X(i):
. return i + 100
.
>>> a.Transform(X)

Exercise 2: Extending using Visual Basic.NET

Open the «SDK Command Prompt» or «Visual Studio 2005 Command Prompt» from the start menu.

Open the «vbextend.cs» file in notepad. The file is initially empty

Add Imports clauses at the beginning of the file:

Imports System
Imports System.Collections

Define a simple class:

Public Class Simple
Private data As Integer

Public Sub New(ByVal data As Integer)
Me.data = data
End Sub

Overrides Function ToString() As String
Return String.Format(«Simple «, data)
End Function

Switch back to the SDK Command Prompt window and build the code using the available vbx.bat (Visual Basic extension):

Start the IronPython console from the tutorial directory (see Introduction for details).

Load the dll that you just built (vbextend.dll) into IronPython. Then explore the Simple class using built-in dir() function:

You will see following output:

>>> import clr
>>> clr.AddReferenceToFile(«vbextend.dll»)
>>> import Simple
>>> dir(Simple)

[‘Equals’, ‘GetHashCode’, ‘GetType’, ‘ToString’, ‘__new__’, ‘__repr__’]

Create instance of the Simple class:

IronPython will output:

>>> s = Simple(10)
>>> print s

You just have explored all the functionality available in the Simple class. Exit IronPython and return back to the Visual Basic code to add more functionality.

Task 2: Making the object enumerable

Back in Notepad, add more functionality to the vbextend.vb, Simple class

First, inherit the Simple class from IEnumerable and implement GetEnumerator() method. Unlike C#, Visual Basic does not offer the yield keyword so implementing IEnumerable interface requires adding a helper class SimpleEnum:

Imports System
Imports System.Collections

Public Class SimpleEnum
Implements IEnumerator

Private data As Integer
Private curr As Integer

Public ReadOnly Property Current() As Object _
Implements IEnumerator.Current
Get
Return New Simple(curr)
End Get
End Property

Public Function MoveNext() As Boolean _
Implements IEnumerator.MoveNext
curr += 1
Return curr «, data)
End Function

Function GetEnumerator() As IEnumerator _
Implements IEnumerable.GetEnumerator
Return New SimpleEnum(data)
End Function

Compile the code (vbx), launch IronPython Console (ip) and test the code:

for i in s: print i

You will get the following output in the IronPython console window:

>>> import clr
>>> clr.AddReferenceToFile(«vbextend.dll»)
>>> import Simple
>>> dir(Simple)
[‘Equals’, ‘GetEnumerator’, ‘GetHashCode’, ‘GetType’, ‘ToString’, ‘__new__’, ‘__repr__’]
>>> s = Simple(10)

>>> for i in s: print i

Simple
Simple
Simple
Simple
Simple
Simple
Simple
Simple
Simple
Simple

Notice that the dir() function now returned the GetEnumerator method.

Exit IronPython and return back to the Visual Basic code to add more functionality.

Task 3: Adding custom operator

Add the operator + method to the Simple class:

Public Class Simple
Implements IEnumerable
Private data As Integer

Public Sub New(ByVal data As Integer)
Me.data = data
End Sub

Overrides Function ToString() As String
Return String.Format(«Simple «, data)
End Function

Function GetEnumerator() As IEnumerator _
Implements IEnumerable.GetEnumerator
Return New SimpleEnum(data)
End Function

Shared Operator +(ByVal a As Simple, ByVal b As Simple) As Simple
Return New Simple(a.data + b.data)
End Operator

Compile the code (vbx), launch IronPython Console (ip) and test the code:

Notice that in the output of dir() call you will now get additional methods __add__ and __radd__, Python’s notion of custom operator implementation:

>>> import clr
>>> clr.AddReferenceToFile(«vbextend.dll»)
>>> import Simple
>>> dir(Simple)
[‘Equals’, ‘GetEnumerator’, ‘GetHashCode’, ‘GetType’, ‘ToString’, ‘__add__’, ‘__new__’, ‘__radd__’, ‘__repr__’]
>>> a = Simple(10)
>>> b = Simple(20)

Task 4: Adding delegate

Add the definition of the delegate to the top of the Visual Basic source file:

Imports System
Imports System.Collections

Public Delegate Function Transformer(ByVal input As Integer) As Integer

Add «Transform» method to the Simple class that takes the delegate as a parameter and invokes the delegate:

Public Class Simple
Implements IEnumerable
Private data As Integer

Public Sub New(ByVal data As Integer)
Me.data = data
End Sub

Overrides Function ToString() As String
Return String.Format(«Simple «, data)
End Function

Function GetEnumerator() As IEnumerator _
Implements IEnumerable.GetEnumerator
Return New SimpleEnum(data)
End Function

Function Transform(ByVal t As Transformer) As Integer
Return t(data)
End Function

Shared Operator +(ByVal a As Simple, ByVal b As Simple) As Simple
Return New Simple(a.data + b.data)
End Operator

Return back to the SDK command prompt, compile the code (vbx), launch IronPython Console (ip) and test the code:

def X(i):
return i + 100

The function X is getting passed as the delegate to the Simple’s Transform method. You will get following output:

>>> import clr
>>> clr.AddReferenceToFile(«vbextend.dll»)
>>> import Simple
>>> a = Simple(10)
>>> def X(i):

. return i + 100
.
>>> a.Transform(X)

The code to experiment with debugging of Python and C# or Visual Basic code, use Python scripts debugcsx.py and debugvbx.py respectively.

In this tutorial you performed the following exercises.

In this tutorial, you implemented a simple class to be used from IronPython. You added the ability for IronPython to enumerate the class, added an operator to it and support for delegate. The implementation was in either C# or Visual Basic, or both.

Tutorial 6: Embedding IronPython

Estimated time to complete this tutorial: 25 minutes

Exercise 1: IronPython as an expression evaluator

In this exercise, you will implement simple C# application that will embed IronPython and use it to evaluate expressions.

Task 1: IronPython as an expression evaluator

Open the «SDK Command Prompt» or «Visual Studio 2005 Command Prompt» from the start menu.

Open the «eval.cs» file in notepad. The file is initially empty

Insert the using statements at the beginning of the file. The PythonEngine, a class that provides the functionality we will leverage in this exercise, is located in the IronPython.Hosting namespace:

using System;
using IronPython.Hosting;

Implement the simple evaluator. The evaluator will create instance of PythonEngine class and call the Evaluate method, passing the command line argument as the expression string:

public class Eval <
public static void Main(string[] args) <
PythonEngine pe = new PythonEngine();
Console.WriteLine(pe.Evaluate(args[0]));
>
>

Save the changes and return to the SDK Command Prompt. Build the eval.cs using the provided batch file «cseval.bat». The batch script also copies the IronPython binaries to the current directory (they are not installed in Global Assembly Cache) so that the runtime can find them as the eval program executes:

Execute the eval program and pass simple expressions on the command line to be evaluated by the PythonEngine:

The complete code for the eval.cs is available in «Tutorial\Embed\eval.cs»

Exercise 2: IronPython as application’s scripting engine

The previous exercise demonstrated one-way interaction between IronPython and an application: the eval program used IronPython as a worker, and IronPython had no need to know anything about eval. From the IronPython engine’s perspective, there was no difference between commands sent from eval and those that someone sitting directly at the console might type.

However, IronPython can be embedded much more fully as a scripting engine for an application. The hosting application can make its own objects available to the IronPython engine, allowing users to write scripts in IronPython that manipulate these objects. Thus, the flexibility of IronPython can be used to automate complicated or frequently-performed tasks, and to provide an open-ended, extensible application.

In this exercise, you will:

Embed IronPython in an application as the scripting engine

Handle IronPython exceptions gracefully

Redirect the engine’s output streams

Task 1: Embedding IronPython in an application

Open the file HostingApp\MonthAtAGlance.cs. (This is the only file in the project containing application logic; everything else is used by Forms only.) At the top of the file, add references to IronPython.Hosting and IronPython.Compiler:

using IronPython.Hosting;
using IronPython.Compiler;

Add a PythonEngine instance as a private member of the class MonthAtAGlance:

// Application variables
private Dictionary dateEntries;
private System.DateTime lastDate;

private PythonEngine engine;

Add a method to initialize the PythonEngine, import the site module, and make the dateEntries variable available to it under the name dateentries.

void InitializePythonEngine()
<
engine = new PythonEngine();
engine.Import(«Site»);
engine.Globals[«dateentries»] = dateEntries;
>

Place a call to InitializePythonEngine() in the constructor for the App’s main form:

public MonthAtAGlance() <
InitializeComponent();
InitializeApp();

engine.Execute(«n = dateentries.Count»);
int nEntries = engine.EvaluateAs («n»);
label.Text = «There are now » + nEntries.ToString() + » entries in the dictionary.»;

Compile the application using the script makeha.bat. Run it inside the HostingApp directory, where it is found. The executable will be App.exe. The source file for this step is also available as HostingApp\MonthAtAGlance.1.cs

Task 2: Handle IronPython exceptions gracefully

If an application’s users have IronPython available as a scripting engine, it’s a given that syntax and logic errors will sometimes occur, raising IronPython exceptions. To show how this can degrade usability, let’s first see what happens when an application doesn’t have any way of handling exceptions from IronPython scripts gracefully:

At the end of InitializePythonEngine, we’ll add some Python code that generates an exception by attempting to reference an undefined variable, so:

Compile and run App.exe; again, the prepared source-file for this step is available, as MonthAtAGlance.2.1.cs. At once, you will see an exception dialog:

This dialogue appears because the default UncaughtExceptionHandler for the current AppDomain is invoked. By adding a new UncaughtExceptionHandler, you can perform various clean-up and reporting tasks before this dialogue appears. However, ideally you would like to handle the situation a little better than that. At the very least, your application can catch exceptions raised inside the PythonEngine and display the stack-trace to the user.

Wrap the call to Execute that you added in step 1 in a try/catch block:

> catch (Exception exc) <
MessageBox.Show(exc.ToString());
>

Compile and run to see the stack-trace displayed in the message-box; after dismissing it, you can interact with the application normally.

try <
engine.Execute(«print y»);

> catch (IronPython.Runtime.PythonNameError exc) <
MessageBox.Show(«IronPython engine complained: «+exc.Message);
> catch (Exception exc) <
MessageBox.Show(«Unexpected exception: «+exc.ToString()+»\nShutting down!»);
System.Environment.Exit(-1);
>

Compile and run again; note the different message-box that appears:

Task 3: Redirect the engine’s output streams

In Task 2, we directed the PythonEnginer to execute a print statement. Although this direction failed, because we asked it to print an undefined variable, nonetheless it raises an important question: if we execute a print, or any other statement which has console output as a side-effect, where does this output go when we host the engine in a GUI application? Let’s see what happens…

Modify the print statement added in Task 2 so that it executes without an error:

engine.Execute(«print ‘Hello, world!’«);

Now compile and run the program again. Look at the command window you launched the program from. You’ll see ‘Hello world!’ printed there. By default, the IronPython engine writes to the standard output; but it’s straightforward to redirect to a file so that all interactions with the engine are logged.

Modify InitializePythonEngine as follows:

engine = new PythonEngine();

System.IO.FileStream fs = new System.IO.FileStream(«scripting-log.txt»,
System.IO.FileMode.Create);
engine.SetStdout(fs);
engine.SetStderr(fs);

Now compile and run.Look in the home directory of the executable for scripting-log.txt; it should contain the text ‘Hello, world!’.

Now let’s use the IronPython engine to view information on the application objects. Add the following lines to the empty body of defaultEvtHandler:

engine.Execute(«print ‘———‘»);
engine.Execute(«for i in dateentries.Keys: print ‘Day %s: %s’ % (i, dateentries[i])»);

Now try compiling and running. Add a few entries to the calendar. You’ll see that, after you shut down, scripting-log.txt contains a text list of your calendar entries. (Any standard error output will be directed there as well.) Actually, it contains a complete record of the updates you have made to the calendar, since this Python code will be invoked whenever a date’s entry is altered.

In this tutorial you performed the following exercises.

Estimated time to complete this tutorial: 5 minutes

The objective of this tutorial is to set up Visual Studio for some basic tool support for debugging.

Exercise 1: Setting up Visual Studio for IronPython Debugging

Task 1: Setting up Visual Studio for IronPython Debugging

Open Visual Studio and close any solution or projects you might have open.

In the properties dialog, you will fill in two fields, the Command Arguments and Working Directory. For the Command Arguments, enter «first.py». For the Working Directory, enter the path to the Tutorial directory (c:\IronPython\Tutorial\ is where we assume you have it). Click Apply and OK to confirm your changes.

To test out our set up, use Ctrl+O to open a file. Browse to the «first.py» file in the Tutorial directory. Place the caret on the line that reads «def add(a, b):», and press F9 to set a breakpoint.

Press F5 to run the script, and you will hit the breakpoint. If you Press F10, you will step through the file, but all it does is load the definitions and set some variables before terminating.

In this tutorial you performed the following exercises.

In this tutorial you set up Visual Studio to work on Python scripts in a directory and debug them.

Источник

Операционные системы и программное обеспечение