Click here to Skip to main content
15,885,216 members
Articles / Operating Systems / Windows
Article

Call Ironpython in C#

Rate me:
Please Sign up or sign in to vote.
3.33/5 (5 votes)
13 Sep 2006CPOL 52.1K   525   14   3
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.

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

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:

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

History

  • 13th September, 2006: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralCalling Multiple functions from IronPaython using c# Pin
snehat21-Nov-07 0:04
snehat21-Nov-07 0:04 
GeneralIt doesn't support with IronPython 2.0A3 Pin
dreamwinter9-Aug-07 16:58
dreamwinter9-Aug-07 16:58 
GeneralVery useful article! Thanks a lot! Pin
zilibaba24-Nov-06 16:00
zilibaba24-Nov-06 16:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.