Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ IronPython and C # to interact     - CentOS 6.x and CentOS7 installation RPMforge (Linux)

- Zabbix configure DataGuard monitoring (Database)

- Use Markdown editor for document work under Linux (Linux)

- Installation and Configuration rsync server under CentOS 6.3 (Server)

- Fedora 19/20 and Debian Jessie / Sid users to install FFmpeg 2.3.2 (Linux)

- Linux Security trust with users (Linux)

- AngularJS (Programming)

- How to use the ps command to monitor progress in the implementation of Linux commands (Linux)

- How to disable IPv6 on Ubuntu, Linux Mint, Debian (Linux)

- Linux account management add relevant directives (Linux)

- Ubuntu disable graphics card (Linux)

- Java integrated development environment common set of operations (Linux)

- Ubuntu 14.10 PPA installed Android Studio (Linux)

- Keepalived achieve high availability Nginx Reverse Proxy (Server)

- SSH without password (Linux)

- Vim copy and paste register (Linux)

- Why JavaScript basic types can invoke methods (Programming)

- Why is better than Git SVN (Linux)

- Ubuntu method for single-card dual-IP (Linux)

- CentOS 6.4 Python 2.6 upgrade to 2.7 (Linux)

 
         
  IronPython and C # to interact
     
  Add Date : 2017-08-31      
         
         
         
  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.
     
         
         
         
  More:      
 
- Redis 3.0.3 Cluster Setup (Database)
- CentOS install Java 1.8 (Linux)
- Oracle set and remove columns unavailable (Database)
- Ubuntu Tutorial: E: Failed to get lock / var / lib / apt / lists / lock - open (Linux)
- XenServer Virtual Machine Installation --- first ISO image file storage expansion (Linux)
- How to protect your eyes automatically adjust the screen brightness on Linux (Linux)
- The array of C language (Programming)
- Linux system - The understanding cpu load (Linux)
- Eclipse Android development environment installation (Linux)
- Use XtraBackup be physical standby database MySQL (Database)
- Set multiple IP addresses for a single network card on Ubuntu 15.10 (Linux)
- Fedora 19/20 and Debian Jessie / Sid users to install FFmpeg 2.3.2 (Linux)
- Camouflage Nginx Web server version to prevent invasion (Linux)
- Binary Tree Traversal (Linux)
- How do I upgrade from Ubuntu 15.04 to Ubuntu 15.10 (Linux)
- Linux system last command usage (Linux)
- IBM Data Studio to use ---- window displays all rows (Database)
- Syncthing: Private Security Synchronization tool to synchronize files between computers / folder (Linux)
- 10 important Linux ps command combat (Linux)
- Nginx + uWSGI + Django + Python Application Architecture Deployment (Server)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.