[Mono-list] IronPython ImportError - only when running as a service

David Jagoe davidjagoe at gmail.com
Sun Nov 21 04:35:33 EST 2010


G'day all,

I am embedding IronPython in a C# application and using the
Microsoft.Scripting tools (code posted below). The Python code
I'm embedding is trivially simple:

print "Running main.py"

import sys
print sys

# Exceptions not shown when running mono-service
try:
    import time
    print time
except Exception, e:
    print e

print "done"

This works ok if I compile and execute the code as a stand-alone
executable.

However, if I run the code as a service (using System.ServiceProcess),
I manage to import sys but not time, even though they are both
built-in modules. I see the following error: 'No module named time'

I have also run this in Windows as a service with the same result, so it seems
like a feature rather than a bug.

I would be most grateful if anyone can explain the situation or tell
me what I'm doing wrong.


Cheers,
David



using System;
using System.ServiceProcess;

namespace Sample
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            System.ServiceProcess.ServiceBase[] ServicesToRun;
            ServicesToRun = new System.ServiceProcess.ServiceBase[] {
                new SampleService() };
            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
        }
    }
}


using System;
using System.ServiceProcess;
using System.Timers;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
using IronPython.Runtime;
using System.Reflection;
using System.IO;

namespace Sample
{

    public partial class SampleService : ServiceBase
    {
        private runtime;

        public SampleService()
        {
        string codebase = Assembly.GetAssembly(typeof(MainClass)).CodeBase;
	UriBuilder uri = new UriBuilder(codebase);
	string path = Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path));
	string pythonPath = Path.Combine(path, "Python");
	ScriptRuntime runtime = Python.CreateRuntime();
	ScriptEngine engine = runtime.GetEngine("python");
	System.Collections.Generic.ICollection<string> search_paths =
engine.GetSearchPaths();
	search_paths.Add(pythonPath);
	engine.SetSearchPaths(search_paths);
        runtime.ExecuteFile(Path.Combine("Python", "main.py"));
        }


More information about the Mono-list mailing list