65.9K
CodeProject 正在变化。 阅读更多。
Home

在 C# 中调用 Ironpython

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.33/5 (5投票s)

2006年9月13日

CPOL
viewsIcon

52715

downloadIcon

541

在 C# 中调用 Ironpython

引言

IronPython 是一种优秀的脚本语言,可以用作 .NET 项目中的胶水,尤其是在需要频繁更改的部分,例如由于业务增长或变化,或者在受限的部署环境中。

在本示例中,它将文件头传递给 Python,Python 使用正则表达式解析文件头,并将结果返回给 C# 函数。

public string callPythonFile(string pyFile, Hashtable parameters)
{
    if (!File.Exists(pyFile) )
        return "Can not find "+pyFile;
    PythonEngine pe = new PythonEngine();
    if (parameters != null)
    {
        foreach (string key in parameters.Keys)
            pe.Globals.Add(key, parameters[key]);
    }
    MemoryStream sout = new MemoryStream();
    pe.SetStandardOutput(sout);
    pe.ExecuteFile(pyFile);
    return ASCIIEncoding.ASCII.GetString(sout.ToArray());
}

要运行演示,您需要 .NET 2.0 或 Visual Studio 2005,IronPython 1.0。您需要将 IronPython.dll 复制到测试文件夹。

Python 文件:Test1.py

import re
g=globals()
str=g['param1']
if re.match('...HDR',str):
    print 'HDR'
else:
    print 'NONE'

呼叫

Hashtable ht = new Hashtable();
ht.Add("param1", param1);
outPut=new IronPythonAgent().callPythonFile(pyFile,ht);

历史

  • 2006 年 9 月 13 日:初始发布
© . All rights reserved.