|
IronPython is a Python implementation on the .NET platform, including a complete compiler and run-time support execution engine, capable of existing .NET library seamlessly integrated together.
IronPython is already well integrated into the .NET framework, so the interaction Ironpython and C # will become very simple. Here's some simple examples to look at the interaction between IronPython and C #.
Environment settings
We must first of its profits, so before you start IronPython development, we first find a convenient development environment.
PTVS (Python tools for Visual Studio) is a free open source VisualStudio plugin support VisualStudio 2010/2012/2013, after installing the plug-in, we can develop IronPython directly through the VS.
IronPython calling C #
First, we look at a simple example of how to use C # in the IronPython.
Using standard .NET library
In .NET, there are many standard library in IronPython, you can use import to introduce the standard library to be used directly. Look at a simple example, we use the .NET String and DateTime
from System import DateTime, String
formatStr = String.Format ( "{0} {1}", "Hello World! The current date and time is", DateTime.Now)
print formatStr
print dir (String)
raw_input ( "press Enter to exit!")
Code output below, you can see the IronPython code can be output string formatted by the Format String method.
The introduction of .NET libraries
In .NET development, often to refer to some of the .NET libraries References, of course, in the IronPython project, you can reference and use .NET libraries.
For example, we now have a Calc calculation type, which has a method Add and Sub. With this type, it generated a CalcLib.dll.
namespace CalcLib
{
public class Calc
{
public int Add (int a, int b)
{
return a + b;
}
public int Sub (int a, int b)
{
return a - b;
}
}
}
Here's how to use this dll in IronPython project in IronPython, you can use the "clr" module to add .NET Quote:
import clr
clr.AddReference ( 'CalcLib')
# Clr.AddReferenceToFile ( 'CalcLib.dll')
from CalcLib import Calc
print dir (Calc)
calcObj = Calc ()
print "result of 3 + 4 is:", calcObj.Add (3,4)
print "result of 10 + 2 is:", calcObj.Sub (10,2)
raw_input ( "press Enter to exit!")
Code output as follows, when quoted CalcLib.dll, we can create Calc instance type, and use the C # method instance.
IronPython create WPF applications
In IronPython project to be associated with the introduction of WPF .NET library, so you can easily create a GUI application.
After installed PTVS, which has a "IronPython WPF Application" template, by this template, you can directly create WPF applications.
In the new project, VS will help us automatically referenced WPF associated libraries, and at the same time there will be a .py .xaml files.
Let's look at a simple example, a simple calculator IrpnPython implemented interface code as follows:
< Grid>
< Grid.RowDefinitions>
< RowDefinition> < / RowDefinition>
< RowDefinition> < / RowDefinition>
< RowDefinition> < / RowDefinition>
< RowDefinition> < / RowDefinition>
< RowDefinition> < / RowDefinition>
< RowDefinition> < / RowDefinition>
< /Grid.RowDefinitions>
< Grid.ColumnDefinitions>
< ColumnDefinition> < / ColumnDefinition>
< ColumnDefinition> < / ColumnDefinition>
< ColumnDefinition> < / ColumnDefinition>
< ColumnDefinition> < / ColumnDefinition>
< /Grid.ColumnDefinitions>
< TextBlock Name = "InputTb" Grid.Row = "0" Grid.ColumnSpan = "4" />
< TextBlock Name = "ResultTb" Grid.Row = "1" Grid.ColumnSpan = "3" />
< Button Content = "1" Grid.Row = "2" Grid.Column = "0" Click = "Input_Button_Click" />
< Button Content = "2" Grid.Row = "2" Grid.Column = "1" Click = "Input_Button_Click" />
< Button Content = "3" Grid.Row = "2" Grid.Column = "2" Click = "Input_Button_Click" />
< Button Content = "4" Grid.Row = "3" Grid.Column = "0" Click = "Input_Button_Click" />
< Button Content = "5" Grid.Row = "3" Grid.Column = "1" Click = "Input_Button_Click" />
< Button Content = "6" Grid.Row = "3" Grid.Column = "2" Click = "Input_Button_Click" />
< Button Content = "7" Grid.Row = "4" Grid.Column = "0" Click = "Input_Button_Click" />
< Button Content = "8" Grid.Row = "4" Grid.Column = "1" Click = "Input_Button_Click" />
< Button Content = "9" Grid.Row = "4" Grid.Column = "2" Click = "Input_Button_Click" />
< Button Content = "0" Grid.Row = "5" Grid.Column = "0" Click = "Input_Button_Click" />
< Button Content = "+" Grid.Row = "2" Grid.Column = "3" Click = "Input_Button_Click" />
< Button Content = "-" Grid.Row = "3" Grid.Column = "3" Click = "Input_Button_Click" />
< Button Content = "*" Grid.Row = "4" Grid.Column = "3" Click = "Input_Button_Click" />
< Button Content = "/" Grid.Row = "5" Grid.Column = "3" Click = "Input_Button_Click" />
< Button Content = "." Grid.Row = "5" Grid.Column = "1" Click = "Input_Button_Click" />
< Button Content = "C" Grid.Row = "5" Grid.Column = "2" Click = "Clear_Button_Click" />
< Button Content = "=" Grid.Row = "1" Grid.Column = "3" Click = "Calc_Button_Click" />
< / Grid>
Corresponding IronPython code is as follows:
from __future__ import division
import traceback
import wpf
from System.Windows import Application, Window, MessageBox
class MyWindow (Window):
def __init __ (self):
wpf.LoadComponent (self, 'IronPythonWPF.xaml')
def Calc_Button_Click (self, sender, e):
try:
result = eval (self.InputTb.Text)
self.ResultTb.Text = str (result)
except Exception, e:
tracelog = traceback.format_exc ()
MessageBox.Show (str (e))
pass
def Clear_Button_Click (self, sender, e):
self.InputTb.Text = ""
self.ResultTb.Text = ""
pass
def Input_Button_Click (self, sender, e):
self.InputTb.Text + = sender.Content
pass
if __name__ == '__main__':
Application (). Run (MyWindow ())
C # call IronPython
We've seen how to use the .NET library in IronPython, take a look at the following script execute IronPython C # code. In the .NET framework, including IronPython compiler and execution engine, so we can create an instance of the engine through the C # code, and then execute the script.
We need to look at the type of use:
ScriptEngine: dynamic languages (IronPython) execution class to parse and can perform dynamic language code.
ScriptScope: Build an execution context in which to save the environment and global variables; the host (Host) execution context can be provided by a plurality of data isolation create different ScriptScope.
ScriptSource: control type dynamic language code can be compiled (Compile), running (Execute) code.
Now we have a simple print current time IronPython script:
import datetime
print "current datetiem is:", datetime.datetime.now ()
Then you can use the following manner script:
static void Main (string [] args)
{
try
{
ScriptEngine engine = Python.CreateEngine ();
ScriptScope scope = engine.CreateScope ();
ScriptSource script = engine.CreateScriptSourceFromFile (@ "Script.py");
var result = script.Execute (scope);
}
catch (Exception e)
{
Console.WriteLine (e.Message);
}
Console.Read ();
}
IronPython to pass parameters
In ScriptScope type, there is a SetVariable way, we can pass parameters to the script by this method.
public void SetVariable (string name, object value)
In this way, we can put a C # instance to IronPython, then a member of the script you can use C # instance. Look at an example:
public class Student
{
public int Age {get; set;}
public string Name {get; set;}
public override string ToString ()
{
return string.Format ( "{0} is {1} years old", this.Name, this.Age);
}
}
class Program
{
static void Main (string [] args)
{
try
{
ScriptEngine engine = Python.CreateEngine ();
ScriptScope scope = engine.CreateScope ();
Student stu = new Student {Name = "Wilber", Age = 28};
scope.SetVariable ( "stuObj", stu);
ScriptSource script = engine.CreateScriptSourceFromFile (@ "PrintStuInfo.py");
var result = script.Execute (scope);
}
catch (Exception e)
{
Console.WriteLine (e.Message);
}
Console.Read ();
}
}
In this example, C # code creates an instance of type Student, and this instance is passed to PrintStuInfo.py script.
print "Student name:", stuObj.Name
print "Student age:", stuObj.Age
print stuObj.ToString ()
Output can be seen by members of IronPython scripts can easily access C # examples.
to sum up
This article demonstrates some examples of interactive IronPython and C #, I feel there are still very few examples of interesting.
Sometimes the use of C # to call IronPython can make the program more flexible, through a C # type provides a set of packaged operation, every build type instance is then passed to the script; this way, the user can write IronPython scripts, and then use the C # type operating methods provided in order to achieve different custom actions. |
|
|
|