65.9K
CodeProject is changing. Read more.
Home

Call Ironpython in C#

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.33/5 (5 votes)

Sep 13, 2006

CPOL
viewsIcon

52473

downloadIcon

526

Call ironpython in C#

Introduction

Ironpython is a good script language to be used as a glue in .NET projects, especially in the parts that need to be changed frequently due to business growing or changing, or in restricted deployment environments.

In this sample, it passes the file header to python, python parses the header with regex and returns to C# function.

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());
}

To run the demo, you need .NET 2.0 or Visual Studio 2005, IronPython 1.0. You need to copy IronPython.dll to the test folder.

Python file: Test1.py

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

Call:

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

History

  • 13th September, 2006: Initial post