我有以下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脚本时,如何更改此代码以将命令行参数传递给它?
虽然我认为@Discord使用设置变量是可行的,但它需要将
sys.argv
s更改为variableName
。因此,要回答这个问题,应该使用
engine.Sys.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。如果要做的是传递参数,而不一定是命令行参数,那么有几种方法。
最简单的方法是将变量添加到您定义的作用域中,并在脚本中读取这些变量。例如:
在python代码中,您将拥有
variableName
变量。谢谢你们指引我正确的方向。出于某种原因,engine.sys似乎不再适用于更新版本的IronPython,因此必须使用GetSysModule。下面是我的代码的修订版本,它允许我更改argv:
相关问题 更多 >
编程相关推荐