Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!

Dynamically Create a Python Type Within C#

By: ncosentino on Sep 29th, 2013  |  syntax: C#  |  size: 2.13 KB  |  views: 127  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. // -------------------------------------------------------------------------------------
  2. // This is an example from a blog post over at Dev Leader. Check it out:
  3. // http://www.devleader.ca/2013/10/01/dynamic-python-c/
  4. //
  5. // Follow Dev Leader:
  6. // Facebook - http://www.facebook.com/DevLeaderCa
  7. // Google+ - https://plus.google.com/b/108985236662325804542/108985236662325804542/posts
  8. // Twitter - http://www.twitter.com/nbcosentino
  9. // -------------------------------------------------------------------------------------
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Text;
  13. using Microsoft.Scripting.Hosting;
  14.  
  15. using IronPython.Hosting;
  16.  
  17. namespace DynamicScript
  18. {
  19.     internal class Program
  20.     {
  21.         private static void Main(string[] args)
  22.         {
  23.             Console.WriteLine("Enter the text you would like the script to print!");
  24.             var input = Console.ReadLine();
  25.  
  26.             var script =
  27.                 "class MyClass:\r\n" +
  28.                 "    def __init__(self):\r\n" +
  29.                 "        pass\r\n" +
  30.                 "    def go(self, input):\r\n" +
  31.                 "        print('From dynamic python: ' + input)\r\n" +
  32.                 "        return input";
  33.            
  34.             try
  35.             {
  36.                 var engine = Python.CreateEngine();
  37.                 var scope = engine.CreateScope();
  38.                 var ops = engine.Operations;
  39.  
  40.                 engine.Execute(script, scope);
  41.                 var pythonType = scope.GetVariable("MyClass");
  42.                 dynamic instance = ops.CreateInstance(pythonType);
  43.                 var value = instance.go(input);
  44.                
  45.                 if (!input.Equals(value))
  46.                 {
  47.                     throw new InvalidOperationException("Odd... The return value wasn't the same as what we input!");
  48.                 }
  49.             }
  50.             catch (Exception ex)
  51.             {
  52.                 Console.WriteLine("Oops! There was an exception while running the script: " + ex.Message);
  53.             }
  54.  
  55.             Console.WriteLine("Press enter to exit...");
  56.             Console.ReadLine();
  57.         }
  58.     }
  59. }