从C#访问IronPython字典

3

我在Ironpython脚本中定义了一个字典,我希望可以从我的C#代码中访问这个字典。请问有人能够提供示例代码来满足我的需求吗?

抱歉之前没有陈述我的问题附带代码。

import clr
clr.AddReference("System.Core")
import System
clr.ImportExtensions(System.Linq)
from System.Collections.Generic import Dictionary,List

def check(self):
    dict1 = Dictionary[str,str]
    dict1["a"] = "aa"
    dict2 = Dictionary[str,str]
    dict2["b"] = "bb"
    self[0] = dict1
#   self.Add(dict1)
    return self

C#

var runtime = Python.CreateRuntime();
dynamic test = runtime.UseFile("Test.py");


var myDictList = new List<Dictionary<string, string>>();
var myDL = new List<Dictionary<string, string>>();
myDL = test.check(myDictList);

我的目标是在Python中对字典列表进行操作(添加、从列表中删除),并将其发送回C#,以便我可以进一步使用它。
我想要的是在Python或C#中创建一个字典列表,并在这两个地方(Python和C#)使用它。
如何做到这一点?

提供代码可以让他人更好地帮助你。 - Ramunas
2个回答

8

这个有效:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.Utils;
using Microsoft.Scripting.Runtime;
using IronPython;
using IronPython.Hosting;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ScriptEngine pyEngine = Python.CreateEngine();
            ScriptScope pyScope = pyEngine.CreateScope();
            ScriptSource pyScript = pyEngine.CreateScriptSourceFromString("d = {'a':1,'b':2,'c':3}");
            CompiledCode pyCompiled = pyScript.Compile();
            pyCompiled.Execute(pyScope);
            IronPython.Runtime.PythonDictionary d = pyScope.GetVariable("d");
            Console.WriteLine(d.get("a"));
            Console.Read();
        }
    }
}

应该返回键'a'的第一个值。希望这能帮到你。 可能有一两个包含的文件过多。


1
Python字典和C#字典只共享名称。例如,在C#中不能有混合类型。使用IronPython.Runtime.PythonDictionary作为数据类型有什么问题?您可以使用pyScope.SetVariable设置数据,也可以获取数据。 - Johannes Maria Frank
在Python中,我正在编写一个解析器,它将以文件路径为输入,并创建已解析项目的字典列表。然后我想在C#中使用解析数据。因此,我认为pyScope.SetVariable或pyScope.GetVariable都不会帮助我,因为在C#中我不会修改任何内容,我只是要使用已解析的内容。 - user703686
你试过我的小代码片段吗?我使用了CreateScriptSourceFromString,但你也可以将Python脚本文件作为输入。d是字典。它有条目a:1 b:2和c:3。我访问了a并得到了1。这不正是你想要的吗? 另外,你还可以使用Xml.Serializer将字典序列化并在C#中重新读取。这将克服Python字典和通用字典之间的不兼容性。 - Johannes Maria Frank

1
def check(self):
    dict1 = Dictionary[str,str]()
    dict1["a"] = "aa"
    dict2 = Dictionary[str,str]()
    dict2["b"] = "bb"
    self[0] = dict1
    #   self.Add(dict1)
    return self

注意,这里的 ()。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接