在c#中调用python

来源:互联网 发布:淘宝苏宁易购怎么自提 编辑:程序博客网 时间:2024/05/16 19:25

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

把该文件添加的当前的项目中。


 注意:在运行前一定要把hello.py文件设为:始终复制. 否则运行时会报找不到hello.py文件,发生异常。


4. 在C#中调用Python方法


首先添加两个引用:它们定义了Python和ScriptRuntime两个类型。

第一句代码创建了一个Python的运行环境,第二句则使用.net4.0的语法创建了一个动态的对象, OK,下面就可以用这个dynamic类型的对象去调用刚才在定义的welcome方法了。

VS2013源码:

using IronPython.Hosting;using Microsoft.Scripting.Hosting;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace PythonTest{    class Program    {        static void Main(string[] args)        {            //第一句代码创建了一个Python的运行环境,第二句则使用.net4.0的语法创建了一个动态的对象            //下面就可以用这个dynamic类型的对象去调用刚才定义的welcome方法了。            ScriptRuntime pyRunTime=Python.CreateRuntime();            dynamic obj =pyRunTime.UseFile("hello.py");            Console.WriteLine(obj.welcome("hua"));            Console.ReadKey();        }    }}