[Python.NET] Application scripting - Embedding/Extending Python.
solution
Sam Iredale
gyrepin at techie.com
Mon Aug 9 23:28:56 CEST 2004
I got it working. Here's my sample code:
using System;
using Python.Runtime;
namespace PyTest
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class PyTestClass
{
PyObject module = null;
PyObject func = null;
PyTestClass()
{
PythonEngine.Initialize();
}
~PyTestClass()
{
PythonEngine.Finalize();
}
void Scratch()
{
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
try
{
// initiliaze the engine
PyTestClass pyTest = new PyTestClass();
if(!PythonEngine.IsInitialized)
throw new
Exception("PythonEngine not initialized.");
// load the module and the dictionary
pyTest.module =
PythonEngine.ImportModule("PyTest");
// get a reference to the function named
"test" from the Python script
pyTest.func =
pyTest.module.GetAttr((string) "test");
// if the reference we got in the above
call in callable, call it.
if(pyTest.func.IsCallable())
{
PyObject[] obj = new
PyObject[1]; // an array of objects representing the function arguments
PyTuple tup; // we'll pass the
arguments to the funciton in a tuple
// convert our string into a
PyObject and place it in the array
obj[0] =
PyObject.FromManagedObject((string) "Embedding and Extending.");
// convert the array of
PyObjects into a single PyTuple
tup = new PyTuple(obj);
// call the Ivoke method of the
funciton reference with the tuple containing
// the function arguements.
pyTest.func.Invoke(tup);
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.Write(e.StackTrace);
}
}
}
public class PyTestInterface
{
public PyTestInterface()
{
// do nothing, just making a public constructor
}
public void PyTestMsg(string testname)
{
Console.WriteLine("Test Pass! " + testname);
}
}
}
And here's the sample Python script:
import CLR # gives this Python script access to managed namespaces
from CLR.System.Reflection import Assembly # for importing managed
assemblies
asm = Assembly.LoadWithPartialName("PyTest.exe")
from CLR.PyTest import PyTestInterface # mports the interface for this
applicaiton
iface = PyTestInterface()
def test(str):
print "testing:"
iface.PyTestMsg(str)
print "test finished.";
test("Extending")
I hope this helps someone out there. There are certainly a number of
ways this can be done. But this specific approach leads me in the
direction I need to go in order to solve the problems I want to solve.
SI
More information about the PythonDotNet
mailing list