1

I have an embedded resource in my dll which is a python script. I'd like to make the classes and functions in that resource available to the python engine, so I can execute external .py files (as __main__) which would be able to do something like

import embedded_lib # where embedded_lib is an embedded python script

Is there a way to accomplish this? I was hoping there will be some sort of IronPython.ImportModule('module_name', source) so I've looked through IronPython docs and couldn't find anything, but I'm hoping I'm just bad at looking.. Maybe there is some way to intercept a call to import and load my script that way?

1 Answer 1

1

It is possible. You just need to add search paths to ScriptEngine object like this:

var paths = engine.GetSearchPaths();
paths.Add(yourLibsPath); // add directory to search

or

engine.SetSearchPaths(paths);

Then you could use any module in directories, which you add:

import pyFileName # without extension .py

Update OK. If you want to use embedded resource strings like module, you may use this code:

var scope = engine.CreateScope(); // Create ScriptScope to use it like a module
engine.Execute("import clr\n" +
                "clr.AddReference(\"System.Windows.Forms\")\n" +
                "import System.Windows.Forms\n" + 
                "def Hello():\n" +
                "\tSystem.Windows.Forms.MessageBox.Show(\"Hello World!\")", scope); // Execute code from string in scope. 

Now you have a ScriptScope object (scope in code) containing all executed functions. And you may insert them into another scope like this:

foreach (var keyValuePair in scope.GetItems())
{
    if(keyValuePair.Value != null)
        anotherScope.SetVariable(keyValuePair.Key, keyValuePair.Value);
}

Or you can execute your scripts right in this ScriptScope:

dynamic executed = engine.ExecuteFile("Filename.py", scope);
executed.SomeFuncInFilename();

And in this script you may use all functions without import:

def SomeFuncInFilename():
    Hello() # uses function from your scope
Sign up to request clarification or add additional context in comments.

4 Comments

Oh sorry, you whant to use modules from embedded resource... Then I think you may try to execute your embedded resource modules with engine.Execute(string, ScriptScope) and then use its ScriptScope in another executing scripts or files. Or you can always create a temp file with your resource text and use search paths :)
Update your answer accordingly if you think it is answering the question. Add the code to explain it, if needed..
Seems to be working so far, thanks! (Easier than I thought it'd be!)
Is it possible to really use it as a module (I mean with the import keyword?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.