PageRenderTime 73ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/IronPython_2_0/Tutorial/Tutorial.htm

#
HTML | 2996 lines | 2969 code | 26 blank | 1 comment | 0 complexity | 1623e1b5d96dc0645c03a305c88dde4e MD5 | raw file
Possible License(s): GPL-2.0, MPL-2.0-no-copyleft-exception, CPL-1.0, CC-BY-SA-3.0, BSD-3-Clause, ISC, AGPL-3.0, LGPL-2.1, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
  4. <title>IronPython Tutorial</title>
  5. <!--link rel="stylesheet" type="text/css" href="../Doc/IronPython.css"-->
  6. <style type="text/css">
  7. p.AntiVerify { display : none; }
  8. p.Code-Background { color : gray; }
  9. p.Code-Highlighted { color : gray; }
  10. p.CodeSample { color:blue; }
  11. p.DOSCommand { color:green; }
  12. p.ExceptionExample { color:green; }
  13. p.ExceptionOutput {display : none; }
  14. p.HiddenCode { display : none; }
  15. p.HiddenOutput {display : none; }
  16. p.LooseVerify { display : none; }
  17. p.Stepnonumbering { text-indent: 2em; }
  18. p.TypedExample { color : green; }
  19. p.UserCode { color:green; }
  20. </style>
  21. </head>
  22. <body lang="EN-US">
  23. <div class="Section1">
  24. <p class="Title1">IronPython Tutorial</p>
  25. <p class="Title2">A tour of Python on .NET</p>
  26. <p class="Title2">&nbsp;</p>
  27. <hr />
  28. <p class="CopyrightText">Information in this document is subject to change without
  29. notice. The example companies, organizations, products, people, and events depicted
  30. herein are fictitious. No association with any real company, organization, product,
  31. person or event is intended or should be inferred. Complying with all applicable
  32. copyright laws is the responsibility of the user. Without limiting the rights
  33. under copyright, no part of this document may be reproduced, stored in or introduced
  34. into a retrieval system, or transmitted in any form or by any means (electronic,
  35. mechanical, photocopying, recording, or otherwise), or for any purpose, without
  36. the express written permission of Microsoft Corporation.</p>
  37. <p class="CopyrightText">&nbsp;</p>
  38. <p class="CopyrightText">Microsoft may have patents, patent applications, trademarked,
  39. copyrights, or other intellectual property rights covering subject matter in
  40. this document. Except as expressly provided in any written license agreement
  41. from Microsoft, the furnishing of this document does not give you any license
  42. to these patents, trademarks, copyrights, or other intellectual property.</p>
  43. <p class="CopyrightText">&nbsp;</p>
  44. <p class="CopyrightText">Š Microsoft Corporation. All rights reserved.</p>
  45. <p class="CopyrightText">&nbsp;</p>
  46. <p class="CopyrightText">Microsoft, MS-DOS, MS, Windows, Windows NT, MSDN, Active
  47. Directory, BizTalk, SQL Server, SharePoint, Outlook, PowerPoint, FrontPage,
  48. Visual Basic, Visual C++, Visual J++, Visual InterDev, Visual SourceSafe, Visual
  49. C#, Visual J#,&nbsp; and Visual Studio are either registered trademarks or trademarks
  50. of Microsoft Corporation in the U.S.A. and/or other countries.</p>
  51. <p class="CopyrightText">&nbsp;</p>
  52. <p class="CopyrightText">Other product and company names herein may be the trademarks of their respective owners.</p>
  53. <hr />
  54. <p class="ContentsHeading">Contents</p>
  55. <p class="Toc1"><a href="#Intro">Introduction</a></p>
  56. <p class="Toc1">Tutorial 1: <a href="#T1">Basic IronPython</a></p>
  57. <p class="Toc2">Exercise 1: <a href="#T1.1">The IronPython interactive console</a></p>
  58. <p class="Toc3">Task 1: <a href="#T1.1.1">IronPython console</a></p>
  59. <p class="Toc3">Task 2: <a href="#T1.1.2">Built-in modules and interactive exploration</a></p>
  60. <p class="Toc3">Task 3: <a href="#T1.1.3">External Python modules</a></p>
  61. <p class="Toc2">Exercise 2: <a href="#T1.2">Using the standard .NET libraries from IronPython</a></p>
  62. <p class="Toc3">Task 1: <a href="#T1.2.1">Basic .NET library use</a></p>
  63. <p class="Toc3">Task 2: <a href="#T1.2.2">Working with .NET classes</a></p>
  64. <p class="Toc3">Task 3: <a href="#T1.2.3">Generics</a></p>
  65. <p class="Toc2">Exercise 3: <a href="#T1.3">Loading .NET libraries</a></p>
  66. <p class="Toc3">Task 1: <a href="#T1.3.1">Using System.Xml - AddReference</a></p>
  67. <p class="Toc3">Task 2: <a href="#T1.3.2">Mapack - Loading the .NET libraries - AddReferenceToFile</a></p>
  68. <p class="Toc2">Exercise 4: <a href="#T1.4">Obtaining and Using Python Standard Library</a></p>
  69. <p class="Toc3">Task 1: <a href="#T1.4.1">Configuring IronPython to use the Python standard library</a></p>
  70. <p class="Toc1">Tutorial 2: <a href="#T2">Advanced IronPython</a></p>
  71. <p class="Toc2">Exercise 1: <a href="#T2.1">Events and Delegates</a></p>
  72. <p class="Toc3">Task 1: <a href="#T2.1.1">File System Watcher</a></p>
  73. <p class="Toc3">Task 2: <a href="#T2.1.2">Improving the event handler</a></p>
  74. <p class="Toc3">Task 3: <a href="#T2.1.3">Defining events in Python</a></p>
  75. <p class="Toc2">Exercise 2: <a href="#T2.2">Windows Forms</a></p>
  76. <p class="Toc3">Task 1: <a href="#T2.2.1">Simple Windows Forms application</a></p>
  77. <p class="Toc2">Exercise 3: <a href="#T2.3">Windows Presentation Foundation (Avalon)</a></p>
  78. <p class="Toc3">Task 1: <a href="#T2.3.1">Simple Avalon Application</a></p>
  79. <p class="Toc3">Task 2: <a href="#T2.3.2">Avalon calculator</a></p>
  80. <p class="Toc1">Tutorial 3: <a href="#T3">IronPython and COM interoperability</a></p>
  81. <p class="Toc2">Exercise 1: <a href="#T3.1">Merlin the Wizard</a></p>
  82. <p class="Toc3">Task 1: <a href="#T3.1.1">Creating COM interop assemblies</a></p>
  83. <p class="Toc3">Task 2: <a href="#T3.1.2">Using COM objects from IronPython</a></p>
  84. <p class="Toc2">Exercise 2: <a href="#T3.2">Use Word for Spell Checking</a></p>
  85. <p class="Toc3">Task 1: <a href="#T3.2.1">Accessing Word and Checking
  86. Spelling</a></p>
  87. <p class="Toc3">Task 2: <a href="#T3.2.2">Use Windows Form Dialog to Correct
  88. Spelling</a></p>
  89. <p class="Toc1">Tutorial 4: <a href="#T4">Debugging IronPython program</a></p>
  90. <p class="Toc2">Exercise 1: <a href="#T4.1">Debugging IronPython programs</a></p>
  91. <p class="Toc3">Task 1: <a href="#T4.1.1">Debugging IronPython programs using Microsoft CLR Debugger</a></p>
  92. <p class="Toc1">Tutorial 5: <a href="#T5">Extending IronPython</a></p>
  93. <p class="Toc2">Exercise 1: <a href="#T5.1">Extending using C#</a></p>
  94. <p class="Toc3">Task 1: <a href="#T5.1.1">Implementing simple class - constructor and ToString</a></p>
  95. <p class="Toc3">Task 2: <a href="#T5.1.2">Making the object enumerable</a></p>
  96. <p class="Toc3">Task 3: <a href="#T5.1.3">Adding custom operator</a></p>
  97. <p class="Toc3">Task 4: <a href="#T5.1.4">Adding delegate</a></p>
  98. <p class="Toc2">Exercise 2: <a href="#T5.2">Extending using Visual Basic.NET</a></p>
  99. <p class="Toc3">Task 1: <a href="#T5.2.1">Implementing simple class - constructor and ToString</a></p>
  100. <p class="Toc3">Task 2: <a href="#T5.2.2">Making the object enumerable</a></p>
  101. <p class="Toc3">Task 3: <a href="#T5.2.3">Adding custom operator</a></p>
  102. <p class="Toc3">Task 4: <a href="#T5.2.4">Adding delegate</a></p>
  103. <p class="Toc1">Tutorial 6: <a href="#T7">Using Visual Studio to Edit .py
  104. Files and Debug Them</a></p>
  105. <p class="Toc2">Exercise 1: <a href="#T6.1">Setting up Visual Studio for
  106. IronPython Debugging</a></p>
  107. <p class="Toc3">Task 1: <a href="#T6.1.1">Setting up Visual Studio for
  108. IronPython Debugging</a></p>
  109. </div>
  110. <div class="Section2">
  111. <h1><a name="Intro">Introduction</a></h1>
  112. <p class="Normal">IronPython is the .NET implementation of the Python programming language
  113. (<a href="http://www.python.org">www.python.org</a>).&nbsp; It's a dynamically typed language with support
  114. for many programming paradigms such as object-oriented programming, and also allows
  115. you to seamlessly use .NET code.</p>
  116. <p class="Normal">&nbsp;</p>
  117. <p class="Normal">The goal of this tutorial is to quickly
  118. familiarize you with the IronPython console, and to show you how to make use of the extensive .NET libraries available.&nbsp;
  119. This tutorial also shows you how to get started in more specialized areas
  120. such as interoperating with COM, extending IronPython with C#, and embedding
  121. IronPython.&nbsp; This tutorial is NOT meant to be an introduction to Python
  122. itself, and if you're looking for that, we recommend you start with the
  123. tutorial at <a href="http://docs.python.org/tut/tut.html">www.python.org</a>
  124. or the often recommended book <i>Learning Python</i> by Mark Lutz and David
  125. Ascher. For an introduction to both the Python language as well as the unique
  126. capabilities of IronPython, we recommend <i>IronPython in Action</i> by
  127. Michael Foord<br><br>
  128. Some of the exercises in this tutorial require prerequisites.&nbsp; The prerequisites to successfully complete the whole tutorial are:</p>
  129. <ul type="disc">
  130. <li class="Normal">Microsoft .NET Framework Version 3.5
  131. <ul type="circle">
  132. <li class="Normal">Required to run IronPython on Windows Vista.</li>
  133. <li class="Normal">Microsoft .NET Framework Version 3.0 SP1 or higher needed for Windows operating systems released prior to Windows Vista</li>
  134. <li class="Normal">Download from
  135. <a href="http://www.microsoft.com/downloads/details.aspx?familyid=333325FD-AE52-4E35-B531-508D977D32A6&displaylang=en ">
  136. here</a>.</li>
  137. </ul>
  138. </li>
  139. </ul>
  140. <ul>
  141. <li class="Normal">Visual Studio 2005 or 2008<ul type="circle">
  142. <li class="Normal">Required for &quot;Setting up Visual Studio for IronPython Debugging&quot; tutorials.</li>
  143. </ul>
  144. </li>
  145. </ul>
  146. <ul>
  147. <li class="Normal">Microsoft Word<ul type="circle">
  148. <li class="Normal">Required for &quot;Use Word for Spell Checking&quot; and &quot;Merlin the Wizard&quot; tutorials.</li>
  149. </ul>
  150. </li>
  151. </ul>
  152. <ul>
  153. <li class="Normal"><a name="Mapack">Mapack</a> (example assembly found
  154. on the internet)<ul>
  155. <li>Required for the &quot;Basic IronPython&quot; tutorial, exercise &quot;Loading .NET
  156. Libraries&quot;.</li>
  157. <li>Download Mapack from
  158. <a href="http://www.lutzroeder.com/dotnet/">here</a> (direct link
  159. to the Mapack.zip download is
  160. <a href="http://www.lutzroeder.com/dotnet/Download.aspx?File=Mapack">
  161. here</a>).</li>
  162. <li>Extract Mapack.dll from the zip file directly into the Tutorial
  163. directory.</li>
  164. </ul>
  165. </li>
  166. </ul>
  167. <p class="Normal">&nbsp;</p>
  168. <p class="Body">Visual Studio 2005 or 2008 can be used in place of the Microsoft .NET
  169. Framework Version 2.0 and the .NET Framework 2.0 Software Development Kit (SDK).
  170. Since Visual Studio installs both the .NET Framework 2.0 and the .NET Framework
  171. SDK, there is no need to install those explicitly if you have Visual Studio
  172. 2005 available. Visual Studio 2008 also installs .NET Framework 3.5. </p>
  173. <p class="Body">This tutorial also assumes that you will launch the
  174. IronPython console (c:\ironpython\ipy.exe) from the tutorial directory.&nbsp;
  175. When the tutorials direct you to start the IronPython console from the tutorial directory,
  176. you should change to the tutorial directory (&gt;cd c:\ironpython\tutorial)
  177. and launch the console with the tutorial as your working directory (&gt;..\ipy.exe). If you
  178. install IronPython via the MSI installer, it will install to c:\Program Files\IronPython 2.0
  179. by default. In this scenario, you can still run the tutorial, but several tutorials require
  180. write access to the tutorial directory, which will require administrator access if IronPython
  181. is installed under Program Files.</p>
  182. <p class="Body">&nbsp;</p>
  183. <h1><a name="T1">Tutorial 1: Basic IronPython</a></h1>
  184. <p class="Body">The emphasis of this tutorial is on the basic interaction with
  185. the IronPython interpreter and using the interactive environment to explore
  186. the .NET libraries.</p>
  187. <p class="Body">Estimated time to complete this tutorial: <b>30 minutes</b></p>
  188. <p class="Body">The objective of this tutorial is to launch the IronPython interpreter,
  189. explore the environment of the interactive console and use IronPython to interact
  190. with .NET libraries.</p>
  191. <p class="Body">The exercises in this tutorial are:</p>
  192. <ul>
  193. <li>
  194. <p class="ExerciseList"><a href="#T1.1">The IronPython interactive console</a></p>
  195. </li>
  196. <li>
  197. <p class="ExerciseList"><a href="#T1.2">Using the standard .NET libraries
  198. from IronPython</a></p>
  199. </li>
  200. <li>
  201. <p class="ExerciseList"><a href="#T1.3">Loading additional .NET libraries</a></p>
  202. </li>
  203. </ul>
  204. <h2><a name="T1.1">Exercise 1: The IronPython interactive console</a></h2>
  205. <p class="Body">In this exercise, you will start the IronPython interactive
  206. interpreter and perform simple tasks to become acquainted with the IronPython
  207. environment.</p>
  208. <p class="Normal">If you are familiar with using the Python interactive console,
  209. the import statement and exploring the Python interactive environment using
  210. dir() function and __doc__ attribute, you can <a href="#T1.2">skip this exercise</a>.</p>
  211. <h3><a name="T1.1.1">Task 1: IronPython console</a></h3>
  212. <ol>
  213. <li>
  214. <p class="Step">Start the IronPython console from the tutorial directory
  215. by changing to the tutorial directory (&gt;cd c:\ironpython\tutorial) and
  216. launching the console c:\ironpython\ipy.exe executable (&gt;..\ipy.exe).&nbsp;
  217. This is how you should always launch the console for the tutorials, but
  218. from now on, we'll just direct you to &quot;start the IronPython console from
  219. the tutorial directory&quot;.</p>
  220. </li>
  221. </ol>
  222. <p class="Code-Highlighted">IronPython 2.0 (2.0.0.0) on .NET 2.0.50727.3053<br />
  223. Copyright (c) Microsoft Corporation. All rights reserved.</p>
  224. <p class="Code-Highlighted">&gt;&gt;&gt; _</p>
  225. <ol start="2">
  226. <li>
  227. <p class="Step">Execute simple statements listed below.&nbsp; After each statement IronPython prints the result, if any, and awaits more input.&nbsp;
  228. (The input line starting with &quot;for&quot; requires an extra return or enter
  229. key press because the interpreter prompts for more statements in the
  230. 'for' loop.)</p>
  231. </li>
  232. </ol>
  233. <p class="TypedExample">2+2</p>
  234. <p class="TypedExample">print &quot;Hello World!&quot;</p>
  235. <p class="TypedExample">for i in range(3): print i</p>
  236. <p class="TypedExample">x = 10</p>
  237. <p class="TypedExample">print x</p>
  238. <p class="Stepnonumbering">&nbsp;</p>
  239. <p class="Stepnonumbering">After this step, the console window will contain
  240. the following text:</p>
  241. <p class="Code-Highlighted">&gt;&gt;&gt; 2+2</p>
  242. <p class="Code-Background">4</p>
  243. <p class="Code-Highlighted">&gt;&gt;&gt; print &quot;Hello World!&quot;</p>
  244. <p class="Code-Background">Hello World!</p>
  245. <p class="Code-Highlighted">&gt;&gt;&gt; for i in range(3): print i</p>
  246. <p class="Code-Highlighted">...</p>
  247. <p class="Code-Background">0<br />
  248. 1<br />
  249. 2</p>
  250. <p class="Code-Highlighted">&gt;&gt;&gt; x = 10<br />
  251. &gt;&gt;&gt; print x</p>
  252. <p class="Code-Background"></p>
  253. <p class="Code-Background">10</p>
  254. <p class="Code-Highlighted">&gt;&gt;&gt; </p>
  255. <ol start="3">
  256. <li>
  257. <p class="Step">IronPython console supports multi-line statements, often
  258. used by function definitions.&nbsp; IronPython prompts for additional lines of
  259. multi-line statements using:</p>
  260. </li>
  261. </ol>
  262. <p class="Code-Highlighted">...</p>
  263. <p class="Code-Background"></p>
  264. <p class="Stepnonumbering">Unlike C# or Java, where blocks of code are grouped by curly brackets "{...}",
  265. blocks of code in Python are grouped based on their level of indentation.&nbsp; Every new block of code
  266. must be indented one more level than the previous block of code.&nbsp; Blocks of code are used for
  267. function and class definitions as well as 'if' statements and loops. </p>
  268. <p class="Stepnonumbering">Define the &quot;add&quot; function (note, you
  269. need to enter spaces before the 'return' statement):</p>
  270. <p class="TypedExample">def add(a, b):<br>
  271. &nbsp;&nbsp;&nbsp; return a + b</p>
  272. <p class="Stepnonumbering">To complete the function definition, press Enter
  273. once more at this point</p>
  274. <p class="TypedExample">add(3, 2)</p>
  275. <p class="TypedExample">add(&quot;Iron&quot;, &quot;Python&quot;)</p>
  276. <p class="Stepnonumbering">After this step, the console contents will be:</p>
  277. <p class="Code-Highlighted">&gt;&gt;&gt; def add(a, b):<br />
  278. ...&nbsp;&nbsp;&nbsp;&nbsp; return a + b<br />
  279. ...<br />
  280. &gt;&gt;&gt; add(3, 2)</p>
  281. <p class="Code-Background">5</p>
  282. <p class="Code-Highlighted">&gt;&gt;&gt; add(&quot;Iron&quot;, &quot;Python&quot;)</p>
  283. <p class="Code-Background">&#39;IronPython&#39;</p>
  284. <p class="Code-Highlighted">&gt;&gt;&gt; </p>
  285. <p class="Step">&nbsp;</p>
  286. <ol start="4">
  287. <li>
  288. <p class="Step">To exit the IronPython interactive console, type Ctrl+Z and Enter (alternatively,
  289. press F6 followed by Enter).</p>
  290. </li>
  291. </ol>
  292. <p class="TypedExample">^Z</p>
  293. <h3><a name="T1.1.2">Task 2: Built-in modules and interactive exploration</a></h3>
  294. <ol>
  295. <li>
  296. <p class="Step">Start the IronPython console from the tutorial directory
  297. (see <a href="#Intro">Introduction</a> for details).</p>
  298. </li>
  299. <li>
  300. <p class="Step">Using the built-in dir() function, list the contents of
  301. the IronPython environment:</p>
  302. </li>
  303. </ol>
  304. <p class="TypedExample">dir()</p>
  305. <p class="Stepnonumbering">The output in the console window will be:</p>
  306. <p class="Code-Highlighted">&gt;&gt;&gt; dir()</p>
  307. <p class="Code-Background">['__builtins__', '__doc__', '__name__']<br />
  308. </p>
  309. <ol start="3">
  310. <li>
  311. <p class="Step">IronPython comes with several built-in modules, the most
  312. frequently used one being &quot;sys&quot;.&nbsp; Import &quot;sys&quot; module using the &quot;import&quot;
  313. statement:</p>
  314. </li>
  315. </ol>
  316. <p class="TypedExample">import sys</p>
  317. <ol start="4">
  318. <li>
  319. <p class="Step">The Python import statement is similar to the &quot;using&quot; statement
  320. of C# or &quot;Imports&quot; statement of Visual Basic. The important difference is
  321. that the C# and VB statements bring the names from the imported namespace
  322. into the global namespace to be accessed directly. Python’s import doesn’t
  323. do that. To access the names or attributes in an imported module, prefix
  324. the
  325. names with the module's name:</p>
  326. </li>
  327. </ol>
  328. <p class="UserExample">sys.version</p>
  329. <ol start="5">
  330. <li>
  331. <p class="Step">Use the dir() function to explore the environment:</p>
  332. </li>
  333. </ol>
  334. <p class="TypedExample">dir()</p>
  335. <p class="Stepnonumbering" style="margin-left: 0.5in">The environment (global namespace) has changed, now
  336. it contains the &quot;sys&quot; module:</p>
  337. <p class="Code-Highlighted">&gt;&gt;&gt; dir()</p>
  338. <p class="Code-Background">['__builtins__', '__doc__', '__name__', 'sys']</p>
  339. <ol start="6">
  340. <li>
  341. <p class="Step">Use the dir() function to explore the contents of the &quot;sys&quot;
  342. module:</p>
  343. </li>
  344. </ol>
  345. <p class="TypedExample">dir(sys)</p>
  346. <p class="HiddenOutput">['__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', 'ps2', 'setcheckinterval', 'setdefaultencoding', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions', 'winver']</p>
  347. <ol start="7">
  348. <li>
  349. <p class="Step">Print the values of some of the &quot;sys&quot; module attributes:</p>
  350. </li>
  351. </ol>
  352. <p class="TypedExample">sys.path</p>
  353. <p class="LooseVerify">['.', '%MERLIN_ROOT%\\Test\\IronPythonTutorial', '%MERLIN_ROOT%\\Test', '%MERLIN_ROOT%\\Languages\\IronPython\\Tutorial', '%MERLIN_ROOT%\\Languages\\IronPython\\Tests', '%MERLIN_ROOT%\\Bin\\Debug\\Lib']</p>
  354. <p class="TypedExample">sys.executable</p>
  355. <p class="LooseVerify">'%MERLIN_ROOT%\\Bin\\Debug\\ipy.exe'</p>
  356. <h3><a name="T1.1.3">Task 3: External Python modules</a></h3>
  357. <p class="Normal">This task uses the module &quot;first.py&quot; located in the Tutorial
  358. folder.</p>
  359. <ol>
  360. <li>
  361. <p class="Step">Import the &quot;first.py&quot; module located in the Tutorial
  362. (because you launched ipy.exe from the Tutorial directory, &quot;first&quot; will
  363. be found on your sys.path):</p>
  364. </li>
  365. </ol>
  366. <p class="TypedExample">import first</p>
  367. <p class="Code-Background"></p>
  368. <ol start="2">
  369. <li>
  370. <p class="Step">Explore the module &quot;first&quot; using dir() function:</p>
  371. </li>
  372. </ol>
  373. <p class="TypedExample">dir(first)</p>
  374. <p class="Code-Highlighted">&gt;&gt;&gt; dir(first)</p>
  375. <p class="Code-Background">['__builtins__', '__file__', '__name__', 'add', 'factorial', 'hi']</p>
  376. <ol start="3">
  377. <li>
  378. <p class="Step">Print the documentation for the &quot;add&quot; and &quot;factorial&quot; functions,
  379. using __doc__ attribute:</p>
  380. </li>
  381. </ol>
  382. <p class="TypedExample">first.add.__doc__</p>
  383. <p class="TypedExample">first.factorial.__doc__</p>
  384. <p class="Stepnonumbering">&nbsp;</p>
  385. <p class="Stepnonumbering">The __doc__ attribute will be later used also for
  386. exploring .NET methods and their parameter types.</p>
  387. <p class="Code-Highlighted">&gt;&gt;&gt; first.add.__doc__</p>
  388. <p class="Code-Background">&#39;add(a, b) -&gt; returns a + b&#39;</p>
  389. <p class="Code-Highlighted">&gt;&gt;&gt; first.factorial.__doc__</p>
  390. <p class="Code-Background">&#39;factorial(n) -&gt; returns factorial of n&#39;</p>
  391. <ol start="4">
  392. <li>
  393. <p class="Step">Call the methods in the &quot;first&quot; module and print the contents
  394. of the &quot;hi&quot; attribute</p>
  395. </li>
  396. </ol>
  397. <p class="TypedExample">first.add(1,2)</p>
  398. <p class="TypedExample">first.factorial(5)</p>
  399. <p class="TypedExample">first.hi</p>
  400. <p class="Stepnonumbering">The expected output is:</p>
  401. <p class="Code-Highlighted">&gt;&gt;&gt; first.add(1,2)</p>
  402. <p class="Code-Background">3</p>
  403. <p class="Code-Highlighted">&gt;&gt;&gt; first.factorial(5)</p>
  404. <p class="Code-Background">120</p>
  405. <p class="Code-Highlighted">&gt;&gt;&gt; first.hi</p>
  406. <p class="Code-Background">&#39;Hello from IronPython!&#39;</p>
  407. <ol start="5">
  408. <li>
  409. <p class="Step">Exit the IronPython Interactive console (Ctrl+Z or F6 followed
  410. by Enter)</p>
  411. </li>
  412. </ol>
  413. <h2><a name="T1.2">Exercise 2: Using the standard .NET libraries from IronPython</a></h2>
  414. <p class="Body">The power of IronPython lies within the ability to seamlessly
  415. access the wealth of .NET libraries. This exercise will demonstrate how the
  416. .NET libraries can be used from IronPython.</p>
  417. <p class="Body">In this exercise, you will use the standard .NET libraries from
  418. IronPython. </p>
  419. <h3><a name="T1.2.1">Task 1: Basic .NET library use</a></h3>
  420. <ol>
  421. <li>
  422. <p class="Step">Start the IronPython console from the tutorial directory
  423. (see <a href="#Intro">Introduction</a> for details).</p>
  424. </li>
  425. <li>
  426. <p class="Step">Using the &quot;import&quot; statement, import the .NET System namespace:</p>
  427. </li>
  428. </ol>
  429. <p class="TypedExample">import System</p>
  430. <p class="Code-Background"></p>
  431. <ol start="3">
  432. <li>
  433. <p class="Step">Explore the System.Environment class and access some of
  434. its properties:</p>
  435. </li>
  436. </ol>
  437. <p class="TypedExample">dir(System.Environment)</p>
  438. <p class="UserCode">System.Environment.OSVersion</p>
  439. <p class="TypedExample">System.Environment.CommandLine</p>
  440. <p class="Stepnonumbering">The expected output of these commands is as follows
  441. (with some ellipsis for convenience):</p>
  442. <p class="Code-Highlighted">&gt;&gt;&gt; dir(System.Environment)</p>
  443. <p class="HiddenOutput">['CommandLine', 'CurrentDirectory', 'Equals', 'Exit', 'ExitCode', 'ExpandEnvironmentVariables', 'FailFast', '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', '__all__', '__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__']</p>
  444. <p class="Code-Highlighted">&gt;&gt;&gt; System.Environment.OSVersion</p>
  445. <p class="Code-Highlighted">&lt;System.OperatingSystem object at 0x000000000000002B [Microsoft Windows NT 6.0.6000.0]</p>
  446. <p class="Code-Highlighted">&gt;&gt;&gt; System.Environment.CommandLine</p>
  447. <p class="Code-Highlighted">&#39;C:\\IronPython\\ipy.exe&#39;
  448. <p class="LooseVerify">'"%MERLIN_ROOT%\\Bin\\Debug\\ipy.exe"'
  449. </p>
  450. <ol start="4">
  451. <li>
  452. <p class="Step">The import statement can be used also to import contents of
  453. a class or module into the global namespace.&nbsp; Use the &quot;from ... import ...&quot;
  454. flavor of the import statement to do that and explore the contents of the
  455. global namespace using dir().</p>
  456. </li>
  457. </ol>
  458. <p class="TypedExample">from System.Math import *</p>
  459. <p class="UserCode">dir()</p>
  460. <p class="HiddenCode">set1 = set(dir())
  461. set2 = set(dir(object))
  462. list(set1-set2)
  463. </p>
  464. <p class="HiddenOutput">
  465. ['Tan','Sqrt','Acos','Sin','Abs','Round','Pow','Floor','Exp','Log','Atan2','IEEERemainder','Atan','__builtins__','Asin','System','E','Cosh','__name__', 'Ceiling','DivRem','BigMul','Cos','Truncate','Min','Tanh','Log10','Sign','Max','Sinh','PI']</p>
  466. <p class="Stepnonumbering">Now you can call Math methods without having to specify
  467. the namespace and class name prefix:</p>
  468. <p class="TypedExample">Sin(PI/2)</p>
  469. <p class="Stepnonumbering">The expected output is:</p>
  470. <p class="Code-Highlighted">&gt;&gt;&gt; from System.Math import *</p>
  471. <p class="Code-Highlighted">&gt;&gt;&gt; dir()</p>
  472. <p class="Code-Highlighted">[&#39;Abs&#39;, &#39;Acos&#39;, &#39;Asin&#39;, &#39;Atan&#39;, &#39;Atan2&#39;, &#39;BigMul&#39;, &#39;Ceiling&#39;, &#39;Cos&#39;, &#39;Cosh&#39;, &#39;DivRem&#39;, &#39;E&#39;, &#39;Equals&#39;, &#39;Exp&#39;, &#39;Floor&#39;, &#39;GetHashCode&#39;, &#39;GetType&#39;, &#39;IEEERemainder&#39;, &#39;Log&#39;, &#39;Log10&#39;, &#39;Max&#39;, &#39;Min&#39;, &#39;PI&#39;, &#39;Pow&#39;, &#39;Round&#39;, &#39;Sign&#39;, &#39;Sin&#39;, &#39;Sinh&#39;, &#39;Sqrt&#39;, &#39;System&#39;, &#39;Tan&#39;, &#39;Tanh&#39;, &#39;ToString&#39;, &#39;Truncate&#39;, &#39;__builtins__&#39;, &#39;__doc__&#39;, &#39;__name__&#39;]</p>
  473. <p class="Code-Highlighted">&gt;&gt;&gt; Sin(PI/2)</p>
  474. <p class="Code-Background">1.0</p>
  475. <h3><a name="T1.2.2">Task 2: Working with .NET classes</a></h3>
  476. <ol>
  477. <li>
  478. <p class="Step">Import the contents of the &quot;System.Collections&quot; namespace
  479. into the global namespace:</p>
  480. </li>
  481. </ol>
  482. <p class="TypedExample">from System.Collections import *</p>
  483. <p class="Code-Background"></p>
  484. <ol start="2">
  485. <li>
  486. <p class="Step">Create instance of the Hashtable class and explore the instance
  487. using dir():</p>
  488. </li>
  489. </ol>
  490. <p class="TypedExample">h = Hashtable()</p>
  491. <p class="Code-Background"></p>
  492. <p class="UserCode">dir(h)</p>
  493. <p class="HiddenCode">set1 = set(dir(h))
  494. set2 = set(dir(object))
  495. list(set1-set2)</p>
  496. <p class="HiddenOutput">
  497. ['Clone','ContainsValue','SyncRoot','hcp','__setitem__','__contains__','KeyEquals','IsSynchronized','GetEnumerator','GetHash','Contains','Item','Values','ContainsKey','Remove','OnDeserialization','__iter__','Add','Synchronized','EqualityComparer','__len__','comparer','Keys','Clear','IsReadOnly','CopyTo','IsFixedSize','__add__','GetObjectData','Count','__getitem__']</p>
  498. <ol start="3">
  499. <li>
  500. <p class="Step">Insert&nbsp;a few elements into the hash table:</p>
  501. </li>
  502. </ol>
  503. <p class="TypedExample">h[&quot;a&quot;] = &quot;IronPython&quot;</p>
  504. <p class="Code-Background"></p>
  505. <p class="TypedExample">h[&quot;b&quot;] = &quot;Tutorial&quot;</p>
  506. <p class="Code-Background"></p>
  507. <p class="Stepnonumbering">&nbsp;</p>
  508. <p class="Stepnonumbering">IronPython supports the C# - style syntax for accessing
  509. the hash table elements.&nbsp; The same syntax applies to any index-able object (Arrays,
  510. Array lists etc):</p>
  511. <p class="TypedExample">h[&quot;a&quot;]</p>
  512. <p class="Stepnonumbering" style="page-break-after:avoid">&nbsp;</p>
  513. <p class="Stepnonumbering" style="page-break-after:avoid">The output of this
  514. step will be:</p>
  515. <p class="Code-Background" style="page-break-after:avoid">&gt;&gt;&gt; h[&quot;a&quot;] = &quot;IronPython&quot;<br />
  516. &gt;&gt;&gt; h[&quot;b&quot;] = &quot;Tutorial&quot;</p>
  517. <p class="Code-Highlighted" style="page-break-after:avoid">&gt;&gt;&gt; h[&quot;a&quot;]</p>
  518. <p class="Code-Background">&#39;IronPython&#39;</p>
  519. <ol start="4">
  520. <li>
  521. <p class="Step">Enumerate the contents of the hash table using the &quot;for
  522. ... in ...&quot; statement. The hash table elements are instances of &quot;DictionaryEntry&quot;
  523. class. Print the &quot;Key&quot; and &quot;Value&quot; properties of each entry:</p>
  524. </li>
  525. </ol>
  526. <p class="TypedExample">for e in h: print e.Key, &quot;:&quot;, e.Value</p>
  527. <p class="Stepnonumbering">&nbsp;</p>
  528. <p class="Stepnonumbering">The expected output in the console is (the input
  529. line starting with &quot;for&quot; requires an extra return or enter key press because
  530. the interpreter prompts for more statements in the 'for' loop.):</p>
  531. <p class="Code-Highlighted">&gt;&gt;&gt; for e in h: print e.Key, &quot;:&quot;, e.Value<br>
  532. ...</p>
  533. <p class="Code-Background">a : IronPython<br />
  534. b : Tutorial</p>
  535. <ol start="5">
  536. <li>
  537. <p class="Step">You can initialize the collection classes by passing in
  538. the Python built-in list or tuple data types as arguments.&nbsp; You can
  539. create a Python list by specifying the list of elements in square brackets: [1,2,3].&nbsp;
  540. You create tuples by specifying elements in the parentheses: (1,2,3).</p>
  541. </li>
  542. </ol>
  543. <p class="TypedExample">l = ArrayList([1,2,3])</p>
  544. <p class="Code-Background"></p>
  545. <p class="TypedExample">for i in l: print i</p>
  546. <p class="TypedExample">s = Stack((1,2,3))</p>
  547. <p class="TypedExample">while s.Count: s.Pop()</p>
  548. <p class="Stepnonumbering">&nbsp;</p>
  549. <p class="Stepnonumbering">The expected output is:</p>
  550. <p class="Code-Highlighted">&gt;&gt;&gt; l = ArrayList([1,2,3])<br />
  551. &gt;&gt;&gt; for i in l: print i<br>
  552. ...</p>
  553. <p class="Code-Background">1<br />
  554. 2<br />
  555. 3</p>
  556. <p class="Code-Background"></p>
  557. <p class="Code-Highlighted">&gt;&gt;&gt; s = Stack((1,2,3))<br />
  558. &gt;&gt;&gt; while s.Count: s.Pop()<br>...</p>
  559. <p class="Code-Background">3<br />
  560. 2<br />
  561. 1</p>
  562. <h3><a name="T1.2.3">Task 3: Generics</a></h3>
  563. <ol>
  564. <li>
  565. <p class="Step">Import the Generic collections from the System.Collections.Generic
  566. namespace:</p>
  567. </li>
  568. </ol>
  569. <p class="TypedExample">from System.Collections.Generic import *</p>
  570. <p class="Code-Background"></p>
  571. <ol start="2">
  572. <li>
  573. <p class="Step">To instantiate a generic class, the generic type arguments
  574. must be specified.&nbsp; IronPython uses the following syntax to specify the type
  575. arguments: generic_type[type_argument, ...].&nbsp; Create an instance of generic
  576. list of string:</p>
  577. </li>
  578. </ol>
  579. <p class="TypedExample">l = List[str]()</p>
  580. <p class="Code-Background"></p>
  581. <ol start="3">
  582. <li>
  583. <p class="Step">Add string values into the list. Since we created a list of
  584. string, adding strings is possible:</p>
  585. </li>
  586. </ol>
  587. <p class="TypedExample">l.Add(&quot;Hello&quot;)</p>
  588. <p class="Code-Background"></p>
  589. <p class="TypedExample">l.Add(&quot;Hi&quot;)</p>
  590. <p class="Code-Background"></p>
  591. <ol start="4">
  592. <li>
  593. <p class="Step">Try adding objects of types other than string:</p>
  594. </li>
  595. </ol>
  596. <p class="ExceptionExample">l.Add(3)</p>
  597. <p class="Code-Background"></p>
  598. <p class="ExceptionExample">l.Add(2.5)</p>
  599. <p class="Code-Background"></p>
  600. <p class="ExceptionExample">l.Add([1,2,3])</p>
  601. <p class="Code-Background"></p>
  602. <p class="Stepnonumbering">&nbsp;</p>
  603. <p class="Stepnonumbering">Obviously, adding non-strings will fail with type
  604. error:</p>
  605. <p class="Code-Highlighted">&gt;&gt;&gt; l.Add(3)</p>
  606. <p class="Code-Highlighted">Traceback (most recent call last):<br>
  607. File , line unknown, in Initialize##40
  608. <br>
  609. TypeError: expected str, got int
  610. <br></p>
  611. <ol start="5">
  612. <li>
  613. <p class="Step">Enumerate the generic collection:</p>
  614. </li>
  615. </ol>
  616. <p class="TypedExample">for i in l: print i</p>
  617. <p class="Stepnonumbering">The output will be:</p>
  618. <p class="Code-Highlighted">&gt;&gt;&gt; for i in l: print i<br>...</p>
  619. <p class="Code-Background">Hello<br />
  620. Hi</p>
  621. <p class="ExceptionOutput">TypeError: expected str, got int
  622. TypeError: expected str, got float
  623. TypeError: expected str, got list</p>
  624. <ol start="6">
  625. <li>
  626. <p class="Step">Exit the IronPython Interactive console (Ctrl+Z or F6 followed
  627. by Enter)</p>
  628. </li>
  629. </ol>
  630. <h2><a name="T1.3">Exercise 3: Loading .NET libraries</a></h2>
  631. <p class="Body">IronPython can directly import only some of the .NET libraries
  632. - the most commonly used ones.&nbsp; To use additional .NET libraries, they must be
  633. explicitly referenced.&nbsp; IronPython maintains a list of all referenced
  634. assemblies (see clr.References in Task 1).&nbsp; To add a reference to a .NET assembly, use the functions
  635. available in the built-in &quot;clr&quot; module:</p>
  636. <ul>
  637. <li>
  638. <p class="Body"><b>clr.AddReference</b> adds a reference to the .NET assembly
  639. either by passing the .NET assembly object directly, or specifying the file
  640. name or the assembly name (full or partial). This function is provided primarily
  641. for the interactive exploration. We recommend using the following functions
  642. in the code modules, since they provide more control over which assembly
  643. is being loaded.</p>
  644. </li>
  645. <li>
  646. <p class="Body"><b>clr.AddReferenceToFile</b> adds reference to the assembly
  647. specified by its file name. This function will load the assembly from the
  648. file regardless of the assembly version. As a result, it doesn&#39;t guarantee
  649. that the correct assembly version is being loaded. To guarantee that correct
  650. assembly version is being loaded, use clr.AddReferenceByName. Moreover,
  651. AddReferenceToFile requires that the assembly be located in a
  652. directory listed in sys.path.</p>
  653. </li>
  654. <li>
  655. <p class="Body"><b>clr.AddReferenceToFileAndPath</b> provides similar
  656. functionality to AddReferenceToFile. The difference is that it accepts
  657. absolute path and before loading the assembly, AddReferenceToFileAndPath
  658. adds the file path into sys.path.</p>
  659. </li>
  660. <li>
  661. <p class="Body"><b>clr.AddReferenceByName</b> adds reference to the assembly
  662. specified by its full assembly name, for example: &#39;System.Xml, Version=2.0.0.0,
  663. Culture=neutral, PublicKeyToken=b77a5c561934e089&#39;.</p>
  664. </li>
  665. <li>
  666. <p class="Body"><b>clr.AddReferenceByPartialName</b> adds reference to the
  667. assembly by specifying a partial assembly name. This function cannot guarantee
  668. that the correct version of the assembly is being loaded. Use clr.AddReferenceByName
  669. to add reference to specific version of the assembly.</p>
  670. </li>
  671. </ul>
  672. <h3><a name="T1.3.1">Task 1: Using System.Xml - AddReference</a></h3>
  673. <ol>
  674. <li>
  675. <p class="Step">Start the IronPython console from the tutorial directory
  676. (see <a href="#Intro">Introduction</a> for details).</p>
  677. </li>
  678. <li>
  679. <p class="Step">To import System.Xml, the reference to the assembly containing
  680. the Xml components must be first added to IronPython.&nbsp; Add reference to System.Xml
  681. using the following code&nbsp; (you can enter &quot;clr.References&quot; before
  682. and after the call to clr.AddReference to see it change if you want):</p>
  683. </li>
  684. </ol>
  685. <p class="TypedExample">import clr</p>
  686. <p class="Code-Background"></p>
  687. <p class="TypedExample">clr.AddReference(&quot;System.Xml&quot;)</p>
  688. <p class="Code-Background"></p>
  689. <p class="TypedExample">from System.Xml import *</p>
  690. <p class="Code-Background"></p>
  691. <p class="TypedExample">dir()</p>
  692. <p class="HiddenOutput">['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']</p>
  693. <ol start="3">
  694. <li>
  695. <p class="Step">Note that the clr.AddReference function accepts either System.Reflection.Assembly object or string
  696. as a parameter. The string parameter can
  697. be a full assembly name, a partial assembly name, or a file name. For more control
  698. over the assembly references, use the appropriate functions described
  699. above. </p>
  700. <p class="Step">For example, consider the following alternatives for the statement clr.AddReference(&quot;System.Xml&quot;) above:</p>
  701. </li>
  702. </ol>
  703. <p class="TypedExample">clr.AddReferenceByName(&#39;System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&#39;)</p>
  704. <p class="Code-Background"></p>
  705. <p class="TypedExample">clr.AddReferenceByPartialName(&quot;System.Xml&quot;)</p>
  706. <p class="Code-Background"></p>
  707. <ol start="4">
  708. <li>
  709. <p class="Step">Load the XML file &quot;load.xml&quot; into the XmlDocument. The
  710. xml file contains sample savegame data from the IronPython sample &quot;Puzzle&quot; .
  711. For direct viewing, the load.xml file is located in the Tutorial folder</p>
  712. </li>
  713. </ol>
  714. <p class="TypedExample">d = XmlDocument()</p>
  715. <p class="Code-Background"></p>
  716. <p class="TypedExample">d.Load(&quot;load.xml&quot;)</p>
  717. <p class="Code-Background"></p>
  718. <ol start="5">
  719. <li>
  720. <p class="Step">We can now query the document. Query for all the saved games using the query below:</p>
  721. </li>
  722. </ol>
  723. <p class="TypedExample">n = d.SelectNodes(&quot;//Puzzle/SavedGames/Game/@caption&quot;)</p>
  724. <p class="TypedExample">for e in n: print e.Value</p>
  725. <p class="Stepnonumbering">&nbsp;</p>
  726. <p class="Stepnonumbering">The output in the console window will be:</p>
  727. <p class="Code-Highlighted">&gt;&gt;&gt; n = d.SelectNodes(&quot;//Puzzle/SavedGames/Game/@caption&quot;)<br />
  728. &gt;&gt;&gt; for e in n: print e.Value<br>...</p>
  729. <p class="Code-Background">
  730. Seattle (default game)<br />
  731. New York<br />
  732. World<br />
  733. North America<br />
  734. </p>
  735. <ol start="6">
  736. <li>
  737. <p class="Step">(Optional) Import the &quot;xmlutil.py&quot; module located in the
  738. Tutorial directory and use the function provided in the module to walk the
  739. contents of the Xml document:</p>
  740. </li>
  741. </ol>
  742. <p class="TypedExample">import xmlutil</p>
  743. <p class="TypedExample">for e in xmlutil.Walk(d): print e.Name, e.Value</p>
  744. <p class="HiddenOutput">#document None
  745. #comment *************************************************************************
  746. *
  747. * Copyright (c) Microsoft Corporation.&nbsp;
  748. *
  749. * This source code is subject to terms and conditions of the Microsoft Public License. A&nbsp;
  750. * copy of the license can be found in the License.html file at the root of this distribution. If&nbsp;
  751. * you cannot locate the Microsoft Public License, please send an email to&nbsp;
  752. * ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound&nbsp;
  753. * by the terms of the Microsoft Public License.
  754. *
  755. * You must not remove this notice, or any other, from this software.
  756. *
  757. *
  758. * ***************************************************************************&nbsp;
  759. Puzzle None
  760. SavedGames None
  761. Game None
  762. caption Seattle (default game)
  763. type a
  764. y 714
  765. x 327
  766. level 11
  767. dimension 3
  768. Game None
  769. caption New York
  770. type r
  771. y 1538
  772. x 1205
  773. level 12
  774. dimension 3
  775. Game None
  776. caption World
  777. type h
  778. y 0
  779. x 0
  780. level 2
  781. dimension 4
  782. Game None
  783. caption North America
  784. type a
  785. x 2
  786. y 5
  787. level 4
  788. dimension 3
  789. TopLeftPreviewTile None
  790. x -3
  791. y -3
  792. dimension 3
  793. level 5
  794. Cache None
  795. allow true</p>
  796. <p class="Stepnonumbering">The Walk function is a generator (a Python function
  797. that contains a &quot;yield&quot; statement). As the Walk function executes, it returns
  798. (yields) the XML nodes one by one to the caller who iterates over the generator.
  799. The source for the Walk function is:</p>
  800. <p class="CodeSample">def Walk(xml):</br>
  801. &nbsp;&nbsp;&nbsp; yield xml</br><br>
  802. &nbsp;&nbsp;&nbsp; if hasattr(xml, &quot;Attributes&quot;):<br />
  803. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; attrs = xml.Attributes<br />
  804. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if attrs:<br />
  805. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for attr in attrs:</br>
  806. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  807. yield attr</br><br>
  808. &nbsp;&nbsp;&nbsp; for child in xml:<br />
  809. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for c in Walk(child):</br>
  810. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  811. yield c</p>
  812. <ol start="7">
  813. <li>
  814. <p class="Step">Exit the IronPython Interactive console (Ctrl+Z or F6 followed
  815. by Enter)</p>
  816. </li>
  817. </ol>
  818. <h3><a name="T1.3.2">Task 2: Mapack - Loading the .NET libraries - AddReferenceToFile</a></h3>
  819. <p class="Normal">This task requires the Mapack.dll library for linear algebra computations.&nbsp;
  820. The library is not part of the IronPython distribution. See <a href="#Mapack">prerequisites</a>
  821. for download details.</p>
  822. <ol>
  823. <li>
  824. <p class="Step">Start the IronPython console from the tutorial directory
  825. (see <a href="#Intro">Introduction</a> for details).</p>
  826. </li>
  827. <li>
  828. <p class="Step">Use the clr.AddReferenceToFile function to load the Matrix
  829. library &quot;Mapack.dll&quot;:</p>
  830. </li>
  831. </ol>
  832. <p class="TypedExample">import clr</p>
  833. <p class="Code-Background"></p>
  834. <p class="TypedExample">clr.AddReferenceToFile(&quot;Mapack.dll&quot;)</p>
  835. <p class="Code-Background"></p>
  836. <p class="TypedExample">from Mapack import *</p>
  837. <p class="Code-Background"></p>
  838. <p class="TypedExample">dir()</p>
  839. <p class="Stepnonumbering">The expected output will be:</p>
  840. <p class="Code-Highlighted">&gt;&gt;&gt; import clr<br />
  841. &gt;&gt;&gt; clr.AddReferenceToFile(&quot;Mapack.dll&quot;)<br />
  842. &gt;&gt;&gt; from Mapack import *<br />
  843. &gt;&gt;&gt; dir()</p>
  844. <p class="Code-Background">['CholeskyDecomposition', 'EigenvalueDecomposition', 'LuDecomposition', 'Matrix', 'QrDecomposition', 'SingularValueDecomposition', '__builtins__', '__doc__', '__name__', 'clr']</p>
  845. <ol start="3">
  846. <li>
  847. <p class="Step">Create instance of Matrix class:</p>
  848. </li>
  849. </ol>
  850. <p class="ExceptionExample">m = Matrix()</p>
  851. <p class="Code-Background"></p>
  852. <p class="Stepnonumbering">Oops, bad arguments for the constructor.&nbsp; In the next
  853. step you&#39;ll learn the way to discover the constructors available.</p>
  854. <p class="Code-Highlighted">Traceback (most recent call last):
  855. <br>
  856. File , line unknown, in Initialize##30
  857. <br>
  858. TypeError: Matrix() takes at least 1 argument (0 given)</p>
  859. <ol start="4">
  860. <li>
  861. <p class="Step">Using the __doc__ attribute, find out information about
  862. Matrix constructors:</p>
  863. </li>
  864. </ol>
  865. <p class="TypedExample">print Matrix.__new__.__doc__</p>
  866. <p class="Code-Highlighted">&gt;&gt;&gt; print Matrix.__new__.__doc__</p>
  867. <p class="Code-Background">__new__(cls, int rows, int columns)<br />
  868. __new__(cls, int rows, int columns, float value)<br />
  869. __new__(cls, Array[Array[float]] value)
  870. </p>
  871. <ol start="5">
  872. <li>
  873. <p class="Step">Create instances of the Matrix class using the correct constructors
  874. and set some matrix elements manually.&nbsp; IronPython supports custom indexing
  875. on .NET classes. </p>
  876. </li>
  877. </ol>
  878. <p class="TypedExample">m = Matrix(2, 2, 1.2)</p>
  879. <p class="Code-Background"></p>
  880. <p class="TypedExample">n = Matrix(2,1)</p>
  881. <p class="Code-Background"></p>
  882. <p class="TypedExample">n[0,0] = 4</p>
  883. <p class="Code-Background"></p>
  884. <p class="TypedExample">print m</p>
  885. <p class="TypedExample">print n</p>
  886. <p class="Code-Highlighted">&gt;&gt;&gt; m = Matrix(2, 2, 1.2)<br />
  887. &gt;&gt;&gt; n = Matrix(2,1)<br />
  888. &gt;&gt;&gt; n[0,0] = 4<br />
  889. &gt;&gt;&gt; print m</p>
  890. <p class="Code-Background">1.2 0 <br />
  891. 0 1.2&nbsp;
  892. </p>
  893. <p class="Code-Highlighted">&gt;&gt;&gt; print n</p>
  894. <p class="Code-Background">4 <br />
  895. 0&nbsp;
  896. </p>
  897. <ol start="6">
  898. <li>
  899. <p class="Step">(Optional) IronPython also supports overloaded operators.&nbsp; Matrix does overload operators +, - (binary and unary) and *.&nbsp; You can see
  900. Python representation of the operators (__add__, __mul__, __sub__, ...)
  901. using dir():</p>
  902. </li>
  903. </ol>
  904. <p class="UserCode">dir(m)</p>
  905. <p class="HiddenCode">set1 = set(dir(m))
  906. set2 = set(dir(object))
  907. list(set1-set2)</p>
  908. <p class="HiddenOutput">
  909. ['Submatrix','Symmetric','Clone','__sub__','Columns','Trace','__ne__','InfinityNorm','Rows','__setitem__','Multiply','__neg__','Diagonal','Random','Subtract','Item','Square','FrobeniusNorm','Solve','__rmul__','Negate','Add','Inverse','__radd__','__rsub__','__mul__','Determinant','__add__','__eq__','__getitem__','Norm1','Transpose']</p>
  910. <ol start="7">
  911. <li>
  912. <p class="Step">Make simple calculations with the matrices:</p>
  913. </li>
  914. </ol>
  915. <p class="TypedExample">m * n</p>
  916. <p class="TypedExample">n.Transpose() * m</p>
  917. <p class="TypedExample">m * 3</p>
  918. <p class="TypedExample">n + -n</p>
  919. <p class="Stepnonumbering">The expected output of this step is:</p>
  920. <p class="Code-Highlighted">&gt;&gt;&gt; m * n</p>
  921. <p class="LooseVerify">Mapack.Matrix</p>
  922. <p class="Code-Highlighted">&gt;&gt;&gt; n.Transpose() * m</p>
  923. <p class="LooseVerify">Mapack.Matrix</p>
  924. <p class="Code-Highlighted">&gt;&gt;&gt; m * 3</p>
  925. <p class="LooseVerify">Mapack.Matrix</p>
  926. <p class="Code-Highlighted">&gt;&gt;&gt; n + -n</p>
  927. <p class="LooseVerify">Mapack.Matrix</p>
  928. <p class="ExceptionOutput">TypeError: Matrix() takes at least 1 argument (0 given)</p>
  929. <ol start="8">
  930. <li>
  931. <p class="Step">Exit the IronPython Interactive console (Ctrl+Z or F6 followed
  932. by Enter)</p>
  933. </li>
  934. </ol>
  935. <h2><a name="T1.4">Exercise 4: Obtaining and Using Python Standard Library</a></h2>
  936. <p class="Body">In this exercise, you will obtain Python and point
  937. IronPython at the Python standard library. If you installed IronPython from the MSI installer,
  938. the Python standard library is installed by default and you can skip this exercise.</p>
  939. <h3><a name="T1.4.1">Task 1: Configuring IronPython to use the Python standard library</a></h3>
  940. <ol>
  941. <li>
  942. <p class="Step">Download the latest Python installer from
  943. <a href="http://www.python.org/download/">http://www.python.org/download/</a>
  944. and install Python.&nbsp; The rest of this exercise will assume you used
  945. defaults (and installed to c:\python25, for example).</p>
  946. </li>
  947. <li>
  948. <p class="Step">Create a file named &quot;site.py&quot; and place it into your
  949. IronPython &quot;Lib&quot; directory.&nbsp; There might be one there
  950. already, so you can just edit it.&nbsp; The &quot;site.py&quot; file is executed every time
  951. you run IronPython.&nbsp; To tell IronPython where the Python standard library
  952. is, you can add the &quot;lib&quot; directory of Python to IronPython's path.&nbsp; To
  953. do so, put the following code into IronPython's &quot;site.py&quot; file (replace
  954. c:\python25\lib with your actual path to the Python lib directory):</p>
  955. </li>
  956. </ol>
  957. <p class="TypedExample">import sys</p>
  958. <p class="TypedExample">sys.path.append(r&quot;c:\python25\lib&quot;)</p>
  959. <ol start="3">
  960. <li>
  961. <p class="Step">Start the IronPython console from the tutorial directory
  962. (see <a href="#Intro">Introduction</a> for details).</p>
  963. </li>
  964. <li>
  965. <p class="Step">Now you can use the Python standard library from
  966. IronPython, for example to get the current working directory (output
  967. uses assumed location of your IronPython installation):</p>
  968. </li>
  969. </ol>
  970. <p class="TypedExample">import os</p>
  971. <p class="Code-Background"></p>
  972. <p class="TypedExample">os.getcwd()</p>
  973. <p class="Code-Highlighted">'C:\\ironpython\\Tutorial'</p>
  974. <p class="LooseVerify">
  975. '%MERLIN_ROOT%\\Test\\IronPythonTutorial'</p>
  976. <p class="LabSummary">Tutorial Summary</p>
  977. <p class="Body">In this tutorial you performed the following exercises.</p>
  978. <ul>
  979. <li>
  980. <p class="Body"><a href="#T1.1">The IronPython interactive console</a></p>
  981. </li>
  982. <li>
  983. <p class="Body"><a href="#T1.2">Using the standard .NET libraries from IronPython</a></p>
  984. </li>
  985. <li>
  986. <p class="Body"><a href="#T1.3">Loading .NET libraries</a></p>
  987. </li>
  988. <li>
  989. <p class="Body"><a href="#T1.4">Obtaining and Using Python Standard
  990. Library</a></p>
  991. </li>
  992. </ul>
  993. <p class="Body">In this tutorial, you became acquainted with IronPython interactive
  994. console, including the dynamic exploratory way of development using the dir() function
  995. and __doc__ attribute to explore the en

Large files files are truncated, but you can click here to view the full file