如何将列表从C#传递给Ironpython作为函数的输入参数

时间:2022-09-20 16:57:16

I have a Python script which I use in my C# code (Ironpython), which works fine. So additionally I'd like to add a list as input parameter for my function in the Python script.

我有一个Python脚本,我在我的C#代码(Ironpython)中使用,它工作正常。另外,我想在Python脚本中为我的函数添加一个列表作为输入参数。

I get some strings from a C# WinForm which I have formatted like Python code:

我从C#WinForm中获取了一些字符串,我将其格式化为Python代码:

string code = "list [a, b, c, d]";

My additional C# Code:

我的额外C#代码:

ScriptSource source = m_engine.CreateScriptSourceFromString(code);
dynamic script = m_engine.ExecuteFile(@"path to my file");
dynamic function = script.UpdateElements(source);

But then I get the following exception:

但后来我得到以下异常:

iteration over non-sequence of type ScriptSource

迭代ScriptSource类型的非序列

In my Python file I have a function like this (where source is a list):

在我的Python文件中,我有一个这样的函数(其中source是一个列表):

def UpdateElements(source):
   #do some stuff

So my question: how can I pass a list of strings from C# as input to my function in the Python script?

所以我的问题是:我如何将C#中的字符串列表作为Python脚本中的函数输入传递?

1 个解决方案

#1


3  

Having a list of strings as

有一个字符串列表

var code = "['a', 'b', 'c', 'd']";

You can execute this list literal source to retrieve an IronPython list:

您可以执行此列表文字源来检索IronPython列表:

dynamic result = source.Execute();

This list can be used to invoke the function:

此列表可用于调用该函数:

dynamic function = script.UpdateElements(result);

As an alternative (if the literal string list is just a workaround and you have the actual values in some other form) you could also provide a .NET collection to your IronPython function and be fine for many scenarios:

作为替代方案(如果文字字符串列表只是一种解决方法,并且您具有其他形式的实际值),您还可以为IronPython函数提供.NET集合,并且适用于许多场景:

var data = new[] { "a", "b", "c", "d" };
var engine = Python.CreateEngine();
dynamic script = engine.ExecuteFile(@"script.py");
dynamic function = script.UpdateElements(data);

#1


3  

Having a list of strings as

有一个字符串列表

var code = "['a', 'b', 'c', 'd']";

You can execute this list literal source to retrieve an IronPython list:

您可以执行此列表文字源来检索IronPython列表:

dynamic result = source.Execute();

This list can be used to invoke the function:

此列表可用于调用该函数:

dynamic function = script.UpdateElements(result);

As an alternative (if the literal string list is just a workaround and you have the actual values in some other form) you could also provide a .NET collection to your IronPython function and be fine for many scenarios:

作为替代方案(如果文字字符串列表只是一种解决方法,并且您具有其他形式的实际值),您还可以为IronPython函数提供.NET集合,并且适用于许多场景:

var data = new[] { "a", "b", "c", "d" };
var engine = Python.CreateEngine();
dynamic script = engine.ExecuteFile(@"script.py");
dynamic function = script.UpdateElements(data);