4

How do I pass command line parameters from my C# application to IronPython 2.x? Google is only returning results about how to do it with Iron Python 1.x.

static void Main(string[] args)
{
    ScriptRuntime scriptRuntime = IronPython.Hosting.Python.CreateRuntime();
    // Pass in script file to execute but how to pass in other arguments in args?
    ScriptScope scope = scriptRuntime.ExecuteFile(args[0]);
}
Danielb
  • 1,608
  • 5
  • 24
  • 34

1 Answers1

5

You can either set the sys.argv via the following C# code:

static void Main(string[] args)
{
    var scriptRuntime = Python.CreateRuntime();
    var argv = new List();
    args.ToList().ForEach(a => argv.Add(a));
    scriptRuntime.GetSysModule().SetVariable("argv", argv);
    scriptRuntime.ExecuteFile(args[0]);
}

having the following python script

import sys
for arg in sys.argv:
    print arg

and calling the exe like

Test.exe SomeScript.py foo bar

gives you the output

SomeScript.py
foo
bar

Another option would be passing the prepared options to Python.CreateRuntime as explained in this answer

Community
  • 1
  • 1
Simon Opelt
  • 6,136
  • 2
  • 35
  • 66