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

标签 c# python 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 脚本?

最佳答案

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

关于c# - 如何使用 IronPython 将参数传递给 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30384793/

相关文章:

c# - 如何找出我的依赖属性已更改?

c# - 为什么 "View Heap"结果与 Visual Studio 中的 'Process Memory Usage' 不匹配

c# - 使用 iOS 加密;使用 .Net 解密

python - 如何针对每个名称附加先前不在数据帧 1 中但在数据帧 2 中的键

python - Anaconda Python : Delete . pkgs 中的 tar.gz

c# - IronPython:如何访问回溯局部变量

winforms - IronPython + Winforms 以非阻塞方式

c# - 向 WebAPI 添加新方法会出现 "multiple actions"错误

python - 当 'text' 可能包含更多 {{ text }} block 时,如何用 re.sub() 替换表达式 {{ text }} ?

python - 在 IronPython 中创建自定义 WPF 控件 : a control made up out of standard controls