IronPython在C#中的集成:一个特定的问题 [英] IronPython integration in C#: a specific problem/question
问题描述
我正在努力通过IronPython为我的C#地图制作应用程序提供可扩展性机制.一切正常,但是我有一个具体的要求,我在实施时遇到了麻烦:我希望用户能够指定两件事:
I'm working on providing an extensibility mechanism for my C# mapmaking application through IronPython. Everything works fine, but I have a specific requirement which I'm having trouble implementing: I want the user to be able to specify two things:
- 要加载的Python脚本的文件名
- 包含Python脚本的单行字符串,通常是该Python文件中的函数调用(示例
getTextLabel(element)
)
这两个设置必须分开,但是我不知道是否可以使用PythonScript
和相关类来做到这一点.
These two settings must be separate, but I don't know if it is possible to do this using PythonScript
and related classes.
我是Python的新手,也许还有另一种方法可以实现这一目标?出于性能方面的考虑,我希望避免多次加载和编译Python脚本文件(因为可能存在上述几种不同的函数调用"设置,并且如果可能的话,我想为该文件重用CompiledCode
实例).
I'm a newbie in Python, perhaps there is another way to achieve this? For performance reasons I want to avoid loading and compiling the Python script file several times (since there could be several above mentioned different "function call" settings and I want to reuse the CompiledCode
instance for the file if possible).
更新: @digEmAll 为我的问题给出了正确答案,因此我接受它为有效答案.但是,如果您担心性能,还应该查看我自己的答案.
UPDATE: @digEmAll gave the correct answer to my question, so I'm accepting it as a valid answer. But if you are concerned with performance, you should also check out my own answer.
推荐答案
您可以执行以下操作:
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);
只要将scope
保留在模块的加载位置,就可以调用模块的功能而无需重新加载模块.
As long as you keep the scope
where the module is loaded, you can call functions of the module without reloading it.
这篇关于IronPython在C#中的集成:一个特定的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!