Use IronPython to integrate Python scripts into. NET programs. ironpythonpython

Source: Internet
Author: User

Use IronPython to integrate Python scripts into. NET programs. ironpythonpython

Take the necessary information from two excellent worlds to reuse code more efficiently. Think about it. NET and python are integrated. What are the "lazy" programmers waiting?

Jesse Smith shows you how to use two languages to serve the same. NET program. You can combine Python and. NET to provide reusable code functions without the need to rewrite the code library for an environment.

By using the IronPython Runtime Library, you can run Python scripts in your. NET program. This article shows you how to use the python script in A. NET program to obtain and display user feedback.

If you have a need to run Python scripts in A. NET Program, the best way to integrate the two is to use IronPython. I have such a requirement. An organization I used to work with needs to expand a toolset that already exists in A. NET map program. Our goal is to use the existing Python code in another tool set to expand this existing tool set. The former is not part of the latter. After some research, I decided to use IronPython, and the process went quite well.

Based on the experience of the above project, I will restore the current scenario and apply it to your situation as well.

The first challenge to this expected solution is to run in. the Python script in the. NET program gets the output, and then uses.. NET Program dialog box to display this output to the user. To my surprise, you can also learn how to do the same thing if it is easier than expected. The entire process is relatively simple. We will give an overview in the following sections.
Embed a Python script in A. NET Program

In this example, I will show you how to embed a Python script in a Windows desktop program. The purpose is to add a new tool button in an existing program. Click the button. A dialog box is displayed, showing the running result of a Python script embedded in the dialog box code.

To pave the way for this example, we use a desktop map software that allows users to create their own maps. The new tool allows users to parse and standardize address points on their maps.

To standardize an address, make sure that the address has a street name, prefix or suffix, house or building number, and connects the street to the previous Street and the next street. Each address segment must follow the instructions of the US post office zip code.

Suppose there is already a Python script that can do this; it is the parsing script in the example. The Python script will output or flash the address being parsed on the screen through the current dialog box. We can trigger the dialog box by selecting the address parsing tool (I don't want to say too detailed, only here .)

The code is not important. It is important to know how to embed the script and how to export the script to the dialog box, and display it on the screen as part of the program. This process is as follows:

  • The user starts the map program and opens a custom map.
  • You can select a new address standardization tool from the existing tool set on the top of the screen.
  • The address standardization dialog box is displayed with a start button to enable the address standardization process.
  • A text box shows the address being parsed. These text boxes quickly disappear, and the address flashed in front of the user, indicating that the process was started and is being parsed.
  • A message indicating the end of the entire process appears. The text box in step 1 is used.

Determine source code and Project

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

When we determine the project that needs to contain source code, we need to reference the IronPython library.

If you use Visual Studio as the editor, the easiest way is to use Nuget Package Manager to add the IronPython Library to the project. You can search for "IronPython", and then select the Runtime Library in the package management tool.
Embedded script

The next step is to embed the script. You must first use the scripting engine to set up a Python script engine instance. Before adding a script, you can set any special path required by your script.

 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 the. NET Framework that the Python engine Runtime Library will redirect the output to the console. However, this is not redirected to the dialog box we need to add a new tool for this application. (The following code will do the job)

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

A simple method is to convert all the double quotes in your script into single quotes. The syntax of the embedded script is as follows:

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

You may need to handle some format issues, but the indentation must be consistent. After the script string parses a valid string, it is time to add the output redirection code so that the Script output is displayed in the tool dialog box:

 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 a new TextWriter, which accepts a TextBoxWriter type parameter, so that we can re-write the script output to a text box. The TextBoxWriter code 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 is 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 attribute of the input TextBoxWriter type is our text box, which appears in the dialog box and displays the Script output. Every output statement in our Python script is redirected to this text box.
Conclusion

In this article, you learned how to integrate Python scripts into A. NET program and output Python script files to a. NET dialog box. Users will not feel this seamless connection. They do not know that Python is actually working in the background.

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

I suggest you create your own simple example, or even directly add the Python code to the. NET application using a Python script file. You can do this. Of course, you do not need to directly embed the script in the. NET source code, but it is most convenient for me to do so.

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.