当前位置:文档之家› IronPython Tutorial

IronPython Tutorial

IronPython Tutorial
IronPython Tutorial

A tour of Python on .NET

Information in this document is subject to change without notice. The example companies, organizations, products, people, and events depicted herein are fictitious. No association with any real company, organization, product, person or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarked, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

? Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, MS, Windows, Windows NT, MSDN, Active Directory, BizTalk, SQL Server, SharePoint, Outlook, PowerPoint, FrontPage, Visual Basic, Visual C++, Visual J++, Visual InterDev, Visual SourceSafe, Visual C#, Visual J#, and Visual

Task 3: Adding custom operator

Task 4: Adding delegate

Tutorial 6: Using Visual Studio to Edit .py Files and Debug Them

Exercise 1: Setting up Visual Studio for IronPython Debugging

Task 1: Setting up Visual Studio for IronPython Debugging Introduction

IronPython is the .NET implementation of the Python programming language (https://www.doczj.com/doc/b68719920.html,). It's a dynamically typed language with support for many programming paradigms such as object-oriented programming, and also allows you to seamlessly use .NET code.

The goal of this tutorial is to quickly familiarize you with the IronPython console, and to show you how to make use of the extensive .NET libraries available. This tutorial also shows you how to get started in more specialized areas such as interoperating with COM, extending IronPython with C#, and embedding IronPython. This tutorial is NOT meant to be an introduction to Python itself, and if you're looking for that, we recommend you start with the tutorial at https://www.doczj.com/doc/b68719920.html, or the often recommended book Learning Python by Mark Lutz and David Ascher.

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

o Microsoft .NET Framework Version 2.0 Redistributable Package (x86)

o Required to run IronPython.

o Download from here.

https://www.doczj.com/doc/b68719920.html, Framework 2.0 Software Development Kit (SDK) (x86)

o Required for the COM interoperability, extending and embedding tutorials.

o Microsoft WinFX Runtime Components (Avalon)

o Required for "Advanced IronPython" and "Embedding IronPython" tutorials.

o Download from here.

o Mapack (example assembly found on the internet)

o Required for the "Basic IronPython" tutorial, exercise "Loading .NET Libraries". o Download Mapack from here (direct link to the Mapack.zip download is here).

o Extract Mapack.dll from the zip file directly into the Tutorial directory.

Visual Studio 2005 can be used in place of the Microsoft .NET Framework Version 2.0 and the .NET Framework 2.0 Software Development Kit (SDK). Since Visual Studio 2005 installs both the .NET Framework 2.0 and the .NET Framework SDK, there is no need to install those explicitly if you have Visual Studio 2005 available. 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

The emphasis of this tutorial is on the basic interaction with the IronPython interpreter and using the interactive environment to explore the .NET libraries. Estimated time to complete this tutorial: 30 minutes

The objective of this tutorial is to launch the IronPython interpreter, explore the environment of the interactive console and use IronPython to interact with .NET libraries.

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

1.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". IronPython 1.0 on .NET 2.0.50727.42

Copyright (c) Microsoft Corporation. All rights reserved.

>>> _

2.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.)

2+2

print"Hello World!"

for i in range(3): print i

x = 10

print x

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

>>> 2+2

4

>>> print "Hello World!"

Hello World!

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

...

1

2

>>> x = 10

>>> print x

10

>>>

3.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

add(3, 2)

add("Iron", "Python")

After this step, the console contents will be:

>>> def add(a, b):

... return a + b

...

>>> add(3, 2)

5

>>> add("Iron", "Python")

'IronPython'

>>>

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

^Z

Task 2: Built-in modules and interactive exploration

1.Start the IronPython console from the tutorial directory (see Introduction

for details).

https://www.doczj.com/doc/b68719920.html,ing the built-in dir() function, list the contents of the IronPython

environment:

dir()

The output in the console window will be:

>>> dir()

['__builtins__', '__doc__', '__name__']

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

import sys

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

sys.version

https://www.doczj.com/doc/b68719920.html,e the dir() function to explore the environment:

dir()

The environment (global namespace) has changed, now it contains the "sys"

module:

>>> dir()

['__builtins__', '__doc__', '__name__', 'sys']

https://www.doczj.com/doc/b68719920.html,e the dir() function to explore the contents of the "sys" module:

dir(sys)

['PerformModuleReload', '__name__', '__stderr__', '__stdin__', '__stdout__',

'_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value',

'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval',

'getdefaultencoding', 'getfilesystemencoding', 'getrecursionlimit', 'hexversion',

'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',

'path_importer_cache', 'platform', 'prefix', 'ps1', 'setcheckinterval',

'setdefaultencoding', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',

'version', 'version_info', 'warnoptions', 'winver']

7.Print the values of some of the "sys" module attributes:

sys.path

