【问题标题】:How do I set __name__ to '__main__' when using IronPython hosted?使用 IronPython 托管时,如何将 __name__ 设置为 '__main__'?
【发布时间】:2012-01-06 01:37:27
【问题描述】:

使用 IronPython 托管时,__name__ 特殊变量返回为 <module> 而不是 __main__。我在这里找到了一些讨论:http://lists.ironpython.com/pipermail/users-ironpython.com/2006-August/003274.html。但我不知道如何将它应用到我的代码中:

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);
} 

【问题讨论】:

    标签: c# scripting ironpython


    【解决方案1】:
    var engine = Python.CreateEngine();
    var scope = engine.CreateScope();
    scope.SetVariable("__name__", "__main__");
    var scr = engine.CreateScriptSourceFromString("print __name__", SourceCodeKind.Statements);
    scr.Execute(scope);
    

    来自文件:

    var scr = engine.CreateScriptSourceFromFile(fname, Encoding.UTF8, SourceCodeKind.Statements);
    

    【讨论】:

    • 这行得通,但对文件使用Statements 也有副作用,例如不填充__file__
    【解决方案2】:

    您需要使用托管 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);
    

    取自http://mail.python.org/pipermail/ironpython-users/2011-November/015419.html。

    【讨论】:

    • 不确定 ModuleOptions.Initialize 究竟做了什么,但对我来说,不需要将 name 设置为 pco.ModuleName。
    猜你喜欢
    • 2011-06-16
    • 2023-03-30
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多