2011-11-25 14 views
5

आयरनपीथन का उपयोग करते समय __name__ विशेष चर रिटर्न के बजाय <module> के रूप में होस्ट किया गया। मुझे यहां कुछ चर्चा मिली: http://lists.ironpython.com/pipermail/users-ironpython.com/2006-August/003274.html। लेकिन मैं नहीं जानता कि कैसे मेरे कोड को लागू करने के लिए:आयरनपीथन होस्ट करते समय मैं __name__ को '__main__' पर कैसे सेट करूं?

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

उत्तर

6

आप की मेजबानी एपीआई से थोड़ा अधिक निम्न स्तर कार्यक्षमता का उपयोग करने की आवश्यकता होगी:

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 से लिया।

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