环境需要:
1. Visual Studio 2012
2. Ironpython 2.7(下载地址:http://ironpython.codeplex.com/)
搭建步骤:
1. 创建一个C# Console Project(注意需要.NET 4.0)
2. 添加Ironpython.dll和Microsoft.Scripting.dll:
3. 修改App.config:
- <?xml version="1.0"?>
- <configuration>
- <configSections>
- <section
- name="microsoft.scripting"
- type="Microsoft.Scripting.Hosting.Configuration.Section,
- Microsoft.Scripting,
- Version=1.1.0.20,
- PublicKeyToken=7f709c5b713576e1"
- requirePermission="false" />
- </configSections>
- <microsoft.scripting>
- <languages>
- <language
- names="IronPython;Python;py"
- extensions=".py"
- displayName="IronPython 2.7"
- type="IronPython.Runtime.PythonContext,
- IronPython,
- Version=2.7.0.40,
- PublicKeyToken=7f709c5b713576e1" />
- </languages>
- </microsoft.scripting>
- </configuration>
4. 创建PythonScript.py:
- def Test():
- return "Hello world!"
5. 在Program.cs中添加:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Microsoft.Scripting.Hosting;
- namespace AdhocStuff
- {
- class Program
- {
- static void Main(string[] args)
- {
- var scriptName = "PythonScript.py";
- var scriptRuntime = ScriptRuntime.CreateFromConfiguration();
- var pythonEngine = scriptRuntime.GetEngine("Python");
- //var source = pythonEngine.CreateScriptSourceFromFile(scriptName);
- //var scope = pythonEngine.CreateScope();
- dynamic test = scriptRuntime.UseFile(scriptName);
- Console.WriteLine(test.Test().ToString());
- Console.ReadKey();
- }
- }
- }
6. 运行程序
备注:
1、在App.config中的dll版本可以在Reference中获得,dll的Culture并不是必须的,PublicKey何以通过以下方法获得:
2、可能出现的问题
a、创建 microsoft.scripting 的配置节处理程序时出错: 未能加载文件或程序集“Microsoft.Scripting, Version=1.1.0.20, PublicKeyToken=7f709c5b713576e1”或它的某一个依赖项。系统找不到指定的文件。出现这种提示可将IronPython.dll和Microsoft.Scripting.dll地道项目所在的Debug文件夹下。
b、出现找不到PythonScript.py的情况,也可以将.py文件移到Debug下可解决问题。这个感觉还可以更该配置来解决。
参考:http://blog.youkuaiyun.com/mcai4gl2/article/details/8096789