2015-11-16 67 views
2

我想在我當前的應用程序中使用IronPython作爲橋將一個非常複雜的Python腳本集成到.NET平臺中。在.NET C中集成Python腳本#

在我的Python腳本我使用NLTK,還有一些其他的字符串分類像sklearn.naive_bayes,這是我進口的:

import nltk 

from nltk.classify.scikitlearn import SklearnClassifier 
import pickle 

from sklearn.naive_bayes import MultinomialNB, BernoulliNB 

from sklearn.linear_model import LogisticRegression, SGDClassifier 

而且我在這個腳本接收的參數字符串,返回一些功能輸出示例:

def testFunction(text): 
    #do some things 
    return somethings 

我想從我的.NET應用程序中調用這個函數,我使用這個代碼調用函數:

 ScriptEngine engine; 
     ScriptScope scope; 
     ScriptSource source; 
     CompiledCode compiled; 

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

     ICollection<string> paths = engine.GetSearchPaths(); 
     string dir = @"C:\Users\Desktop\WinPython-64bit-3.4.3.6\python-3.4.3.amd64\Lib"; 
     paths.Add(dir); 
     string dir2 = @"C:\Users\Desktop\WinPython-64bit-3.4.3.6\python-3.4.3.amd64\Lib\site-packages"; 
     paths.Add(dir2); 

     engine.SetSearchPaths(paths); 

     //loading and compiling code 
     source = engine.CreateScriptSourceFromFile(@"C:\Users\Desktop\script.py"); 


     compiled = source.Compile(); 

     //now executing this code (the code should contain a class) 
     compiled.Execute(scope); 

當我嘗試執行代碼,我得到以下eror:

SyntaxErrorException -> unexpected token 'from'. 

我想打電話給testFunction一個字符串,然後在.NET中使用的輸出,如果該功能。

+0

異常應具有行信息。你可以添加到你的問題?是否有任何庫使用本地模塊/庫?這將是一個問題...... –

+0

據我所知,.NET部分沒有錯.. 因此,錯誤必須在python腳本中。 您是否嘗試過更簡單的事情 - 如 print「test」 – Henrik

+0

爲什麼不使用'Process'實例? –

回答

1

好的。

經過一番澄清評論,我相信我現在就敢回答。

IronPython的是(目前)的IronPython 2.7(對應到Python 2.7) 從這一行:

string dir = @"C:\Users\Desktop\WinPython-64bit-3.4.3.6\python-3.4.3.amd64\Lib"; 

很清楚,你正試圖從蟒蛇加載模塊3.4

在評論中,有人提到Idle用於測試python腳本,但Idle將使用已安裝的Python版本(或者安裝了多個版本,每個版本安裝一個Idle)

在這種情況下,你所使用的Python 3.4

的Python 2.x和Python 3.x都有測試閒置的IDE是兩種不同的編程$ {接口/編譯器/解釋}。用於腳本編寫的語言不是100%相同的。

Python 3不完全向後兼容python 2.由於某些語法被修改。 (與.NET不同,新版本的編譯器支持舊代碼)。

這裏是一些關鍵的不同鏈接: http://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html

嘗試使用ironPython3,而不是IronPython的,它是我的經驗,沒有完全成熟,我也不會在生產環境中尚未使用,但如果你真的依賴python 3模塊,並且需要將python作爲兼容.Net的腳本引擎運行,這是我的建議。

https://github.com/IronLanguages/ironpython3

否則請你幫個忙,並考慮尋找相同的Python模塊爲2.0版本的選項。X兼容 或自己修改,插入Python版本識別塊

How do I check what version of Python is running my script?