I've had some fun with Python.Net today. I'm sure we can find some use for python scripting some time.
Stepped over a few stones to get a working example running, here's a couple of points:
- import CLR has to be stated to interact with .Net code
- Strings passed to .Net has to be unicode
- Why print doesn't output to Console.Out is still a mystery
And without further ado, here's a Hello World app with a function, a variable and some .Net calls:
using System;
using Python.Runtime;
namespace HelloWorld
{
public class Program
{
static void Main(string[] args)
{
IntPtr gs;
PythonEngine.Initialize();
gs = PythonEngine.AcquireLock();
try
{
int result =
PythonEngine.RunSimpleString(""
+ "import CLR\n"
+ "from CLR.System import Console\n"
+ "from time import time,ctime\n"
+ "def GetHello():\n"
+ " return u'Having spam and eggs at ' + unicode(ctime(time()))\n"
+ "\n"
+ "hello = GetHello()\n"
+ "Console.WriteLine(hello)\n"
);
Console.WriteLine(result);
}
finally
{
PythonEngine.ReleaseLock(gs);
PythonEngine.Shutdown();
}
Console.ReadKey();
}
}
}