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

10
我有以下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脚本时,我应该如何更改此代码以传递命令行参数?请注意保留HTML标记。


可能是 https://stackoverflow.com/questions/5949735/how-can-i-pass-command-line-arguments-in-ironpython 的重复问题。 - IronManMark20
3个回答

9
感谢大家为我指明正确的方向。由于某种原因,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);
        }
    }
}

3

"命令行参数"仅适用于进程。如果您以这种方式运行代码,则您的 Python 脚本在启动进程时很可能会看到传递给进程的参数(没有 Python 代码,很难确定)。 如评论中所建议的那样,您可以覆盖命令行参数

如果您想要传递参数,而不一定是命令行参数,则有几种方法。

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

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

在Python代码中,你将有一个名为variableName的变量。

2

谢谢!我有一个关于engine.Sys的问题,我的程序中出现了以下消息:“'Microsoft.Scripting.Hosting.ScriptEngine'不包含'Sys'的定义,也没有接受类型为'Microsoft.Scripting.Hosting.ScriptEngine'的第一个参数的扩展方法'Sys'(您是否缺少使用指令或程序集引用?)”。我该如何消除这个错误并让engine.Sys被识别? - GenericAlias
嗯...我想这个例子使用了PythonRuntime实例。我需要再仔细研究一下。 - IronManMark20

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接