Im using IronPython and i try to instantiate a color from script and return it. I got this method and send in this string as an argument
@"
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);
}
When I run this code I get
$exception {System.InvalidOperationException: Sequence contains no matching element at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate).. etc.
I can not figure out how to get this to work, so please help me.
I won't know for sure until I see either more of your source or the full stack, but I would guess you're missing having the python engine include a reference to the necessary WPF assemblies (PresentationCore for System.Windows.Media.Color AFAICT).
Depending on whether you care about the C# caller needing a reference to the same library, you can change how it gets a reference to it, but just adding PresentationCore lets me reference the necessary assembly (without strings :) and then add it to the IronPython runtime.
The below code runs fine and prints out #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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.