gpt4 book ai didi

c# - C# : a specific problem/question 中的 IronPython 集成

转载 作者:太空狗 更新时间:2023-10-30 00:27:45 25 4
gpt4 key购买 nike

我正致力于通过 IronPython 为我的 C# 制图应用程序提供一种可扩展性机制。一切正常,但我有一个特定的要求,但我很难实现:我希望用户能够指定两件事:

  1. 要加载的Python脚本的文件名
  2. 包含 Python 脚本的单行字符串,通常是从该 Python 文件调用函数(例如 getTextLabel(element))

这两个设置必须分开,但我不知道是否可以使用 PythonScript 和相关类来做到这一点。

我是 Python 的新手,也许还有另一种方法可以实现这一点?出于性能原因,我想避免多次加载和编译 Python 脚本文件(因为上面可能有几个不同的“函数调用”设置,我想尽可能重用文件的 CompiledCode 实例).

更新:@digEmAll 对我的问题给出了正确答案,所以我接受它作为有效答案。但如果您关心性能,您还应该查看我自己的答案。

最佳答案

你可以这样做:

string importScript = "import sys" + Environment.NewLine +
"sys.path.append( r\"{0}\" )" + Environment.NewLine +
"from {1} import *";

// python script to load
string fullPath = @"c:\path\mymodule.py";

var engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();

// import the module
string scriptStr = string.Format(importScript,
Path.GetDirectoryName(fullPath),
Path.GetFileNameWithoutExtension(fullPath));
var importSrc = engine.CreateScriptSourceFromString(scriptStr,Microsoft.Scripting.SourceCodeKind.File);
importSrc.Execute(scope);

// now you ca execute one-line expressions on the scope e.g.
string expr = "functionOfMyModule()";
var result = engine.Execute(expr, scope);

只要保持加载模块的范围,就可以调用模块的函数而无需重新加载它。

关于c# - C# : a specific problem/question 中的 IronPython 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5292366/

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