如何使用IronPython将参数传递给Python脚本

我有以下C#代码,我从C#调用python脚本:

using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Windows.Forms; using System.Linq; using System.Text; using System.Threading.Tasks; using IronPython.Hosting; using Microsoft.Scripting.Hosting; using IronPython.Runtime; namespace RunPython { class Program { static void Main(string[] args) { ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null); ScriptRuntime runtime = new ScriptRuntime(setup); ScriptEngine engine = Python.GetEngine(runtime); ScriptSource source = engine.CreateScriptSourceFromFile("HelloWorld.py"); ScriptScope scope = engine.CreateScope(); source.Execute(scope); } } } 

我无法理解代码的每一行,因为我对C#的经验是有限的。 当我运行它时,如何更改此代码以将命令行参数传递给我的python脚本?

谢谢大家指出我正确的方向。 出于某种原因,engine.sys似乎不再适用于更新版本的IronPython,因此必须使用GetSysModule。 这是我的代码的修订版本,允许我更改argv:

 using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Windows.Forms; using System.Linq; using System.Text; using System.Threading.Tasks; using IronPython.Hosting; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; using IronPython.Runtime; namespace RunPython { class Program { static void Main(string[] args) { ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null); ScriptRuntime runtime = new ScriptRuntime(setup); ScriptEngine engine = Python.GetEngine(runtime); ScriptSource source = engine.CreateScriptSourceFromFile("HelloWorld.py"); ScriptScope scope = engine.CreateScope(); List argv = new List(); //Do some stuff and fill argv argv.Add("foo"); argv.Add("bar"); engine.GetSysModule().SetVariable("argv", argv); source.Execute(scope); } } } 

“命令行参数”仅存在于进程中。 如果你以这种方式运行代码,你的python脚本很可能会在启动时看到传递给你的进程的参数(没有Python代码,很难说)。 正如评论中所建议的那样,您也可以覆盖命令行参数 。

如果你想要做的是传递参数,不一定是命令行参数,那么有几种方法。

最简单的方法是将变量添加到您定义的范围中,并在脚本中读取这些变量。 例如:

 int variableName = 1337; scope.SetVariable("variableName", variableName); 

在python代码中,您将拥有variableName变量。

虽然我认为@ Discord使用设置变量会起作用,但需要将sys.argv s更改为variableName

因此,要回答这个问题,你应该使用engine.Sys.argv

 List argv = new List(); //Do some stuff and fill argv engine.Sys.argv=argv; 

参考文献:

http://www.voidspace.org.uk/ironpython/custom_executable.shtml

如何在IronPython中传递命令行参数?