【问题标题】:Create System.Windows.Media.Color in IronPython在 IronPython 中创建 System.Windows.Media.Color
【发布时间】:2012-05-15 09:37:43
【问题描述】:

我正在使用 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);
}

当我运行这段代码时,我得到了

$exception {System.InvalidOperationException: 序列不包含匹配元素 在 System.Linq.Enumerable.First[TSource](IEnumerable`1 源,Func`2 谓词).. 等。

我不知道如何让它工作,所以请帮助我。

【问题讨论】:

  • 由于我在您的源代码中没有看到 First 调用,您能否提供整个堆栈和项目中的任何其他源代码?
  • 不幸的是,异常并没有指出实际问题 - 这是托管 IronPython 的错误:ironpython.codeplex.com/workitem/32679。实际的异常丢失了。
  • Simon900225,您能否提供一个导致您遇到错误的最小项目?我无法复制它。

标签: c# ironpython


【解决方案1】:

在看到更多您的源代码或完整堆栈之前,我无法确定,但我猜您缺少让 python 引擎包含对必要 WPF 程序集的引用(System.Windows 的 PresentationCore。 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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 2011-06-04
    相关资源
    最近更新 更多