2015-09-11 80 views
5

我正在.NET Framework上使用WPF構建GUI。我想要使用C#運行python腳本(使用numpy,scipy等模塊)。 現在,我有兩個選擇。將python模塊轉換爲DLL文件

  1. 過程p = new Process();//通過傳遞必要的參數,如 「python.exe」 和 「filename.py」
  2. 使用IronPython的

使用方法#1是非常簡單,但如果我分發這個應用程序,那麼我的最終用戶必須在我的應用程序中指定的路徑中包含這些Python模塊。 使用方法#2我遇到了那些python模塊的問題,因爲它們沒有附帶IronPython,我需要這些模塊的DLL文件。 那麼有什麼辦法將Python模塊像numpy,scipy轉換成DLL文件?

回答

1

您可以使用clr.CompileModules將python文件轉換爲dll文件。

from System import IO 
from System.IO.Path import Combine 

def walk(folder): 
    for file in IO.Directory.GetFiles(folder): 
    yield file 
    for folder in IO.Directory.GetDirectories(folder): 
    for file in walk(folder): yield file 

folder = IO.Path.GetDirectoryName(__file__) 
all_files = list(walk(Combine(folder, 'moduleName'))) 

import clr 
clr.CompileModules(Combine(folder, "myDll.dll"), *all_files) 

然後,您可以做這樣的事情添加引用您的DLL:您可以通過做這樣的事情的所有文件添加到一個DLL

import clr 
import sys 

sys.path.append(r"C:\Path\To\Dll") 
clr.AddReference("myDll.dll") 

我不但是知道如何訪問該dll中的函數。根據this,您可以通過執行import moduleName來導入它。這雖然對我不起作用。

信息來源:[add files to single dll][reference dll]