C#中调用python

若是须要查看更多文章,请微信搜索公众号 csharp编程大全,须要进C#交流群群请加微信z438679770,备注进群, 我邀请你进群! ! !python

为了记录本身的学习成果,防止遗忘,同时为了帮助在C#学习过程当中遇到一样问题的同志们,因此将原版代码奉上!!!编程

开发环境:vs2015微信

准备工做:函数

  1. 下载并安装Ironpython学习

  2. 建立控制台应用程序spa

  3. 添加文本文件,并命名为test.py对象

  4. 添加引用:引用IronPython.dll,Microsoft.Scripting.dll 两个dll文件blog

     

控制台程序代码:ip

using System;开发

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

//引用须要的命名空间

using IronPython.Hosting;

using Microsoft.Scripting.Hosting;

 

namespace ConsoleApplication3

{

    class Program

    {

        static void Main(string[] args)

        {

            /*执行bin目录下test.py*/

            /*ScriptEngine pyEngine = Python.CreateEngine();//建立Python解释器对象

            dynamic py = pyEngine.ExecuteFile(@"test.py");//读取脚本文件

            int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 };

            string reStr = py.main(array);//调用脚本文件中对应的函数

            Console.WriteLine(reStr);

            Console.ReadKey();*/

            ScriptRuntime pyRunTime = Python.CreateRuntime();

            dynamic obj = pyRunTime.UseFile("test.py");

            Console.WriteLine(obj.welcome(10));

            Console.ReadKey();

        }

    }

}

python程序:

import math

def welcome(value):

    return  math.pi + value

#print(welcome(100))

运行前注意:点击test.py 将复制到输出目录 设置为始终复制

运行:直接按F5

执行效果:

相关文章
相关标签/搜索