2012-05-06 40 views
2

進出口使用IronPython的創建System.Windows.Media.Color和我嘗試實例從腳本的顏色,並將其返回。 我得到了這個方法,在此字符串作爲參數發送IronPython中

@" 
from System.Windows.Media import Color 
c = Color() 
c.A = 100 
c.B = 200 
c.R = 100 
c.G = 150 
c 
"); 

_python = Python.CreateEngine(); 

public dynamic ExectureStatements(string expression) 
{ 
    ScriptScope scope = _python.CreateScope(); 
    ScriptSource source = _python.CreateScriptSourceFromString(expression); 
    return source.Execute(scope); 
} 

當我運行這段代碼,我得到

$異常{System.InvalidOperationException:序列不包含任何匹配的元素 在System.Linq的.Enumerable.First [TSource(IEnumerable`1源,Func`2謂語)......等

我無法弄清楚如何得到這個工作,所以請幫助我。

+0

因爲我沒有看到你的源第一個呼叫,你能提供整個堆棧,並在項目中的任何其他來源? –

+0

例外,不幸的是,沒有指向實際的問題 - 這是在託管IronPython的一個錯誤:http://ironpython.codeplex.com/workitem/32679。實際的異常會丟失。 –

+0

Simon900225,你將能夠提供一個最小的項目,使你得到了錯誤?我無法複製它。 –

回答

0

我不知道,直到我看到更多的源代碼或完整的堆棧,但我想你錯過了讓python引擎包含對必需WPF程序集的引用(PresentationCore for System.Windows .Media.Color AFAICT)。

取決於您是否關心需要對同一個庫的引用的C#調用方,您可以更改它如何獲取對其的引用,但只需添加PresentationCore即可引用必要的程序集(不帶字符串:),然後添加它到IronPython運行時。

下面的代碼運行正常,並打印出#646496C8

using System; 
using IronPython.Hosting; 
using Microsoft.Scripting.Hosting; 

class Program 
{ 
    private static ScriptEngine _python; 
    private static readonly string _script = @" 
from System.Windows.Media import Color 
c = Color() 
c.A = 100 
c.B = 200 
c.R = 100 
c.G = 150 
c 
"; 


    public static dynamic ExectureStatements(string expression) 
    { 
     var neededAssembly = typeof(System.Windows.Media.Color).Assembly; 
     _python.Runtime.LoadAssembly(neededAssembly); 
     ScriptScope scope = _python.CreateScope(); 
     ScriptSource source = _python.CreateScriptSourceFromString(expression); 
     return source.Execute(scope); 
    } 

    static void Main(string[] args) 
    { 
     _python = Python.CreateEngine(); 
     var output = ExectureStatements(_script); 
     Console.WriteLine(output); 
    } 
}