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

2024-05-08 23:02:48 发布

您现在位置: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脚本时,如何更改此代码以将命令行参数传递给它?


Tags: 代码io脚本sourcesetupsystemcollectionsengine
3条回答

虽然我认为@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?

“命令行参数”仅存在于进程。如果以这种方式运行代码,python脚本很可能会在进程启动时看到传递给它的参数(如果没有python代码,很难说)。如注释中所建议的,您可以override command line arguments too

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

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

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

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

谢谢你们指引我正确的方向。出于某种原因,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);
        }
    }
}

相关问题 更多 >