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 and add following code
class Fib:

    def __init__(self,num):





    def __iter__(self):

        return self

    def next(self):

        if self.index > self.num:

            raise StopIteration


            self.index +=1


            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();
            ScriptScope scope = runtime.ExecuteFile(@"");
        //get the Fib object
            dynamic Fib = scope.GetVariable("Fib");
        foreach (var item in Fib(10))

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\"));
    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 file from the IronPython installation Lib directory, but I assume I need to link to it in the C# code?