ironpython 2.75 在c#中的使用

ironpython的介绍请自行搜索。 一句话,python是一个类似lua js的动态预言。ironpython是在net环境执行python的类库。

效果:在网站中调用一个python文件test.py,test.py引用另一个文件夹下的python文件ceshi.py

调用其中的方法 ceshi.py中的方法。

效果

1 创建一个c#的web网站

2 安装ironpython  Install-Package IronPython

3 网站根下建一个default.aspx的页面

4 创建 pyscripts 文件夹

 pyscripts 文件夹下 ,建一个test.py的文件,

pyscripts 文件夹下,建一个modules文件夹,modules文件夹下建一个ceshi.py的文件和一个__init__.py的文件

整体结构如下

 

代码部分:

default.aspx  

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="pythonscript._default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lab" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>

  default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IronPython.Hosting;

namespace pythonscript
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
              //选项
            Dictionary<string, Object> options = new Dictionary<string, object>();
           options["Debug"] = true;

           //启动ironpython并获取脚本文件对象
           var python = Python.CreateRuntime(options);
           
            string path = AppDomain.CurrentDomain.BaseDirectory + @"pyscripts	est.py";
            dynamic script = python.UseFile(path);

            //调用Python里的类
            var service = script.MyService();
            string result = service.GetData(DateTime.Now.ToString());
            lab.Text = result;
        }
    }
}

  

test.py

先引入sys,然后设置脚本路径,类似windows的各种环境变量如path等。 python将从此处找脚本

然后 引入另一个文件的类 (modules文件夹名,ceshi文件名,Myservice类名) 

# coding=utf-8
import sys
sys.path.append("d:\documents\visual studio 2013\Projects\pythonscript\pythonscript\pyscripts");
from modules.ceshi import MyService  

ceshi.py

一个类 两个方法

import sys

class MyService(object):
    def GetData(self, value):
        return "hello" + value

    def MyFunction(name):
        return "Bye Bye " + name

  

 __init__.py  内容为空即可。也可以设置一些初始设置

原文地址:https://www.cnblogs.com/wang2650/p/5031383.html