c#利用IronPython调用python的过程种种问题

c#利用IronPython调用python的过程种种问题

  • 小菜鸟一枚,最新学习了Python,感觉语言各种简短,各种第三方类库爽歪歪,毕竟之前是从c#转来的,看到Python的request类各种爽歪歪。就是这么没见识。
  • 然后研究pyqt+eric做gui界面,才知道太他妈的不爽,先不说配环境就能把笨猴累个半死,最终mac系统的也没搞定,于是乖乖win里写。
  • 两天后本猴表示,这种做界面完全违背人生苦短我用Python的宗旨。原先c#可以直接拖拖拖就完事了啊。于是乎研究,是否类库用Python写好,界面用c#,直接调用执行。
  • 万能百度告诉我,还真有前人做了IronPython。激动之余下载安装,然而,你以为的就是你以为的吗?百度看大家各种失败,反正成功的朋友也不贴出来教教我。失望。
  • 五个小时过去了,经历各种问题,我成功了。稍稍记载一下,方便下回再用。

配置过程

安装ironPython

下载最新版应该是IronPython-2.7.x.msi
http://ironpython.net/

打开vs2017各种尝试

  • 在IronPython安装目录中找到如下两项dll

    这里写图片描述

  • 写一个最简单的.py文件待调用

      # -*- coding: utf-8 -*-
      def text():
      	return "我是返回结果"
    
  • 导入c#新建的winform

这里写图片描述

  • 调用前添加两个引用再调用

      using IronPython.Hosting;
      using Microsoft.Scripting.Hosting;
    
  • 要调用的地方如下:

      ScriptRuntime pyRuntime = Python.CreateRuntime();
      dynamic py = pyRuntime.UseFile("mainwindows.py");
      string a = py.text();
      textBox1.AppendText(a);
    

看到编辑框添加的返回文本即成功,剩下不表。

到这一切都很愉快,画风一转:

调用复杂含三方类库的python文件

过程没有截图,无非就是写好函数调用,函数中调用了三方类库requests,然后出错,其他类库也有,出错问题往往是'module' object has no XXXX。

  • 应该是path的问题,按照度娘出的答案各种添加path结果无效,检查路径神都对,依然不行。
    按照cmd下,python,添加打印的所有,这样保险。

      import sys
      print(sys.path)
    
  • 发现本机安装的Python3.5,ironPython默认python2.7,只好再次安装Python2.7共存

安装Python2.7

注意在Python2.7安装目录,把Python.exe不变;在Python3.5安装目录,把Python.exe重命名为

python3.exe。cmd下看Python 和 Python3 弹出版本是否为2.7和3.5。

然后配置Python2和3的环境变量

x:\xxx\Python35
x:\xxx\Python35\Scripts
x:\xxx\Python27
x:\xxx\Python27\Scripts
  • 发现path需要添加更为具体的三方类库的.egg,安装路径又找不到.egg

在Python2.7手动install requests,不可pip,pip貌似找不到egg文件,也许我笨。

不要用这个pip install xxxx,用下面的:

    下载源码,解压
    cmd cd进入目录 python setup.py install

此时添加的完整path有效,在pycharm上测试通过:

# -*- coding: utf-8 -*-
import sys
sys.path.append(r'C:\Python27')
sys.path.append(r'C:\Python27\Lib\DLLs')
sys.path.append(r"C:\Python27\Lib")
sys.path.append(r"C:\Python27\Lib\site-packages")
sys.path.append(r'C:\Python27\Lib\site-packages\requests-2.8.1-py2.7.egg')
import requests

注意切换pycharm调用的Python版本,file--settings--project---project interpreter,选版本。

  • 添加的完整path完成后发现依旧报错** 'module' object has no attribute '_getframe',貌似好多人都是卡在了这一步过不去。**

  • 换用Google,外国大神找到方法,http://stackoverflow.com/questions/6997832/ironpython-sys-getframe-not-found
    总而言之就是当创建PythonEngine时添加字典类型参数options:

      var options = new Dictionary<string, object>();
      options["Frames"] = true;
      options["FullFrames"] = true;
      ScriptEngine engine = Python.CreateEngine(options);
    
  • 试验一下,OK大功告成

源码时间

.py文件

# -*- coding: utf-8 -*-
#添加path
import sys
sys.path.append(r'C:\Python27')
sys.path.append(r'C:\Python27\Lib\DLLs')
sys.path.append(r"C:\Python27\Lib")
sys.path.append(r"C:\Python27\Lib\site-packages")
sys.path.append(r'C:\Python27\Lib\site-packages\requests-2.8.1-py2.7.egg')
import requests

def text():
	return "我是返回结果"			
def getPageIps(url="http://www.66ip.cn/mo.php?sxb=&tqsl=1000&port=&export=&ktip=&sxa=&submit=%CC%E1++%C8%A1&textarea="):
	headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64)"}
	r = requests.get(url,headers=headers)	    
	return r.text

c#文件:

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 WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }	        
        private void button1_Click(object sender, EventArgs e)
        {
            ScriptRuntime pyRuntime = Python.CreateRuntime();
            dynamic py = pyRuntime.UseFile("mainwindows.py");
            string a = py.text();
            textBox1.AppendText(a);	

        }
		private void button2_Click(object sender, EventArgs e)
        {
            //初始化,并添加参数
            var options = new Dictionary<string, object>();
            options["Frames"] = true;
            options["FullFrames"] = true;
            ScriptRuntime pyRuntime = Python.CreateRuntime(options);
            dynamic py = pyRuntime.UseFile("mainwindows.py");
            string a = py.getPageIps();
            textBox1.AppendText(a);		
        }
    }
}

(纯手打,转载时请注意作者和出处)

posted @ 2017-03-08 18:27  monkeyfx  阅读(30030)  评论(12编辑  收藏  举报