问题描述
我正在尝试使用 IronPython 在 C# windows 窗体应用程序中使用我的简单 python 类。 我成功地使用了它,但是在 python 脚本中导入一个随机库后,引擎开始给我一个错误。 那么如何将这个库导入到 C# 代码中?!
注意我的问题是在将这一行添加到 python 代码后开始的(import random)
我的 Python 代码:
import random
class Math:
def RandomF(self,a,b):
return random.randint(a,b)
def Emptyss(self):
return 3
def sum(self,b):
return a+b
def sub(self,b):
return a-b
def mult(self,b):
return a*b
def devi(self,b):
return a/b
def Max(self,b):
if a >b:
return a
else:
return b
def Min(self,b):
if a<b:
return a
else :
return b
我的 C# 类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Speech;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Windows.Forms;
using System.IO;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
namespace VoiceRecognition
{
class VoiceRecongnitionClass
{
Microsoft.Scripting.Hosting.ScriptEngine engine;
dynamic MathClass;
public VoiceRecongnitionClass()
{
try
{
string code = @"import random
class Math:
def RandomF(self,b):
return random.randint(a,b)
def Emptyss(self):
return 3
def sum(self,b):
return a+b
def sub(self,b):
return a-b
def mult(self,b):
return a*b
def devi(self,b):
return a/b
def Max(self,b):
if a >b:
return a
else:
return b
def Min(self,b):
if a<b:
return a
else :
return b
";
engine = Python.CreateEngine();
dynamic scope = engine.CreateScope();
//error start here
engine.Execute(code,scope);
MathClass = scope.Math();
}
catch (Exception a)
{
MessageBox.Show(a.ToString());
}
}
public float sum(float a,float b)
{
return MathClass.sum(a,b);
}
}
}
错误信息:
IronPython.Runtime.Exceptions.ImportException: No module named random
at Microsoft.Scripting.Runtime.LightExceptions.CheckAndThrow(Object value)
at Microsoft.Scripting.Interpreter.FuncCallInstruction`2.Run(InterpretedFrame frame)
at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
at Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0,T1 arg1)
at IronPython.Compiler.PythonScriptCode.RunWorker(CodeContext ctx)
at IronPython.Compiler.PythonScriptCode.Run(Scope scope)
at IronPython.Compiler.RuntimeScriptCode.InvokeTarget(Scope scope)
at IronPython.Compiler.RuntimeScriptCode.Run(Scope scope)
at Microsoft.Scripting.sourceUnit.Execute(Scope scope,ErrorSink errorSink)
at Microsoft.Scripting.Hosting.ScriptSource.Execute(ScriptScope scope)
at Microsoft.Scripting.Hosting.ScriptEngine.Execute(String expression,ScriptScope scope)
at CallSite.Target(Closure,CallSite,ScriptEngine,String,Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid3[T0,T2](CallSite site,T0 arg0,T1 arg1,T2 arg2)
at VoiceRecognition.VoiceRecongnitionClass..ctor() in D:\VisualStudio_Projects\Projects\VoiceRecognition\VoiceRecognition\VoiceRecognition\VoiceRecongnitionClass.cs:line 78
不是:第 78 行是 "engine.Execute(code,scope);"
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)