1

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.

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

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

My additional C# Code:

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

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

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?

1
  • Could you extend your sample to show what you are doing with source in UpdateElements? Your exception is probably caused by an iteration like for s in source:... Commented Nov 7, 2013 at 11:09

1 Answer 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:

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:

var data = new[] { "a", "b", "c", "d" };
var engine = Python.CreateEngine();
dynamic script = engine.ExecuteFile(@"script.py");
dynamic function = script.UpdateElements(data);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.