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

How do I pass arguments to a Python script with IronPython

我有以下 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 脚本?

"Command line arguments" 只存在于进程中。如果您 运行 以这种方式编写代码,您的 python 脚本很可能会在进程启动时看到传递给进程的参数(如果没有 Python 代码,则很难判断)。 根据评论中的建议,您可以 override command line arguments too.

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

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

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

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

虽然我认为@Discord 使用设置变量是可行的,但它需要将 sys.argvs 更改为 variableName

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

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

参考文献:

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

How can I pass command-line arguments in IronPython?

谢谢大家给我指明了正确的方向。由于某些原因,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<String> argv = new List<String>();
            //Do some stuff and fill argv
            argv.Add("foo");
            argv.Add("bar");
            engine.GetSysModule().SetVariable("argv", argv);
            source.Execute(scope);
        }
    }
}