IronPython Tutorial: Basics
Материал из AvbWiki
Содержание |
IronPython
The power of .NET Framework in Python.
- IronPython (Python for .NET) homepage: http://ironpython.codeplex.com/
IronPython Tutorial
The IronPython interactive console
- dir() function and __doc__ attribute
- ipy.exe
- First test (built-in module):
import sys sys.version dir() dir(sys) sys.path sys.executable
- Second test (external module):
import first dir(first) first.add(1,2)
Using the standard .NET libraries from IronPython
The biggest advantage of IronPython lies within the ability to seamlessly access the wealth of .NET libraries.
- Using .NET assemblies
import System # System - root .NET namespace dir(System) # Yes! This is .NET System! from System.Math import * # .NET System.Math dir() Sin(PI/2) # .NET System.Math.Sin()
- .NET Collections
from System.Collections import * h = Hashtable() # System.Collections.Hashtable dir(h) h["a"] = "IronPython" h["b"] = "Tutorial" h["c"] = "http://ironpython.codeplex.com/" for e in h: print e.Key, ":", e.Value l = ArrayList([1,2,3]) # System.Collections.ArrayList for i in l: print i s = Stack((1,2,3)) # System.Collections.Stack while s.Count: s.Pop()
- Generics
from System.Collections.Generic import * l = List[str]() l.Add("Hello") l.Add("Hi") # l.Add(3) - error for i in l: print i
Loading additional .NET libraries
- Built-it clr module adds functionality which allows interact .NET platform.
- clr.AddReference
- clr.AddReferenceToFile
- clr.AddReferenceToFileAndPath
- clr.AddReferenceByName
- clr.AddReferenceByPartialName
- Using System.Xml (loading .NET library)
import clr # AddReference - explicitly references .NET assembly # Accepts System.Reflection.Assembly object or string # (full assembly name, a partial assembly name, or a file name) clr.AddReference("System.Xml") from System.Xml import * dir() clr.References # Added references to .NET assemblies d = XmlDocument() d.Load("load.xml") n = d.SelectNodes("//Puzzle/SavedGames/Game/@caption") for e in n: print e.Value
Loading additional Python libraries
- Use standard Python library.
import sys sys.path.append(r"c:\program files\python25\lib") import os os.getcwd()

