Oscar Johansson
Oscar Johansson

Reputation: 145

Unable to run python scripts with libraries using IronPython in Visual Studio

I have tried running python scripts in Visual studio with IronPython and it goes well until I try to use any library in the python script, using this code.

var ipy = Python.CreateRuntime();
dynamic test = ipy.UseFile("C:/Python/Test.py");
var whatever = test.python_string();
MessageBox.Show(whatever);

And Test.py looks like this.

def python_string():
    return "Okay"

As soon as I try to add

from moviepy.editor import *

or any other libary import statement to the python code the Visual Studio program won't execute.

I am using Visual Studio 2015 and I set up IronPython exactly as shown on their website. I am guessing I have to add the library to some place in Visual Studio but I have no idea where or how.

Hope I made this clear. Thanks in advance.

Upvotes: 1

Views: 1709

Answers (2)

SoreDakeNoKoto
SoreDakeNoKoto

Reputation: 1185

I had this same issue while using SharpDevelop. Follow the instructions here and create class libraries (DLLs) for your external modules/packages. Add the output DLLs to your project references. Then in your C# main(), load those assemblies like this:

// make sure to include "using System.IO"

string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "serial.dll");            
engine.Runtime.LoadAssembly(Assembly.LoadFile(path));

Where engine refers to your Python ScriptEngine.

I used this to build an assembly for the pyserial module and include them in a C#/IronPython project. I don't know if there's a better way but after hours of frustration, this is what worked for me.

Upvotes: 1

Lord Drake
Lord Drake

Reputation: 182

When I had this issue, there was another question of a similar nature on Stack somewhere, but I'm not having any luck finding it right now. (If anyone comes across it please drop a link in the comments.)

The way I got it working was by adding paths to the script engine, like so.

        ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null);
        ScriptRuntime runtime = new ScriptRuntime(setup);
        ScriptEngine engine = Python.GetEngine(runtime);

        var paths = engine.GetSearchPaths();
        paths.Add(prod.GetImportScope());
        paths.Add(AppDomain.CurrentDomain.BaseDirectory + "Lib");
        paths.Add(AppDomain.CurrentDomain.BaseDirectory + "selenium");
        engine.SetSearchPaths(paths);

When you run a script in IronPython, it's not running in the usual scope that a Python file would. So you have to tell it where to find the Python StdLib and any other files that you're importing. Even if the script runs fine on it's own, it will not in IronPython without telling it where to find its resources.

I'm not an IronPython expert, so there is probably a more efficient way to do this.

Upvotes: 0

Related Questions