Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

c# - Script arguments and Embedded IronPython

I have an embedded scripting engine in my C# application that uses IronPython 2. I create the Python runtime and add a few classes to the global namespace so that the script can import them as modules.

However, one (pretty basic) thing I can't figure out is how to send script arguments. I realize that I could just create a variable with a list of arguments, but there must be a proper way to do it. Also, doing it in the proper 'Python' way allows me to compile the scripts and use an automated document builder called Sphinx. So the ultimate goal is to be able to use:

import sys
sys.argv

In one of my scripts and have it get the arguments the user specified (through the C# app).

Right now, I call the script by 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've tried searching for an API to add script arguments with no luck. I've also tried appending them to the script path (_path in example) with no luck. I tried with CreateScriptSourceFrom File and CreateScriptSourceFromSting (which was a long shot anyway...).

Is what I'm trying to do even possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you create the engine, you can add an "Arguments" option the contains 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"] to anything that implements ICollection<string>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...