C# 调用Python库 最简单方法

  起个头,技术性文章应该言简意赅(因我看到外国回答问题都是可以一句代码解决的,绝不会写第二句),实现功能无误再贴出文章。

  首先我不用 IronPython来写这个.py文件,因为我有Pycharm,而且ipy需要配置某些环境,且代码没有提示,不推荐。

  直入主题:

  1.安装IronPython并在其路径下找到找到这两个dll,并复制到代码对应路径下。

  2.引用,添加引用,在刚才的路径找到即可。

  3.py写个简单的函数,简单能运行,函数有个返回值就行。

  4.项目中添加新文件夹,右键打开文件路径,将.py文件复制进去。

  5.引用空间。

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

  6.我这里创建的是窗体的一个项目。其中这两行是对python的链接,创建和配置环境,obj就是这个.py文件的实例了。

            ScriptRuntime pyRunTime = Python.CreateRuntime();
            dynamic obj = pyRunTime.UseFile(pyPath+"IronPy_Test.py");
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

namespace WinForm_ipy
{
    
    public partial class Form1 : Form
    {
        //这是.py文件的路径
        string pyPath = "C:\\Users\\hongheng.mei\\Desktop\\InronPy\\WinForm_ipy\\WinForm_ipy\\PythonFiles\\";
        public Form1()
        {
            InitializeComponent();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            ScriptRuntime pyRunTime = Python.CreateRuntime();
            dynamic obj = pyRunTime.UseFile(pyPath+"IronPy_Test.py");
            var value = obj.Hello();
            tbxDisplay.Text = value;
            MessageBox.Show(value);

        }
    }
}

7.关于有些人要设置.py文件属性为始终复制,而我是默认的不复制也能正常运行,这我没弄清楚。

8.最后就是运行效果。

扫描二维码关注公众号,回复: 5372266 查看本文章

  最后,程序员的生命是有限的,何必看长篇大论。

猜你喜欢

转载自www.cnblogs.com/lorzen/p/10457357.html
今日推荐