现在的位置: 首页 > 综合 > 正文

vb.net / C# 调用 python

2018年04月27日 ⁄ 综合 ⁄ 共 1047字 ⁄ 字号 评论关闭

1.IronPython简介

IronPython
是一种在 .NET 及 Mono上的 Python 实现,由微软的 Jim Hugunin 所发起,是一个开源的项目,基于微软的 DLR 引擎;托管于微软的开源网站 CodePlex(www.codeplex.com)。

2.安装IronPython

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

安装下载下来的安装包(要先装VS)。

3.创建项目

添加引用: 浏览到IronPython的安装目录中,添加对IronPython.dll,Microsoft.Scripting.dll,Microsoft.Dynamic.dll 三个dll的引用。


4.添加Python文件到当前的项目 

创建一个文本文件命名为:test.py,
编辑如下

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

def test():
    return "hello"

5.在vb.net中调用Python方法

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

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

注意:在运行前一定要把hello.py文件设为:Copy always.

Imports IronPython.Hosting
Imports Microsoft.Scripting.Hosting

Public Class Form1
    Dim pyruntime As ScriptRuntime
    Dim obj As Object

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        pyruntime = Python.CreateRuntime()
        obj = pyruntime.UseFile("ttt.py")
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim test As String

        test = obj.test()
        MsgBox(test)
    End Sub
End Class

ironPython安装numpy请看另一篇博客


抱歉!评论已关闭.