How do I set __name__ to '__main__' when using IronPython hosted?
Asked Answered
G

2

6

When using IronPython hosted the __name__ special variable returns as <module> instead of __main__. I found some discussion here: http://lists.ironpython.com/pipermail/users-ironpython.com/2006-August/003274.html. But I don't know how to apply it to my code:

public static void RunPythonFile(string filename)
{
    // This is the Key to making sure that Visual Studio can debug
    // the Python script. This way you can attach to 3dsMax.exe
    // and catch exceptions that occur right at the correct location 
    // in the Python script. 
    var options = new Dictionary<string, object>();
    options["Debug"] = true;

    // Create an instance of the Python run-time
    var runtime = Python.CreateRuntime(options);

    // Retrive the Python scripting engine 
    var engine = Python.GetEngine(runtime);

    // Get the directory of the file 
    var dir = Path.GetDirectoryName(filename);                       

    // Make sure that the local paths are available.
    var paths = engine.GetSearchPaths();                
    paths.Add(dir);
    engine.SetSearchPaths(paths);

    // Execute the file
    engine.ExecuteFile(filename);
} 
Gules answered 25/11, 2011 at 3:32 Comment(0)
K
7

You'll need to use a bit more low-level functionality from the hosting API:

   ScriptEngine engine = Python.CreateEngine();
   ScriptScope mainScope = engine.CreateScope();

   ScriptSource scriptSource = engine.CreateScriptSourceFromFile("test.py", Encoding.Default, SourceCodeKind.File);

   PythonCompilerOptions pco = (PythonCompilerOptions) engine.GetCompilerOptions(mainScope);

   pco.ModuleName = "__main__";
   pco.Module |= ModuleOptions.Initialize;

   CompiledCode compiled = scriptSource.Compile(pco);
   compiled.Execute(mainScope);

Taken from http://mail.python.org/pipermail/ironpython-users/2011-November/015419.html.

Kartis answered 25/11, 2011 at 18:31 Comment(1)
Not sure what ModuleOptions.Initialize does exactly, but for me it is not needed to get name set to pco.ModuleName.Pollinate
S
3
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
scope.SetVariable("__name__", "__main__");
var scr = engine.CreateScriptSourceFromString("print __name__", SourceCodeKind.Statements);
scr.Execute(scope);

and from file:

var scr = engine.CreateScriptSourceFromFile(fname, Encoding.UTF8, SourceCodeKind.Statements);
Stroup answered 17/9, 2012 at 13:45 Comment(1)
This works, but using Statements for a file also has side effects like not populating __file__Pollinate

© 2022 - 2024 — McMap. All rights reserved.