簡體   English   中英

IronPython在C#中的集成:一個特定的問題/問題

[英]IronPython integration in C#: a specific problem/question

我正在通過IronPython為我的C#mapmaking應用程序提供可擴展性機制。 一切正常,但我有一個特定的要求,我無法實現:我希望用戶能夠指定兩件事:

  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);

只要保留模塊加載的scope ,就可以調用模塊的功能而無需重新加載。

我已經對@ digEmAll的代碼進行了一些測試。 首先,我必須說它運行正常,並按照我在問題中提出的要求。 但我擔心你必須打電話

string expr = "functionOfMyModule()";
var result = engine.Execute(expr, scope);

每次要評估用戶定義的表達式時。 我擔心的是代碼不是預編譯的,必須在每次執行時重新解析,這可能會嚴重影響我的應用程序的性能(這些類型的表達式可能被稱為數十萬甚至數百萬次,所以每毫秒計數)。

我嘗試了一個不同的解決方案:簡單地在Python模塊的末尾粘貼用戶定義的表達式(我不是說這適用於所有情況!):

def simpleFunc(x):
    return x + 2;

# this is where the pasting occurs:
simpleFunc(x)

我當時做的是編譯這段代碼:

 ScriptSource source = engine.CreateScriptSourceFromString(myCode);
 CompiledCode compiledCode = source.Compile();

...創建一個范圍並運行它:

 ScriptScope scope = engine.CreateScope();
 scope.SetVariable ("x", 10);
 int result = compiledCode.Execute<int>(scope);

現在,我在相同的代碼片段和相同的表達式上執行了兩個解決方案(digEmAll和我自己的),結果如下:

  • engine.Execute(expr,scope):0.29 ms / run
  • compiledCode.Execute(scope):0.01 ms / run

所以我想我會嘗試使用自己的解決方案,除非代碼粘貼被證明是個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM