Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use IronPython in C #

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

How to use IronPython in C#, for this problem, this article details the corresponding analysis and solution, hoping to help more small partners who want to solve this problem find a simpler and easier way.

Using IronPython in C#

Create a new project, ConsoleApplication

NuGet then adds IronPython packages

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(scope);Console.WriteLine(result);

There are three main types used here: ScriptEngine, ScriptScope, ScriptSource

ScriptEngine is the engine, ScriptScope is equivalent to a container that can be used to pass some custom variables, ScriptSource is the script source code.

Hello world!

C#Passing 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(scope);Console.WriteLine(result);

The output becomes Hello 123.

You can also try something more wonderful, such as C#defining a class

public class Foo{

public string Name { get; set; }

public DateTime Birthday { get; set; }}

Try passing in this variable and modifying the code of the Main function

ScriptEngine engine = Python.CreateEngine();ScriptScope scope = engine.CreateScope();string script = @"print ('Hello %s' %foo.Name)foo.DoSth()";//Note that the newline here is required Foo foo = new Foo(){ Name = "Assad", Birthday = new DateTime(1999,2,2)};scope.SetVariable("foo", foo);ScriptSource sourceCode = engine.CreateScriptSourceFromString(script);var result = sourceCode.Execute(scope);Console.WriteLine(result);

Successful output: Hello Assad

So what if I call the method in Foo? Yes, oh, you can try, but also to hit the breakpoint!

Executing IronPython files

Replace the script string with the file path and use ScriptEngine's CreateScriptSourceFromFile method to execute IronPython in file format

Create a new file named test.py and paste the script characters into it. Modify the attribute of the file to "Copy if newer."

Then the code segment of the Main function is:

ScriptEngine engine = Python.CreateEngine();ScriptScope scope = engine.CreateScope();

string path = @"test.py";Foo foo = new Foo(){ Name = "Assad", Birthday = new DateTime(1999,2,2)};scope.SetVariable("foo", foo);ScriptSource sourceCode = engine.CreateScriptSourceFromFile(path);

var result = sourceCode.Execute(scope);Console.WriteLine(result);

Execution successful, output results unchanged.

But at this time the editor support for py file is not available, at this time you can install a plug-in, Python Tools for Visual Studio referred to as PTVS, can be obtained on GitHub: github.com/Microsoft/PTVS/releases

After installation, there will be syntax highlighting and intelligent prompts ~

This tool adds a lot of Python support, and you can also see new Python templates in new projects, including some popular Python website templates such as Django, and of course IronPython templates are also indispensable.

Using C#Types in IronPython

Another question, just defined Birthday attribute in foo, but its type is DateTime, how to use it in IronPython?

Modify the code in the test.py file

print('Hello %s' %foo.Name)foo.DoSth()

from System import DateTime

print("My birthday is %s" %foo.Birthday.ToString())

Here I'm using the from System import DateTime line, which introduces the DateTime type.

Similarly, you can also introduce String, TimeSpan, etc. types in the System assembly, which is very convenient, such as this

from System import *

What if you need to add an assembly reference?

For example, if I create a new class library and put the Foo class into this new class library, then when I want to use Foo, just like this:

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())

Perhaps your program will tell you an error that Module cannot be found, so copy Foo.dll into your execution directory. Or you can modify the code in the Main function by using engine.SetSearchPaths(new[]{@"../ Foo/bin/Debug"}); Sets the path to find class libraries.

If the report cannot find the Foo type in Foo, then you copied the Foo class code into the class library without using the Foo class library namespace.

other

Now that you know how to use IronPython in C#and use C#types and variable passing in IronPython code, you can add cool scripting language dynamics to your C#programs.

Regarding the timing of CreateScriptSource, you can probably use the FileSystemWatcher class to monitor file modifications, but be aware of multithreading issues.

If you don't need IronPython in C#, but just want to use Python-like syntax to do some. net programs such as winform, wpf, etc., you can install IronPython's installation package, which can be downloaded from the official website address given at the top. After installation, you will get a separate environment for IronPython and related documentation.

Then you can create your IronPython program with the IronPython project templates PTVS added for you.

Moreover, they support breakpoint debugging oh! Do you have a good idea, such as using Link files in C#projects to link py files in IronPython projects,

About how to use IronPython in C#questions to share the answer here, I hope the above content can be of some help to everyone, if you still have a lot of doubts not solved, you can pay attention to the industry information channel to learn more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report