Skip to main content
 首页 » 编程设计

c#之在 IronPython 中导入数学失败

2024年02月13日12bonelee

我正在尝试在 C# 中使用 IronPython 日志功能。想法是用户将编写一个数学脚本,该脚本将被评估并将答案显示在 UI 中。当我将此方法用于简单数学(加法、减法等)时,效果很好。当我需要使用日志功能时,我尝试导入数学模块,但它失败了。我的代码是:

public double Calculate(string script) 
{ 
    ScriptEngine engine = Python.CreateEngine(); 
    ScriptSource source = engine.CreateScriptSourceFromString("import math" + System.Environment.NewLine + script, SourceCodeKind.AutoDetect); 
    return source.Execute<double>(); 
} 

当我运行此代码时,出现异常“IronPython.Runtime.Exceptions.ImportException No Module named math”。 我正在调用方法 计算(“math.log(10)”)`

我是否缺少任何导入或 dll?

请您参考如下方法:

我试图重现您的问题,但是我还没有安装 IronPython,所以我安装了来自 here 的最新稳定版本 (2.7.4) .我不确定你是否使用相同的版本...

在创建解决方案时,我知道我需要添加一些引用。我的猜测是,这就是您的“邪恶”之源。

我添加了引用 'IronPython' 和 'Microsoft.Scripting',它们随 IronPython 安装一起提供。确切的版本是 v4.0.30319(IronPython 和 Microsoft Scripting)。

所以我的 Windows 窗体应用程序有一个文本框和一个按钮(毕竟这只是一个测试),我复制了你的示例方法 Calculate,以确保我们有相同的方法,这是我的版本:

 public double Calculate(string script) 
 { 
   ScriptEngine engine = Python.CreateEngine(); 
   ScriptSource source = engine.CreateScriptSourceFromString("import math" + Environment.NewLine + script, Microsoft.Scripting.SourceCodeKind.AutoDetect); 
   return source.Execute<double>(); 
 } 

在我的按钮的事件处理程序中,我放置了以下代码:

private void button1_Click(object sender, EventArgs e) 
{ 
  try 
  { 
    double outcome = Calculate("math.log(10)"); 
    tbOutcome.Text = string.Format("Outcome of log(10): {0}", outcome); 
  } 
  catch (Exception ex) 
  { 
    MessageBox.Show(ex.Message, "Error occured...", MessageBoxButtons.OK, MessageBoxIcon.Error); 
  } 
} 

当执行我的应用程序时,该程序没有像您的那样显示错误,但它显示了我在计算 log(10) 时所期望的结果(假设您正在计算自然对数)。我的文本框包含:

Outcome of log(10): 2,30258509299405 

所以只有一个提示,请尝试找出您是否安装了 不同 版本的 ScriptEngine(我知道除了 Microsoft.Scripting 之外还有一些)并查看引用资料您的解决方案。

希望对您有所帮助!