1. 程式人生 > >在C#中呼叫python方法

在C#中呼叫python方法

1. 安裝IronPython

2. 建立專案

建立一個C#的控制檯應用程式。

新增引用: 瀏覽到IronPython的安裝目錄中,新增對IronPython.dll,Microsoft.Scripting.dll 兩個dll的引用。

python1

3. 新增Python檔案到當前的專案中

建立一個文字檔案命名為:hello.py, 編輯如下

def welcome(name):
    return "hello" + name

把該檔案新增的當前的專案中。

python2

4. 在C#中呼叫Python方法

python3

首先新增兩個引用:它們定義了Python和ScriptRuntime兩個型別。

第一句程式碼建立了一個Python的執行環境,第二句則使用.net4.0的語法建立了一個動態的物件, OK,下面就可以用這個dynamic型別的物件去呼叫剛才在定義的welcome方法了。

注意:在執行前一定要把hello.py檔案設為:始終複製. 否則執行時會報找不到hello.py檔案,發生異常!

vs2010 原始碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
namespace ConsolePython
{
    class Program
    {
        static void Main(string[] args)
        {
            //第一句程式碼建立了一個Python的執行環境,第二句則使用.net4.0的語法建立了一個動態的物件, OK,
            //下面就可以用這個dynamic型別的物件去呼叫剛才在定義的welcome方法了。
            ScriptRuntime pyRuntime = Python.CreateRuntime();
            dynamic obj = pyRuntime.UseFile("hello.py");

            Console.WriteLine(obj.welcome("  world!"));
            Console.ReadKey();
        }
    }
}