在C#中调用python方法

来源:互联网 发布:屋顶光伏支架技术数据 编辑:程序博客网 时间:2024/06/06 08:27

1. 安装IronPython

http://ironpython.codeplex.com/下载。

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

0 0