c# - 从字符串创建 IronPython(动态)对象

标签 c# ironpython

假设我有一个 python 脚本“calculator.py”:

def Add(x,y) :
    return x + y;

我可以像这样实例化一个动态对象:

var runtime = Python.CreateRuntime();
dynamic calculator = runtime.UseFile("calculator.py");
int result = calculatore.Add(1, 2);

是否有类似的简单方法可以从内存中的字符串实例化计算器?我想要得到的是这样的:

var runtime = Python.CreateRuntime();
string script = GetPythonScript();
dynamic calculator = runtime.UseString(script); // this does not exist
int result = calculatore.Add(1, 2);

GetPythonScript() 可能是这样的:

string GetPythonScript() {
   return "def Add(x,y) : return x + y;"
} 

最佳答案

你可以这样做:

var engine = Python.CreateEngine();
dynamic calculator = engine.CreateScope();
engine.Execute(GetPythonScript(), calculator);

关于c# - 从字符串创建 IronPython(动态)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3314443/

相关文章:

C# 等效于 VB.NET 接口(interface)实现

c# - 如何从位图中获取 Bitsperpixel

excel - Ironpython 写入 Excel

.net - 如何创建库项目

python - IronPython:您曾使用 IronPython 而不是标准 .NET 语言(例如 C#)完成过哪些工作

c# - 为什么使用 xpath 获取属性失败?

c# - 在包含其他控件的 C# UserControl 中重写 OnPaint 和抓取鼠标事件的问题

c# - 如果我不从 asp.net 中的图像上传控件中选择图像,我想在数据库中插入 null

c# - 从 Iron Python 脚本(从 C# 脚本引擎调用)调用 Python 脚本时出现问题

c# - 为什么从 C# 调用 Python lambda 表达式不是线程安全的?