Advertisement
ProFishChris

HelloPython (Calling Python from C#)

Jun 20th, 2013
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.65 KB | None | 0 0
  1. using System;
  2. using IronPython.Hosting;
  3. using Microsoft.Scripting.Hosting;
  4.  
  5. /* HelloPython.cs
  6.  * Calls functions from an external script written in Python (see end comments)
  7.  * Uses IronPython
  8.  *
  9.  * lots of help/hints from a post by Jeff Mercado on StackOverflow
  10.  * http://stackoverflow.com/questions/7053172/how-can-i-call-ironpython-code-from-a-c-sharp-app
  11.  */
  12.  
  13. namespace HelloPython
  14. {
  15.     class Program
  16.     {
  17.         static void Main(string[] args)
  18.         {
  19.             // Instantiate the engine and create a scope
  20.             ScriptEngine pyEngine = Python.CreateEngine();
  21.             dynamic scriptScope = pyEngine.CreateScope();
  22.  
  23.             // Load a script from file, passing the scope to get variables
  24.             pyEngine.ExecuteFile("HelloPy.py", scriptScope);
  25.  
  26.             // Pull a variable from the scope
  27.             string aMesssage = scriptScope.GetVariable("aMessage");
  28.  
  29.             // Do something with the variable
  30.             Greeter welcomer = new Greeter(aMesssage);
  31.             welcomer.Greet();
  32.  
  33.             // Call a function from the file
  34.             scriptScope.SayHello();
  35.  
  36.             // Call a function that requires variables
  37.             scriptScope.Flatter("Fisher");
  38.  
  39.             // Return a value from a function
  40.             string someMessage = scriptScope.GetMessage();
  41.             welcomer.Message = someMessage;
  42.             welcomer.Greet();
  43.  
  44.         }
  45.     }
  46. }
  47.  
  48.  
  49. /* HelloPy.py
  50.  
  51. import sys
  52.  
  53. aMessage = "Hello, this is Python"
  54.  
  55. def SayHello():
  56.     print "Hello from Python"
  57.  
  58. def Flatter(person):
  59.     print "You look lovely today " + person
  60.  
  61. def GetMessage():
  62.     return "Python says hello"
  63.  
  64.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement