Script arguments and built-in IronPython

I have a built-in scripting engine in my C # application using IronPython 2. I create a Python runtime and add several classes to the global namespace so that the script can import them as modules.

However, one (rather simple) thing that I cannot understand is to send script arguments. I understand that I can just create a variable with a list of arguments, but there must be a proper way to do this. Also, by doing this in the correct "Python" way, I can compile scripts and use an automatic document creator called Sphinx. Therefore, the ultimate goal is to be able to use:

import sys sys.argv 

In one of my scripts and get the arguments that the user specified (through the C # application).

Right now I'm calling a script using:

 // set up iron python runtime engine _engine = Python.CreateEngine(); _runtime = _engine.Runtime; _scope = _engine.CreateScope(); // run script _script = _engine.CreateScriptSourceFromFile(_path); _script.Execute(_scope); 

And I tried to find an API to add script arguments without any luck. I also tried adding them to the script path (_path in the example) with no luck. I tried with the file CreateScriptSourceFrom and CreateScriptSourceFromSting (which was a long shot anyway ...).

Am I trying to make this even possible?

+4
source share
2 answers

When you create the engine, you can add the "Arguments" parameter containing your arguments:

 IDictionary<string, object> options = new Dictionary<string, object>(); options["Arguments"] = new [] { "foo", "bar" }; _engine = Python.CreateEngine(options); 

Now sys.argv will contain ["foo", "bar"] .

You can set options["Arguments"] on everything that implements ICollection<string> .

+6
source

sys.argv will eventually return the actual parameters passed to the hosting application. Here are some ways to solve this problem:

  • Rewrite the script to accept global variables and then use ScriptScope.SetVariable
  • Run the script, but rely on it to actually return you a class that you can reference methods on (much easier in 4.0 with a dynamic keyword).
  • Override sys.argv with your own implementation (it's still a dynamic language!)
+1
source

All Articles