Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using IronPython.Hosting;
- using Microsoft.Scripting.Hosting;
- /* HelloPython.cs
- * Calls functions from an external script written in Python (see end comments)
- * Uses IronPython
- *
- * lots of help/hints from a post by Jeff Mercado on StackOverflow
- * http://stackoverflow.com/questions/7053172/how-can-i-call-ironpython-code-from-a-c-sharp-app
- */
- namespace HelloPython
- {
- class Program
- {
- static void Main(string[] args)
- {
- // Instantiate the engine and create a scope
- ScriptEngine pyEngine = Python.CreateEngine();
- dynamic scriptScope = pyEngine.CreateScope();
- // Load a script from file, passing the scope to get variables
- pyEngine.ExecuteFile("HelloPy.py", scriptScope);
- // Pull a variable from the scope
- string aMesssage = scriptScope.GetVariable("aMessage");
- // Do something with the variable
- Greeter welcomer = new Greeter(aMesssage);
- welcomer.Greet();
- // Call a function from the file
- scriptScope.SayHello();
- // Call a function that requires variables
- scriptScope.Flatter("Fisher");
- // Return a value from a function
- string someMessage = scriptScope.GetMessage();
- welcomer.Message = someMessage;
- welcomer.Greet();
- }
- }
- }
- /* HelloPy.py
- import sys
- aMessage = "Hello, this is Python"
- def SayHello():
- print "Hello from Python"
- def Flatter(person):
- print "You look lovely today " + person
- def GetMessage():
- return "Python says hello"
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement