如何使用IronPython将参数传递给Python脚本 [英] How do I pass arguments to a Python script with IronPython

查看:94
本文介绍了如何使用IronPython将参数传递给Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following C# code where I call a python script from C#:

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脚本?

I'm having trouble understanding each line of the code because my experience with C# is limited. How would I alter this code in order to pass a command line argument to my python script when I run it?

推荐答案

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

Thank you all for pointing me in the correct direction. For some reason engine.sys seems to no longer work for more recent versions of IronPython so instead GetSysModule must be used. Here is the revised version of my code that allows me to alter 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);
        }
    }
}

这篇关于如何使用IronPython将参数传递给Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