c#调用python脚本和动态执行python脚本

/********************************************************************************
** 类名称: Program
** 描述:c#调用python脚本和动态执行python脚本
** 备注:如果调用需引入IronPython.dll、Microsoft.Scripting.dll、Microsoft.Dynamic.dll文件
*********************************************************************************/

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestPython
{
class Program
{
static void Main(string[] args)
{

NetCallPython();
Console.ReadKey();
}

/// <summary>
/// c#调用Python文件中脚本
/// </summary>
static void NetCallPythonFile()
{
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
var source = engine.CreateScriptSourceFromFile(@"C:\Users\rd_guochao_guo\Documents\visual studio 2012\Projects\TestPython\TestPython\hello.py");
source.Execute(scope);
var welcomeFun = scope.GetVariable("welcome");
var str = welcomeFun(11);
Console.WriteLine(str);
}

/// <summary>
/// C#调用Python
/// </summary>
static void NetCallPython()
{
//创建Python引擎
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
string scriptStr = "def add(num1,num2):\n"
+" return num1+num2\n\n"
+"class He(object):\n"
+" def __init__(self,uid):\n"
+" self.uid=1\n"
+" def show(self):\n"
+" return self.uid";

//填充脚本内容
var source = engine.CreateScriptSourceFromString(scriptStr);

//脚本执行
source.Execute(scope);

//调用Python脚本中函数
var addFun = scope.GetVariable("add");
var num = addFun(2, 2);
Console.WriteLine(num);

//调用Python脚本中类中函数
var He = scope.GetVariable("He");
var he = He(1);
var uid = engine.Operations.GetMember(he, "uid");
var uid2 = he.show();
Console.WriteLine(uid2);
}
}
}

posted on 2017-07-25 14:56  伈隨夢飛  阅读(621)  评论(0编辑  收藏  举报

导航