['%MERLIN_ROOT%\\Test\\IronPythonTutorial', '%MERLIN_ROOT%\\Test',

'%MERLIN_ROOT%\\Languages\\IronPython\\Tutorial',

'%MERLIN_ROOT%\\Languages\\IronPython\\Tests',

'%MERLIN_ROOT%\\Bin\\Debug\\Lib']

sys.executable

'%MERLIN_ROOT%\\Bin\\Debug\\ipy.exe'

Task 3: External Python modules

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

1.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): import first

2.Explore the module "first" using dir() function:

dir(first)

>>> dir(first)

['__builtins__', '__file__', '__name__', 'add', 'factorial', 'hi']

3.Print the documentation for the "add" and "factorial" functions, using __doc__ attribute:

first.add.__doc__

first.factorial.__doc__

The __doc__ attribute will be later used also for exploring .NET methods and their parameter types.

>>> first.add.__doc__

'add(a, b) - returns a + b'

>>> f irst.factorial.__doc__

'factorial(n) - returns factorial of n'

4.Call the methods in the "first" module and print the contents of the "hi" attribute first.add(1,2)

first.factorial(5)

first.hi

The expected output is:

>>> first.add(1,2)

3

>>> first.factorial(5)

120

>>> first.hi

'Hello from IronPython!'

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

Exercise 2: Using the standard .NET libraries from IronPython

The power of IronPython lies within the ability to seamlessly access the wealth

of .NET libraries. This exercise will demonstrate how the .NET libraries can be used from IronPython.

In this exercise, you will use the standard .NET libraries from IronPython.

Task 1: Basic .NET library use

1.Start the IronPython console from the tutorial directory (see Introduction

for details).

https://www.doczj.com/doc/b68719920.html,ing the "import" statement, import the .NET System namespace: import System

3.Explore the System.Environment class and access some of its properties: dir(System.Environment)

System.Environment.OSVersion

https://www.doczj.com/doc/b68719920.html,mandLine

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

>>> dir(System.Environment)

['CommandLine', 'CurrentDirectory', 'Equals', 'Exit', 'ExitCode',

'ExpandEnvironmentVariables', 'FailFast', 'Finalize', 'GetCommandLineArgs',

'GetEnvironmentVariable', 'GetEnvironmentVariables', 'GetFolderPath',

'GetHashCode', 'GetLogicalDrives', 'GetType', 'HasShutdownStarted',

'MachineName', 'MemberwiseClone', 'NewLine', 'OSVersion', 'ProcessorCount',

'ReferenceEquals', 'SetEnvironmentVariable', 'SpecialFolder', 'StackTrace',

'SystemDirectory', 'TickCount', 'ToString', 'UserDomainName', 'UserInteractive',

'UserName', 'Version', 'WorkingSet', '__class__', '__delattr__', '__doc__',

'__getattribute__', '__hash__', '__init__', '__new__', '__reduce__',

'__reduce_ex__', '__repr__', '__setattr__', '__str__', 'get_CommandLine',

'get_CurrentDirectory', 'get_ExitCode', 'get_HasShutdownStarted',

'get_MachineName', 'get_NewLine', 'get_OSVersion', 'get_ProcessorCount',

'get_StackTrace', 'get_SystemDirectory', 'get_TickCount', 'get_UserDomainName', 'get_UserInteractive', 'get_UserName', 'get_Version', 'get_WorkingSet',

'set_CurrentDirectory', 'set_ExitCode']

>>> System.Environment.OSVersion

>>> https://www.doczj.com/doc/b68719920.html,mandLine

'C:\\IronPython\\ipy.exe'

'"%MERLIN_ROOT%\\Bin\\Debug\\ipy.exe"'

4.The import statement can be used also to import contents of a class or module into the global namespace. Use the "from ... import ..." flavor of the import statement to do that and explore the contents of the global namespace using dir(). from System.Math import *

dir()

set1 = set(dir()) set2 = set(dir(object)) list(set1-set2)

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

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

Sin(PI/2)

The expected output is:

>>> from System.Math import *

>>> dir()

['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__']

>>> Sin(PI/2)

1.0

Task 2: Working with .NET classes

1.Import the contents of the "System.Collections" namespace into the global

namespace:

from System.Collections import *

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

h = Hashtable()

dir(h)

set1 = set(dir(h)) set2 = set(dir(object)) list(set1-set2)

['get_Values', 'ContainsValue', 'Keys', 'get_SyncRoot', 'GetObjectData', 'Count',

'get_IsFixedSize', 'get_Keys', 'Contains', 'Add', '__getitem__', 'get_IsReadOnly', 'get_comparer', 'get_IsSynchronized', 'EqualityComparer', 'get_EqualityComparer', 'GetHash', 'IsFixedSize', 'KeyEquals', 'ContainsKey', 'CopyTo', 'get_Count', 'hcp', 'Clone', 'SyncRoot', '__setitem__', 'GetEnumerator', 'set_comparer', 'Remove',

'Synchronized', 'Clear', '__iter__', 'IsReadOnly', 'comparer', 'Values', 'get_Item', 'get_hcp', 'IsSynchronized', 'OnDeserialization', 'set_Item', 'set_hcp']

