Use IronPython to add materials to the. Net program, ironpython.net

Source: Internet
Author: User

Use IronPython to add materials to the. Net program, ironpython.net

During development, you are often troubled by the planning of frequent changes. At this time, we want to add some dynamic languages to help.

Before considering using dynamic languages, I also thought about how to use dynamic dll loading to implement basic interfaces. A problem occurs during uninstallation. Although it can be bypassed through the application domain, it is added to the interaction between the application domains. There is no convenient Dynamic Language.

IronPython Official Website: http://ironpython.codeplex.com/

Use IronPython in C #

Create a project named ConsoleApplication

Then NuGet adds the IronPython package

Write the following code in the Main function:

    ScriptEngine engine = Python.CreateEngine();    ScriptScope scope = engine.CreateScope();    string script = "print('Hello world!')";    var sourceCode = engine.CreateScriptSourceFromString(script);    var result = sourceCode.Execute<object>(scope);    Console.WriteLine(result);

Three main types are used: ScriptEngine, ScriptScope, and ScriptSource.

As the name suggests, ScriptEngine is an engine, and ScriptScope is equivalent to a container that can be used to pass custom variables. ScriptSource is the script source code.

Output result after running: Hello world!

C # pass variables to IronPython

Modify the above Code as follows:

            ScriptEngine engine = Python.CreateEngine();            ScriptScope scope = engine.CreateScope();            string script = "print('Hello %d' %number)";            scope.SetVariable("number", 123);            ScriptSource sourceCode = engine.CreateScriptSourceFromString(script);            var result = sourceCode.Execute<object>(scope);            Console.WriteLine(result);

The output result is: Hello 123.

For example, C # defines a class.

    public class Foo    {        public string Name { get; set; }        public DateTime Birthday { get; set; }    }

Input this variable and try to modify the Main function code.

ScriptEngine engine = Python. createEngine (); ScriptScope scope = engine. createid (); string script = @ "print ('Hello % s' % foo. name) foo. dosomething () "; // note that the line feed here is required Foo foo = new Foo () {Name =" Asad ", Birthday = new DateTime (, 2)}; scope. setVariable ("foo", foo); ScriptSource sourceCode = engine. createScriptSourceFromString (script); var result = sourceCode. execute <object> (scope); Console. writeLine (result );

Success output: Hello Asad

What if I call the methods in Foo? Yes. You can try it and hit the breakpoint!

Execute the IronPython File

Replace the script string with the file path. Use the CreateScriptSourceFromFile method of ScriptEngine to execute IronPython in the file format.

Create a new file named test. py. paste the script Character above into the file. Modify the file attribute to "copy if new ".

The code segment of the Main function is:

ScriptEngine engine = Python. createEngine (); ScriptScope scope = engine. createid (); string path = @ "test. py "; Foo foo = new Foo () {Name =" Asad ", Birthday = new DateTime (, 2)}; scope. setVariable ("foo", foo); ScriptSource sourceCode = engine. createScriptSourceFromFile (path); var result = sourceCode. execute <object> (scope); Console. writeLine (result );

The execution is successful and the output result remains unchanged.

But at this time the editor of py file support is wooden, at this time you can install a plug-in, Python Tools for Visual Studio PTVS for short, can be obtained on GitHub: https://github.com/Microsoft/PTVS/releases

After installation, you will see syntax highlighting and smart prompts ~

This tool adds a lot of support for Python. You can also see the newly added Python templates in the new project, including some popular Python website templates such as Django, of course, IronPython templates are also indispensable.

 

Use the C # type in IronPython

Another problem is that the Birthday attribute is defined in foo, but its type is DateTime. How can I use it in IronPython?

Modify the code in the test. py file

print('Hello %s' %foo.Name)foo.DoSth()from System import DateTimeprint("My birthday is %s" %foo.Birthday.ToString())

Here, I use the from System import DateTime statement to introduce the DateTime type.

Similarly, you can also introduce the String, TimeSpan, and Other types in the System assembly to make it easy, for example

From System import *

What if I want to add Assembly reference?

For example, if I create a new class library and add the Foo class to the new class library, I only need to do this when using Foo:

import clr,sysclr.AddReference('Foo')from Foo import Foofoo = Foo()foo.Name = "haha"print('Hello %s' %foo.Name)from System import *print("My birthday is %s" %foo.Birthday.ToString())

Maybe your program will tell you an error where the Module cannot be found. Copy Foo. dll to your execution directory. Alternatively, you can modify the code in the Main function and use engine. SetSearchPaths (new [] {@ "../Foo/bin/Debug"}) to set the path for searching the class library.

If the report cannot find the Foo type in Foo, The namespace of the Foo class is not used when you copy the Foo class code to the class library.

Others

Now I know how to use IronPython in C # and how to use the C # type and variable to pass in IronPython code, then you can add cool dynamic features to your C # program.

You may be able to use the FileSystemWatcher class to monitor file modifications when using CreateScriptSource, but pay attention to multithreading.

If you do not need to add IronPython to C #, you just want to use the same syntax as Python.. net programs such as winform and wpf. you can install the IronPython installation package. The installation package is downloaded from the official website at the top. After installation, you will obtain the IronPython runtime environment and related documents.

Then you can create your IronPython program using the IronPython project templates added by PTVS.

Besides, they support breakpoint debugging! Do you have any good ideas, such as using the Link file in the C # project to Link the py file in the IronPython project, ^ _ ^

 

I can't wait to write a script editing game.

 

Add a Sample IronPython mini-game on GitHub.

 

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.