Tutorials for integrating Python scripts into a. NET program using IronPython

Source: Internet
Author: User
Picking from two excellent worlds, more efficient reuse code. Just think about it and get drunk. NET and Python are fused. "Lazy" handlers, what are you waiting for?

Jesse Smith shows you how to service the same. NET program in two languages. You can set up 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 Runtime Library, you can have Python scripts run in your. NET programs. This article shows you how to use one. NET program to get and present user feedback.

If you ever had one in a. NET program to run Python scripts, the best way to integrate both is to use IronPython. I've had this kind of demand. An organization I have worked with needs to expand one that already exists in one. NET Map program. Our goal is to extend the existing toolset with another toolset, which is not part of the latter, using the same Python code. After doing some research, I decided to use IronPython and things went well.

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

The first challenge for the solution we expect is to run from the. NET program to get the output, and then use one of the. NET Program dialog box to show this output to the user. To my surprise, this is easier than expected, and you can learn how to do the same thing. The whole process is relatively straightforward and we'll 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 you click the button, the program pops up a dialog box that displays the results of a Python script embedded in the Code of the dialog box.

In order to pave the example for more of the cause and consequences, our app is a desktop map software that allows users to create their own maps. This new tool allows users to parse and standardize address points on their maps.

Standardizing an address means making sure that the address has a street name, prefix or suffix, a house or building number, and the previous street and the next street connected to the street. Each address segment must follow the US Post code Address Standard Guide.

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

The code is not important, it is important to know how to embed the script and how to direct 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.
    • The user selects a new address normalization tool from the existing set of tools at the top of the screen.
    • Popup Address Normalization dialog box with Start button to start address normalization process
    • A text box displays the address that is currently being parsed. These text boxes disappear quickly, and the address flashes past the user's eyes, indicating that the process is up and parsing.
    • A message appears that represents the end of the process, using the same text box in step 4th.

Identify source code and project

The first thing to do is to determine where the script should be embedded in the source code of the application. In our example/scenario, this location should be added to the new dialog box that contains the Toolset project. This dialog box is triggered by an already existing method for handling toolbar click events.

Once we have identified the items that need to contain 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 the NuGet Package Manager to add the IronPython library to your project. You can search for "IronPython", and then the runtime library can be selected in the Package management tool.
Embed script

The next step is to actually embed the script. You first need to set up a Python scripting engine instance using the scripting engine (scripting engines). Before you add a script, you can also set any special paths that your script requires.

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

The second line tells. The run-time library of the NET Framework Python engine redirects the output to the console. However, this is not a redirect to the dialog boxes that are required for the new tool that we added for this app. (The code below will do the work)

But first we need to add a script with a simple string variable. You need to change the quotation marks in your script to work with the quotation marks of the strings.

An easy way 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 indentation must be consistent. After the script string resolves a valid 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 parameter of type Textboxwriter, 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 data was 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. Each output statement in our Python script will be redirected to this text box.
Conclusion

In this article, you learned how to integrate a Python script into a. NET program and output a Python script file to a. NET dialog box. This seamless connection, users will not feel, they do not know is actually python in the background of some work.

In many situations, it is useful to integrate two languages. I shared this scenario and provided a good solution for my situation. You can follow similar steps and apply it to many occasions in the same way.

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

  • Related Article

    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.