3.Insert a few elements into the hash table:

h["a"] = "IronPython"

h["b"] = "Tutorial"

IronPython supports the C# - style syntax for accessing the hash table elements. The same syntax applies to any index-able object (Arrays, Array lists etc):

h["a"]

The output of this step will be:

>>> h["a"] = "IronPython"

>>> h["b"] = "Tutorial"

>>> h["a"]

'IronPython'

4.Enumerate the contents of the hash table using the "for ... in ..." statement. The hash table elements are instances of "DictionaryEntry" class. Print the "Key" and "Value" properties of each entry:

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

5.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).

l = ArrayList([1,2,3])

for i in l: print i

s = Stack((1,2,3))

while s.Count: s.Pop()

The expected output is:

>>> l = ArrayList([1,2,3])

>>> for i in l: print i

...

1

2

3

>>> s = Stack((1,2,3))

>>> while s.Count: s.Pop()

...

3

2

1

Task 3: Generics

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

namespace:

from System.Collections.Generic import *

2.To instantiate a generic class, the generic type arguments must be

specified. IronPython uses the following syntax to specify the type

arguments: generic_type[type_argument, ...]. Create an instance of

generic list of string:

l = List[str]()

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

l.Add("Hello")

l.Add("Hi")

4.Try adding objects of types other than string:

l.Add(3)

l.Add(2.5)

l.Add([1,2,3])

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

>>> l.Add(3)

Traceback (most recent call last):

File , line unknown, in Initialize##40

TypeError: expected str, got int

5.Enumerate the generic collection:

for i in l: print i

The output will be:

>>> for i in l: print i

...

Hello

Hi

TypeError: expected str, got int TypeError: expected str, got float TypeError: expected str, got list

6.Exit the IronPython Interactive console (Ctrl+Z or F6 followed by Enter) Exercise 3: Loading .NET libraries

IronPython can directly import only some of the .NET libraries - the most commonly used ones. To use additional .NET libraries, they must be explicitly referenced. IronPython maintains a list of all referenced assemblies (see

clr.References in Task 1). To add a reference to a .NET assembly, use the functions available in the built-in "clr" module:

o clr.AddReference adds a reference to the .NET assembly either by passing the .NET assembly object directly, or specifying the file name or the assembly name (full or partial). This function is provided primarily for the interactive exploration. We recommend using the following functions in the code modules, since they provide more control over which assembly is being loaded.

o 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.

o 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.

o 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'.

o 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.

Task 1: Using System.Xml - AddReference

1.Start the IronPython console from the tutorial directory (see Introduction

for details).

2.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):

import clr

clr.AddReference("System.Xml")

from System.Xml import *

dir()

['ConformanceLevel', 'EntityHandling', 'Formatting', 'IHasXmlNode', 'IXmlLineInfo', 'IXmlNamespaceResolver', 'NameTable', 'NewLineHandling', 'ReadState', 'Schema', 'Serialization', 'ValidationType', 'WhitespaceHandling', 'WriteState', 'XPath',

'XmlAttribute', 'XmlAttributeCollection', 'XmlCDataSection', 'XmlCharacterData',

'XmlComment', 'XmlConvert', 'XmlDateTimeSerializationMode', 'XmlDeclaration', 'XmlDocument', 'XmlDocumentFragment', 'XmlDocumentType', 'XmlElement',

'XmlEntity', 'XmlEntityReference', 'XmlException', 'XmlImplementation',

'XmlLinkedNode', 'XmlNameTable', 'XmlNamedNodeMap', 'XmlNamespaceManager', 'XmlNamespaceScope', 'XmlNode', 'XmlNodeChangedAction',

'XmlNodeChangedEventArgs', 'XmlNodeChangedEventHandler', 'XmlNodeList',

'XmlNodeOrder', 'XmlNodeReader', 'XmlNodeType', 'XmlNotation',

'XmlOutputMethod', 'XmlParserContext', 'XmlProcessingInstruction',

'XmlQualifiedName', 'XmlReader', 'XmlReaderSettings', 'XmlResolver',

'XmlSecureResolver', 'XmlSignificantWhitespace', 'XmlSpace', 'XmlText',

'XmlTextReader', 'XmlTextWriter', 'XmlTokenizedType', 'XmlUrlResolver',

'XmlValidatingReader', 'XmlWhitespace', 'XmlWriter', 'XmlWriterSettings', 'Xsl',

'__builtins__', '__doc__', '__name__', 'clr']

3.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, Public KeyToken=b77a5c561934e089')

相关主题
文本预览
相关文档 最新文档