How to call python generator in c#

In this post,I will show you how to call python generator in c#.Create a console Application and then right click on the project and add new file fib.py and add following code
class Fib:

    def __init__(self,num):

        self.a=0

        self.b=1

        self.num=num

        self.index=0

    def __iter__(self):

        return self

    def next(self):

        if self.index > self.num:

            raise StopIteration

        else:

            self.index +=1

            self.a,self.b=self.b,self.a+self.b

            return self.a

Open Progrm.cs and add following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Scripting.Hosting;
namespace IronPython_Tut1
{
        class Program
    {
        static void Main(string[] args)
        {
        //Create runtime
            ScriptRuntime runtime = IronPython.Hosting.Python.CreateRuntime();
        //excute 
            ScriptScope scope = runtime.ExecuteFile(@"Fib.py");
        //get the Fib object
            dynamic Fib = scope.GetVariable("Fib");
        foreach (var item in Fib(10))
            {
                Console.WriteLine(item);
            }
          
        }
    }
}


1 comment:

  1. Thanks bro. It is working but i am facing another problem.

    I'm a complete noob when it comes to IronPython. I need to call a py script from an ASP.NET website, and have the following code:
    var ipy = IronPython.Hosting.Python.CreateRuntime();
    dynamic test = ipy.UseFile(Server.MapPath(@"~\python\test.py"));
    test.DoWork();
    The version of IronPython I'm using is 2.7.

    The 3rd party python file I need to call has the following import directives:

    import sys
    from array import *
    from subprocess import *
    I'm receiving the error "No module named subprocess". I've copied the subprocess.py file from the IronPython installation Lib directory, but I assume I need to link to it in the C# code?

    Thanks.

    ReplyDelete