Simple IronPython and C# Interaction Example

by rsutton 29. July 2009 01:47

I have yet to find a simple example of executing an IronPython script from C#, so here is mine.  Note that the Project I created is called ByFeatureApp and the WebScrapper class is public.  I also show setting a variable (the) in C# and then the python script prints the value.

 

C# Code

namespace ByFeatureApp

{

    class Program

    {

        static void Main(string[] args)

        {

            var the = "hello I'm the the string";

 

            var engine = Python.CreateEngine();

            var source = engine.CreateScriptSourceFromFile("Scripts\\test.py");

            var scope = engine.CreateScope();

            source.Engine.SetVariable(scope, "the", the);

            source.Execute(scope);

 

            Console.ReadLine();

        }

    }

 

    public class WebScraper

    {

        public void LoadUrl(string url)

        {

            Html = new WebClient().DownloadString(url);

        }

 

        public string Html { get; set; }

    }

}

 

IronPython Script

import clr

clr.AddReference('ByFeatureApp')

from ByFeatureApp import *

 

print the

 

ws = WebScraper()

ws.LoadUrl('http://www.barchart.com')

 

istart = ws.Html.find('<tr><td><a href="http://quote.barchart.com/quote.asp?sym=GCQ9">Gold</a>')

iend = ws.Html.find('</tr>', istart)

 

print ws.Html[istart:iend+5]

 

Anyway I hope this is useful.

Tags:

Development

Comments

Comments are closed

Powered by BlogEngine.NET 1.4.5.0
Theme by Extensive SEO

Profile

Member of the Church of Jesus Christ of Latter-Day Saints, Developer and IT Professional