Tutorial on using IronPython to integrate Python scripts into a. NET program _python

Source: Internet
Author: User
Tags python script

From two great world to the need, more efficient reuse of code. Think about it and get drunk. NET and Python are merged. "Lazy" program members, what are you waiting for?

Jesse Smith shows you how to serve the same. NET program in two languages. You can set two directors: Python and. NET work together to provide reusable code functionality without requiring you to rewrite the code base for an environment.

By using the IronPython run-time library, you can have the Python script run in your. NET program. This article shows you how to use a. NET program to capture and display user feedback.

If you ever had one in a. NET program to run the Python script, the best way to integrate the two is to use IronPython. I've had this kind of demand. I used to work for an organization that needs to expand one that already exists in one. NET Map program, set of tools. Our goal is to use another tool to centralize existing Python code to extend this set of tools, which is not part of the latter. After doing some research, I decided to use IronPython and things went well.

Based on the experience of the above project, I will revert to the scene and apply to your situation as well.

The first challenge for the solution that we expect is to run from the. NET program to get the output, and then use one of the Python scripts. NET Program dialog box to display this output to the user. To my surprise, it's easier than expected, and you can learn how to do the same thing. The whole process is relatively simple, and we will outline it in the following sections.
embed a Python script in a. NET program

In this example, I show you how to embed a Python script in a Windows desktop program. The goal is to add a new tool button to an existing program. When the button is clicked, the program pops up a dialog box that shows the results of a Python script embedded in the dialog box code.

To give this example more cause and consequences, our application is a desktop map software that allows users to create their own maps. This new tool allows users to parse and standardize the address points on their maps.

Standardizing an address means making sure that the address has a street name, prefix or suffix, a house or construction number, and a street that connects the street and the next street. Each address segment must be guided by the US Post code address standard.

Suppose there is already a Python script that can do this; it is the script that performs the parsing in the example. The Python script will output or flash the resolved address through the current dialog box, and we can trigger the dialog box by selecting the Address resolution tool (I don't want to say too thin, just to explain it here.) )

The code is not important, it is important to know how to embed the script and how to orient the output of the script to the dialog box, which is displayed on the screen as part of the program. This process is done as follows:

    • The user launches the Map program and opens a custom map.
    • Users select a new address standardization tool from an existing set of tools at the top of the screen.
    • An Address Normalization dialog box with a Start button that can start the address normalization process is popped up
    • A text box displays the address that is currently being resolved. These text boxes disappear quickly, and the addresses flash past the user's eyes, indicating that the process is starting and parsing.
    • A message appears that indicates the end of the entire process, using the same text box in step 4th.

Identify source code and projects

The first thing to do is to determine where the script should be embedded in the application's source code. In our example/scenario, this position should be a new dialog box that is added to the containing tool set project. This dialog box is triggered by an already existing method for handling the Click events of the toolbar

Once we have identified the project that contains the source code, we need to refer to the IronPython library.

If you use Visual Studio as an editor, the easiest way to do this is to use NuGet Package Manager to add IronPython libraries to your project. You can search for "IronPython", and then the Run-time library can be selected in the Package management tool.
Embed script

The next thing to do is to really embed the script. You first need to use the scripting engine (scripting engine) to set up a Python script engine instance. Before adding a script, you can also set any specific path that your script requires.

 
ScriptEngine pyengine = Python.createengine ();
PyEngine.Runtime.IO.RedirectToConsole ();
var paths = Pyengine.getsearchpaths ();
Paths. ADD (@ "C:python27lib");
Paths. ADD (@ "c:python27libsite-packages");
Pyengine.setsearchpaths (paths);

The second line tells. NET Framework Python engine's run-time library redirects output to the console. However, this is not redirected to the dialog boxes that we need to add new tools for this application. (The following code does this work)

However, first we need to add the script through a simple string variable. You need to change the quotes in your script to work with the string's quotation marks.

An easy way to do this is to turn all the double quotes in your script into single quotes. The syntax for embedding scripts is as follows:

 
String thescript =
  @ "
  (here is the actual script content)
  ";

You may need to deal with some formatting problems, but indents must be consistent. After parsing a valid string in the script string, it is time to add the output redirection code so that the output of the script is displayed in the tool's dialog window:

 
Console.setout (textwriter.synchronized (New Textboxwriter (statustext)));
    Pyengine.execute (thescript);
    This. Alldone (finished);
   }
   catch (Exception ex)
   {this
    . Alldone (ex. innerexception.stacktrace);
   }
  public void Alldone (String message)
  {
   buttonstart.enabled = true;
   This.statusLabel.Text = message;
  }

In the above code, we set up a new TextWriter that takes a textboxwriter type of argument, which allows us to write the output of the script back into a text box. The code for the Textboxwriter type is as follows:

public class Textboxwriter:textwriter
  {
   private TextBox _textbox;
   Public Textboxwriter (textbox textbox)
   {
    _textbox = textbox;
   }
   public override void Write (char value)
   {
    base. Write (value);
    When character the data are written, append it to the text box.
    _textbox.appendtext (value. ToString ());
   }
   public override System.Text.Encoding Encoding
   {get
    {return System.Text.Encoding.UTF8;}
   }
  }
 }

The StatusText property of the incoming Textboxwriter type is our text box, which appears in the dialog box, showing the output of the script. Every output statement in our Python script will be redirected to this text box.
Conclusions

In this article, you learned how to integrate Python scripts into a. NET program and output Python script files to a. NET dialog box. This seamless convergence, users do not feel, they do not know that is actually python processing some of the work behind the scenes.

In many situations, it is useful to integrate both languages. I shared this situation and provided a good solution for my situation. You can follow similar steps and use the same method to apply it to many situations.

I suggest you build a simple example of yourself and even use Python script files to add Python code directly to the. NET application, and you can do that. Of course you don't have to embed the script directly into the. NET source code, but this is the most convenient for me.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.