4

如何将命令行参数从我的 C# 应用程序传递到 IronPython 2.x?Google 只返回有关如何使用 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]);
}
4

1 回答 1

5

您可以通过以下 C# 代码设置 sys.argv:

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]);
}

具有以下python脚本

import sys
for arg in sys.argv:
    print arg

并像调用exe一样

Test.exe SomeScript.py foo bar

给你输出

SomeScript.py
foo
bar

另一种选择是将准备好的选项传递给本答案Python.CreateRuntime中的说明

于 2012-06-01T20:21:14.813 回答