static void Main(string[] rawArgs) { List<string> args = new List<string>(rawArgs); args.Insert(0, Application.ExecutablePath); PythonEngine engine = new PythonEngine(); engine.AddToPath(Path.GetDirectoryName(Application.ExecutablePath)); engine.Sys.argv = List.Make(args); EngineModule engineModule = engine.CreateModule("__main__", new Dictionary<string, object>(), true); engine.DefaultModule = engineModule; string path = Path.Combine( Path.GetDirectoryName(Application.ExecutablePath), "main.py"); engine.ExecuteFile(path); }
private static int RunFile(PythonEngine engine, ArrayList args) { string fileName = (string)args[0]; if (fileName == "-") { fileName = "<stdin>"; } else { if (!File.Exists(fileName)) { Console.WriteLine("File {0} does not exist", fileName); System.Environment.Exit(1); } engine.AddToPath(Path.GetDirectoryName(Path.GetFullPath(fileName))); } engine.AddToPath(Environment.CurrentDirectory); InitializePath(engine); InitializeModules(engine); ImportSite(engine); int result = 1; if (HandleExceptions) { try { result = engine.RunFileInNewModule(fileName, args, introspection, skipLine); } catch (Exception e) { engine.DumpException(e); } finally { engine.DumpDebugInfo(); } } else { try { result = engine.RunFileInNewModule(fileName, args, introspection, skipLine); } finally { engine.DumpDebugInfo(); } } if (PressKeyToContinue) { WaitForAnyKey(); } return(result); }
public void SetPath(PythonEngine engine, String rootPath) { engine.AddToPath(rootPath); // This path entry allows the framework modules to be loaded from // rootPath/bin/Lib engine.Sys.prefix = Path.Combine(rootPath, "bin"); string libpath = Path.Combine(Path.Combine(rootPath, "bin"), "Lib"); engine.AddToPath(libpath); // This path entry allows the application specific modules to be // loaded from rootPath/wsgiapp. This allows seperation of the // the framework and application. engine.AddToPath(Path.Combine(rootPath, "wsgiapp")); }
// This is called when the python extension is first loaded. public static void LoadExtension() { WriteOutput("IronPython-Mdbg Extension loaded"); g_python = new IronPython.Hosting.PythonEngine(); g_pythonInteractive = new PythonCommandLine(g_python); string ver = g_python.GetType().Assembly.GetName().Version.ToString(); WriteOutput(MDbgOutputConstants.Ignore, "Binding against Iron Python version: " + ver); // Get original load command, for use in python load command. g_origLoadCmd = Shell.Commands.Lookup("load"); // Add Python extension commands to Shell.Commands. MDbgAttributeDefinedCommand.AddCommandsFromType(Shell.Commands, typeof(PythonExt)); // Add the current directory to the python engine search path. g_python.AddToPath(Environment.CurrentDirectory); // Tell Python about some key objects in Mdbg. Python can then reflect over these objects. // These variables live at some special "main" scope. Python Modules imported via python "import" command // can't access them. Use PythonEngine.ExecuteFile() to import files such that they can access these vars. g_python.Globals.Add("CommandBase", IronPython.Runtime.Types.ReflectedType.FromType(typeof(CommandBase))); // Hook input + output. This is redirecting pythons 'sys.stdout, sys.stdin, sys.stderr' // This connects python's sys.stdout --> Stream --> Mdbg console. MDbgStream s = new MDbgStream(); // New codepaths for IronPython 1.0 g_python.SetStandardInput(s); g_python.SetStandardOutput(s); g_python.SetStandardError(s); }
private void GetPythonEngine(out PythonEngine engine, out MemoryStream output) { engine = new PythonEngine(); engine.Execute("import clr"); foreach (DirectoryInfo di in m_SearchPath) { if (di.Exists) { engine.AddToPath(di.FullName); } } foreach (string name in m_Globals.Keys) { if (!engine.Globals.ContainsKey(name)) { engine.Globals.Add(name, m_Globals[name]); } else { engine.Globals[name] = m_Globals[name]; } } output = new MemoryStream(); MemoryStream error = new MemoryStream(); engine.SetStandardOutput(output); engine.SetStandardError(error); }
private static void ImportSite(PythonEngine engine) { if (!Options.ImportSite) { return; } string site = System.Reflection.Assembly.GetExecutingAssembly().Location; site = Path.Combine(Path.GetDirectoryName(site), "Lib"); engine.AddToPath(site); engine.ImportSite(); }
private static void InitializePath(PythonEngine engine) { if (Options.IgnoreEnvironmentVariables) { return; } string path = Environment.GetEnvironmentVariable("IRONPYTHONPATH"); if (path != null && path.Length > 0) { string[] paths = path.Split(';'); foreach (string p in paths) { engine.AddToPath(p); } } }
private static int RunInteractive(PythonEngine engine) { string version = InitializeModules(engine); engine.AddToPath(Environment.CurrentDirectory); InitializePath(engine); ImportSite(engine); AppDomain.CurrentDomain.UnhandledException += engine.DefaultExceptionHandler; engine.MyConsole.WriteLine(version, Style.Out); engine.MyConsole.WriteLine(PythonEngine.Copyright, Style.Out); RunStartup(engine); int result = engine.RunInteractive(); engine.DumpDebugInfo(); return(result); }
private void GetPythonConsoleEngine(out PythonEngine engine) { engine = new PythonEngine(); //engine.Execute("import clr"); foreach (DirectoryInfo di in m_SearchPath) { if (di.Exists) { engine.AddToPath(di.FullName); } } foreach (string name in m_Globals.Keys) { if (!engine.Globals.ContainsKey(name)) { engine.Globals.Add(name, m_Globals[name]); } else { engine.Globals[name] = m_Globals[name]; } } }
private static int RunString(PythonEngine engine, string command, ArrayList args) { engine.AddToPath(Environment.CurrentDirectory); InitializePath(engine); InitializeModules(engine); ImportSite(engine); int result = 1; args[0] = "-c"; engine.Sys.argv = IronPython.Runtime.List.Make(args); if (HandleExceptions) { try { result = engine.Execute(command); } catch (Exception e) { engine.DumpException(e); } finally { engine.DumpDebugInfo(); } } else { try { result = engine.Execute(command); } finally { engine.DumpDebugInfo(); } } if (PressKeyToContinue) { WaitForAnyKey(); } return(result); }
private PuffinPython() { if (srcDir == null || srcDir.Length == 0) { srcDir = @"c:\bbd\python\source"; } if (runDir == null || runDir.Length == 0) { runDir = @"c:\bbd\python\runtime"; } engine = new PythonEngine(); sbout = new MemoryStream(); sberr = new MemoryStream(); loaded = new StringBuilder(); EngineModule agent = engine.CreateModule("agentModule", true); puffinAgent = new PuffinAgent(); agent.Globals.Add("agent", puffinAgent); engine.SetStandardOutput(sbout); engine.SetStandardError(sberr); engine.AddToPath(runDir); WritePy("INTRINSICS", Code()); WriteDB(); }
/// <summary> /// Initializes main IronPythonEngine and loads pswrdgen.py variables /// </summary> private void bootstrap() { try { //Let check and make sure the user has Python24 if (!Directory.Exists("C:\\Python24\\Lib")) { DialogResult dResult = MessageBox.Show("C:\\Python24\\Lib not found.\r\npswrdgeniron needs Python24 to run. Do you want to download Python24?", "Python 2.4 Not Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (dResult == DialogResult.Yes) { System.Diagnostics.Process.Start(@"http://www.python.org/download/releases/2.4.4/"); } else { return; } } //Start importing pswrdgen.py to IronPython pe.ExecuteCommand("import sys"); pe.AddToPath("C:\\Python24\\Lib"); pe.AddToPath(Application.StartupPath);//add the windows installation path so no errors when using shortcuts pe.ExecuteCommand("import os"); pe.ExecuteCommand("import pswrdgen"); pe.ExecuteCommand("i = pswrdgen.pswrdgen()"); //Get version number of current file currentversion = pe.EvaluateAs <string>("pswrdgen.__version__"); //Get url string url = pe.EvaluateAs <string>("pswrdgen.__url__"); //Display some info to user... tbDisplay.AppendText("*************************************************************************\r\n"); tbDisplay.AppendText("pswrdgeniron: " + url + "\r\npswrdgen.py version " + currentversion + " on \r\n" + pe.VersionString + "\r\n"); tbDisplay.AppendText(pe.EvaluateAs <string>(@"pswrdgen.__doc__") + "\r\n"); tbDisplay.AppendText("*************************************************************************\r\n"); //Get the pswrdgen.py defaults values and assign them to the C# equivalent variables SWAPS = (PythonDictionary)pe.EvaluateAs <PythonDictionary>("i.SWAPS").Clone(); MINLENGTH = (int)pe.EvaluateAs <object>("i.MINLENGTH"); MAXLENGTH = (int)pe.EvaluateAs <object>("i.MAXLENGTH"); CAPLENGTH = (int)pe.EvaluateAs <object>("i.CAPLENGTH"); GENCOUNT = (int)pe.EvaluateAs <object>("i.GENCOUNT"); ADDCHAR = (string)pe.EvaluateAs <object>("i.ADDCHAR"); ADDCOUNT = (int)pe.EvaluateAs <object>("i.ADDCOUNT"); WORDFILELISTS = (List)pe.EvaluateAs <List>("i.WORDFILELISTS"); //*** Update the controls to display to user //Display the current SWAP PythonDictionary ruleset tbSwapSet.Text = SWAPS.ToString(); //Display the current ADDCHAR ruleset tbInsertionChars.Text = ADDCHAR; //Update cbMinLength and the Event will update cbMaxLength and cbCaps int numbers = 3; if (MINLENGTH <= MAXLENGTH) { //Populate the choices for MinLength while (numbers <= 25) { cbMinLength.Items.Add(numbers); numbers = numbers + 1; } cbMinLength.SelectedItem = MINLENGTH; cbMaxLength.SelectedItem = MAXLENGTH; cbCaps.SelectedItem = CAPLENGTH; //Populate the choices for MinLength numbers = 1; while (numbers <= 101) { cbGencount.Items.Add(numbers); numbers = numbers + 1; } cbGencount.SelectedItem = GENCOUNT; //Populate the choices for AddCount numbers = 0; while (numbers <= 40) { cdAddCount.Items.Add(numbers); numbers = numbers + 1; } cdAddCount.SelectedItem = ADDCOUNT; //Make bUpdate button enabled false since their were no changes // this must be done after its data population bUpdate.Enabled = false; bSavesettings.Enabled = false; } else { MessageBox.Show("MINLENGTH > MAXLENGTH ; Can not populate cbMinLength"); } //update the file list combobox IEnumerator listenum = WORDFILELISTS.GetEnumerator(); while (listenum.MoveNext()) { cbWordFiles.Items.Add(listenum.Current); } cbWordFiles.SelectedIndex = 0; } catch (Exception ex) { MessageBox.Show("bootstrap error:\r\n" + ex.Message + "\r\n" + ex.InnerException); } }
private PuffinPython() { if (srcDir == null || srcDir.Length == 0) srcDir = @"c:\vlab\python\source"; if (runDir == null || runDir.Length == 0) runDir = @"c:\vlab\python\runtime"; engine = new PythonEngine(); sbout = new MemoryStream(); sberr = new MemoryStream(); loaded = new StringBuilder(); EngineModule agent = engine.CreateModule("agentModule", true); puffinAgent = new PuffinAgent(); agent.Globals.Add("agent", puffinAgent); engine.SetStandardOutput(sbout); engine.SetStandardError(sberr); engine.AddToPath(runDir); WritePy("INTRINSICS", Code()); WriteDB(); }
public void Initialize(string[] args) { if (args.Length == 1 && args[0] == "/reset") { Properties.Settings.Default.Reset(); } m_baseServicesDispatcher = new BaseServicesDispatcher(); // Init mainwindow and display m_mainWindow = new MainWindow(this); m_paragraphContainer = new ParagraphContainer(); m_mainWindow.TextView.ParagraphContainer = m_paragraphContainer; ChiConsole.SetChiConsole(this); // Initialize ironpython IronPython.Compiler.Options.GenerateModulesAsSnippets = true; /* IronPython.Compiler.Options.GenerateDynamicMethods = false; * IronPython.Compiler.Options.DebugMode = true; * IronPython.Compiler.Options.EngineDebug = true; * IronPython.Compiler.Options.ILDebug = true; * IronPython.Compiler.Options.Frames = true; */ m_pythonEngine = new PythonEngine(); //m_pythonEngine.CreateModule("globals", true); ChiPythonStream s = new ChiPythonStream(); m_pythonEngine.SetStandardOutput(s); m_pythonEngine.SetStandardError(s); m_pythonEngine.SetStandardInput(s); m_pythonEngine.AddToPath(Application.StartupPath + "/lib"); #if DEBUG m_pythonEngine.AddToPath(@"../../../scripts/lib"); #endif m_pythonEngine.LoadAssembly(typeof(TriggerManager).Assembly); // load ChiropteraBase m_pythonEngine.LoadAssembly(typeof(System.Drawing.Bitmap).Assembly); // load System.Drawing m_pythonEngine.LoadAssembly(typeof(System.Windows.Forms.Keys).Assembly); // load System.Windows.Forms // Network m_telnet = new Telnet(); m_telnet.connectEvent += new Telnet.ConnectDelegate(_ConnectEvent); m_telnet.disconnectEvent += new Telnet.DisconnectDelegate(_DisconnectEvent); m_telnet.receiveEvent += new Telnet.ReceiveDelegate(_ReceiveEvent); m_telnet.promptEvent += new Telnet.PromptDelegate(_PromptEvent); m_telnet.telnetEvent += new Telnet.TelnetDelegate(_TelnetEvent); m_commandManager = new CommandManager(m_baseServicesDispatcher); AddBuiltinCommands(); m_triggerManager = new TriggerManager(m_baseServicesDispatcher); m_triggerManager.SetTriggers(Properties.Settings.Default.Triggers); m_hiliteManager = new HiliteManager(m_triggerManager); m_keyManager = new KeyManager(m_baseServicesDispatcher); m_keyManager.SetKeyBindings(Properties.Settings.Default.KeyBindings); PythonInterface.Initialize(m_baseServicesDispatcher, m_triggerManager, m_commandManager, this, this, m_pythonEngine, m_keyManager, m_hiliteManager); try { #if DEBUG PythonInterface.RunScript(Path.GetFullPath("../../../scripts/std/init_std.bc")); #else PythonInterface.RunScript(Path.Combine(Environment.CurrentDirectory, "std/init_std.bc")); #endif } catch (Exception e) { ChiConsole.WriteError("Error running init_std.bc", e); } try { string userScript = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Chiroptera/init.bc"); if (File.Exists(userScript)) { PythonInterface.RunScript(userScript); } } catch (Exception e) { ChiConsole.WriteError("Error running init.bc", e); } Version currentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; Version baseVersion = System.Reflection.Assembly.GetAssembly(typeof(Telnet)).GetName().Version; ChiConsole.WriteLine("Chiroptera version {0} (base {1})", currentVersion.ToString(2), baseVersion.ToString(2)); ChiConsole.WriteLine("Using {0}", PythonEngine.VersionString); CheckClientVersion(); }
public void PostInitialise() { m_log.Info("[PYTHON] Initialising IronPython engine."); m_python = new PythonEngine(); m_python.AddToPath(System.Environment.CurrentDirectory + System.IO.Path.DirectorySeparatorChar + "Python"); }
public frmMain() { InitializeComponent(); //DirectoryInfo di = new DirectoryInfo(); outstream = new MyStream(Shell); Shell.CommandEntered += new UILibrary.EventCommandEntered(Shell_CommandEntered); engine = new PythonEngine(); engine.AddToPath(Environment.CurrentDirectory); string exepath = Environment.CurrentDirectory; engine.Import("clr"); engine.SetStandardOutput(outstream); engine.SetStandardError(new MyStream(Shell)); engine.Execute("import clr;clr.AddReferenceToFile(\"Interop.SAPbobsCOM.dll\")"); engine.Execute("import SAPbobsCOM;import System;import System.IO;import System.Text;import System.Collections"); IronPython.Runtime.List objecttypes = engine.EvaluateAs<IronPython.Runtime.List>("dir(SAPbobsCOM.BoObjectTypes)"); foreach (string otype in objecttypes) { if (otype.StartsWith("o")) { string handle; int endcut = 2; if (otype.ToUpper().EndsWith("US")) { endcut = 1; } else if (otype.ToUpper().EndsWith("HES")) { endcut = 3; } else if (otype.ToUpper().EndsWith("S")) { endcut = 2; } else { endcut = 1; } handle = otype.Substring(1, otype.Length - endcut).ToUpper(); if (handle.EndsWith("IE")) { handle = handle.Substring(0, handle.Length - 2) + "Y"; } engine.Globals[handle] = engine.EvaluateAs<BoObjectTypes>("SAPbobsCOM.BoObjectTypes." + otype); B1ObjectList.Add(handle, engine.Globals[handle]); } } System.Collections.Generic.List<string> enums = new System.Collections.Generic.List<string>(); Assembly[] domainAssemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly ass in domainAssemblies) { if (ass.FullName.Contains("SAPbobsCOM")) { Type[] types = ass.GetTypes(); foreach (Type type in types) { if (type.IsEnum) { string[] enumnames = System.Enum.GetNames(type); Array enumvalues = System.Enum.GetValues(type); for (int enumindex = 0; enumindex < enumnames.Length; enumindex++) { engine.Globals[enumnames[enumindex]] = enumvalues.GetValue(enumindex); if (!enumnames[enumindex].StartsWith("o")) { B1EnumList.Add(enumnames[enumindex], enumvalues.GetValue(enumindex)); B1EnumValues.Add(enumnames[enumindex], enumvalues.GetValue(enumindex).GetType().Name); Type enumclass = enumvalues.GetValue(enumindex).GetType(); if (!B1EnumClassList.Contains(enumclass.Name)) { B1EnumClassList.Add(enumclass.Name); } } engine.Globals[enumnames[enumindex].ToLower()] = enumvalues.GetValue(enumindex); engine.Globals[enumnames[enumindex].ToUpper()] = enumvalues.GetValue(enumindex); enums.Add(type.Name + ":" + enumvalues.GetValue(enumindex)); } } } } } engine.Globals["enumvalues"] = enums; foreach (string key in B1ObjectList.Keys) { this.cmbRefObjects.Items.Add(key); } foreach (string key in B1EnumList.Keys) { this.cmbRefEnum.Items.Add(key); } foreach (string key in B1EnumClassList) { this.cmbEnumInfo.Items.Add(key); } SyntaxDocument doc = new SyntaxDocument(); doc.SyntaxFile = "Python.syn"; this.codeEditor.Document = doc; }
/// <summary> /// Add the given path to the list of places to search for scripts /// </summary> /// <param name="path"></param> public static void AddPath(string path) { interpreter.AddToPath(ResolvePath(path)); }
public ClientCore() { s_clientCore = this; //Ansi.SendAnsiInit(); m_synchronizedInvoke = new SynchronizedInvoke(); // Services m_baseServicesDispatcher = new BaseServicesDispatcher(); // Init console m_textConsole = new TextConsole(); ChiConsole.SetChiConsole(m_textConsole); // Initialize ironpython IronPython.Compiler.Options.GenerateModulesAsSnippets = true; m_pythonEngine = new PythonEngine(); ChiPythonStream s = new ChiPythonStream(); m_pythonEngine.SetStandardOutput(s); m_pythonEngine.SetStandardError(s); m_pythonEngine.SetStandardInput(s); //m_pythonEngine.AddToPath(Environment.CurrentDirectory); //m_pythonEngine.AddToPath(Application.StartupPath + "/lib"); #if DEBUG m_pythonEngine.AddToPath(@"../../../scripts/lib"); #endif m_pythonEngine.LoadAssembly(typeof(TriggerManager).Assembly); // load BatClientBase m_pythonEngine.LoadAssembly(typeof(System.Drawing.Bitmap).Assembly); // load System.Drawing m_pythonEngine.LoadAssembly(typeof(System.Windows.Forms.Keys).Assembly); // load System.Windows.Forms // Network m_telnet = new Telnet(); m_telnet.connectEvent += new Telnet.ConnectDelegate(_ConnectEvent); m_telnet.disconnectEvent += new Telnet.DisconnectDelegate(_DisconnectEvent); m_telnet.receiveEvent += new Telnet.ReceiveDelegate(_ReceiveEvent); m_telnet.promptEvent += new Telnet.PromptDelegate(_PromptEvent); m_telnet.telnetEvent += new Telnet.TelnetDelegate(_TelnetEvent); m_netPipe = UnixPipes.CreatePipes(); m_commandManager = new CommandManager(m_baseServicesDispatcher); AddBuiltinCommands(); m_triggerManager = new TriggerManager(m_baseServicesDispatcher); m_keyManager = new KeyManager(m_baseServicesDispatcher); m_hiliteManager = new HiliteManager(m_triggerManager); PythonInterface.Initialize(m_baseServicesDispatcher, m_triggerManager, m_commandManager, this, m_textConsole, m_pythonEngine, m_keyManager, m_hiliteManager); // run init script Version currentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; Version baseVersion = System.Reflection.Assembly.GetAssembly(typeof(Telnet)).GetName().Version; ChiConsole.WriteLine("Chiroptera version {0} (base {1})", currentVersion.ToString(2), baseVersion.ToString(2)); ChiConsole.WriteLine("Using {0}", PythonEngine.VersionString); try { #if DEBUG PythonInterface.RunScript(Path.GetFullPath("../../../scripts/std/init_std.bc")); #else PythonInterface.RunScript(Path.Combine(Environment.CurrentDirectory, "std/init_std.bc")); #endif } catch (Exception e) { ChiConsole.WriteError("Error running init_std.bc", e); } /* * m_pythonEngine.Import("site"); * * try * { * m_pythonEngine.ExecuteFile("init.py"); * } * catch (Exception e) * { * ChiConsole.WriteError("Eval failed", e); * } */ }
private void GetPythonConsoleEngine(out PythonEngine engine) { engine = new PythonEngine(); //engine.Execute("import clr"); foreach (DirectoryInfo di in m_SearchPath) { if (di.Exists) engine.AddToPath(di.FullName); } foreach (string name in m_Globals.Keys) { if (!engine.Globals.ContainsKey(name)) engine.Globals.Add(name, m_Globals[name]); else engine.Globals[name] = m_Globals[name]; } }
private void GetPythonEngine(out PythonEngine engine, out MemoryStream output) { engine = new PythonEngine(); engine.Execute("import clr"); foreach (DirectoryInfo di in m_SearchPath) { if (di.Exists) engine.AddToPath(di.FullName); } foreach (string name in m_Globals.Keys) { if (!engine.Globals.ContainsKey(name)) engine.Globals.Add(name, m_Globals[name]); else engine.Globals[name] = m_Globals[name]; } output = new MemoryStream(); MemoryStream error = new MemoryStream(); engine.SetStandardOutput(output); engine.SetStandardError(error); }