在.Net6中调用IronPython实现动态执行脚本
本文显示了一个在.Net6中借用IronPython动态执行Python脚本的功能的简单示例,可供需要动态执行脚本的工况进行参考。示例显示了动态Python脚本能与c#代码交互,支持定义函数,定义变量,获取返回值(“不需特殊处理”)等功能。
开发环境及相关依赖需求
- 依赖Nuget包:IronPython V3.4.1;
- 运行时:.Net6.0 (其他环境未测试);
代码
// Program.cs
namespace ConsoleOutValue
{
internal class Program
{
static void Main(string[] args)
{
CSPython cspy = new CSPython();
cspy.Test1();
Console.ReadLine();
}
}
}
// CSPython.cs
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
namespace ConsoleOutValue
{
public class CSPython
{
private ScriptEngine engine;
private ScriptScope scope;
public CSPython()
{
// 创建 IronPython 引擎实例
engine = Python.CreateEngine();
scope = engine.<
在.NET6中利用IronPython动态脚本执行与交互

本文介绍了如何在.NET6环境中使用IronPython实现动态脚本执行,包括创建ScriptEngine实例、定义函数、变量操作以及跨语言交互。示例展示了如何导入Python库、执行函数并处理异常。
最低0.47元/天 解锁文章
279





