1.下载IronPython2.7(http://ironpython.codeplex.com/)
2.安装IronPython2.7
3.VS2010创建Console程式,参考引用C:/Program Files/IronPython 2.7/IronPython*.dll,Microsoft.*.dll
如:
4.Console代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronPython.Hosting;
using IronPython.Compiler;
using IronPython.Modules;
using IronPython.Runtime;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
namespace PythonConsole
{
class Program
{
static void Main(string[] args)
{
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
//注意要有空格 否则会导致缩进对不上位置 即expected an indented block 错误
var py = "def adder(arg1,arg2):\n"+" return arg1 + arg2 \n"+"\n"+"def hello(arg1):\n"+" return 'hello'+arg1 \n"+"\n"+"class MyClass(object):\n"+" def __init__(self,value):\n"+" self.value=value\n"; //__init__ 是两个下划线
var code = engine.CreateScriptSourceFromString(py,SourceCodeKind.Statements);
code.Execute(scope);
var adder = scope.GetVariable<Func<object ,object,object >>("adder");
var hello = scope.GetVariable<Func<object,object>>("hello");
var myClass=scope.GetVariable<Func<object,object>>("MyClass");
var myInstance = myClass("IronPython");
Console.WriteLine(adder(1,2));
Console.WriteLine(hello("Mark"));
Console.WriteLine(engine.Operations.GetMember(myInstance,"value"));
engine.CreateScriptSourceFromString("print 'Hello Python'").Execute();
Console.WriteLine();
engine.Execute("print 'Hello World'"); //严格要求 没有空格的地方不要加空格
Dictionary<string, object> options = new Dictionary<string, object>();
options["Debug"] = true;
ScriptRuntime pyRuntime = Python.CreateRuntime(options);
dynamic scriptScope = pyRuntime.UseFile("TestPython.py");
Console.WriteLine(scriptScope.getYear());
Console.ReadLine();
}
}
}
结果:
本文介绍了如何在Visual Studio 2010的C#项目中使用IronPython库调用和整合Python函数。通过创建Console应用程序,引入IronPython相关DLL,并编写C#代码来执行Python的定义函数、类,以及从外部Python文件导入并执行函数。示例中展示了如何执行Python的加法函数、打印语句,以及实例化Python类。同时强调了`TestPython.py`文件的位置要求,该文件包含一个返回年份的Python函数。

348

被折叠的 条评论
为什么被折叠?



