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 d_guochao_guoDocumentsvisual studio 2012ProjectsTestPythonTestPythonhello.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): "
+" return num1+num2 "
+"class He(object): "
+" def __init__(self,uid): "
+" self.uid=1 "
+" def show(self): "
+" 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);
}
}
}

原文地址:https://www.cnblogs.com/joyet-john/p/7234091.html