2012-09-28 66 views
4

我目前正在測試IronPython(我知道有點C#和一點CPython)。現在我想在Python腳本中使用我的自定義類。在(鐵)Python腳本中引用宿主程序集失敗

我有以下項目結構:

Solution IPTest 
---Project IPTest 
------Namespace IPTest 
---------Program class (main) 
---------Elem class 
------Scripts 
---------Worker.py 

凡ELEM是一個簡單的:

public class Elem { 
    public string Name; 
} 

我可以使用在.NET程序的Python腳本,而不喜歡任何問題:

ScriptEngine engine = Python.CreateEngine(); 
ScriptSource source = engine.CreateScriptSourceFromFile("./Scripts/Worker.py"); 
ScriptScope scope = engine.CreateScope(); 
source.Execute(scope); 
// or var worker = Python.CreateRuntime().UseFile("./Scripts/Worker.py"); 
dynamic Worker = scope.GetVariable("Worker"); 
dynamic worker = Worker(); 
var res1 = worker.add(4, 5); 

但是,我無法弄清楚如何在Python腳本中引用宿主程序集。經過一番研究,我嘗試了以下方法:

import sys 
import System 
sys.path.append(System.IO.Directory.GetCurrentDirectory()) #make sure assembly dir is in sys.path 
import clr 
clr.AddReference(「IPTest.exe」) 
# or clr.AddReferenceToFile(r"IPTest.exe") 
# or clr.AddReference(r"<fullpath>\IPTest\bin\Debug\IPTest.exe") 
# or clr.AddReference(「../IPTest.exe」) #when not adding workingdir to sys.path 
from IPTest import Elem 
# or from IPTest.IPTest import Elem 
# or import Elem 

兩者都不起作用。我得到兩個不同的錯誤信息:

  1. 當添加到工作目錄或sys.path中使用相對路徑,或使用 AddReferenceToFile:無模塊名爲IPTest
  2. 當使用絕對路徑:給定的程序集名稱或代碼庫 是無效。 (異常來自HRESULT:0x80131047)

我檢查了大會名字真IPTest並試圖用一個DLL,而不是exe文件的 - 雖然它一般不應有任何區別,令人驚訝也不管用。

免責聲明:解決方案描述here

engine.Runtime.LoadAssembly(Assembly.GetExecutingAssembly()); //in c# 
from IPTest import Elem # in python script 

的作品就好了。不過,我認爲它也應該通過在腳本文件中引用(這會更好)。

也許我錯過了一些明顯的東西,但我不能看到它,所以任何提示都非常感謝。

回答

3

嘗試clr.AddReferenceToFile(r'IPTest.exe')在你的錯誤中提到:

  1. 當添加到工作目錄或sys.path中使用相對路徑,或使用AddReferenceToFile:沒有模塊名爲IPTest
+0

我要瘋了。 ..我試過'clr.AddReferenceToFile(r「IPTest.exe」)'(與「比」) - 這是行不通的,但是當使用'一切都運行平穩。 – marce

相關問題