gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:49:37 25 4
gpt4 key购买 nike

我有以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com