def GetSubList(self): # Explicit lookup in the registry. ret = [] key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib") win32ui.DoWaitCursor(1) try: num = 0 while True: try: keyName = win32api.RegEnumKey(key, num) except win32api.error: break # Enumerate all version info subKey = win32api.RegOpenKey(key, keyName) name = None try: subNum = 0 bestVersion = 0.0 while True: try: versionStr = win32api.RegEnumKey(subKey, subNum) except win32api.error: break try: versionFlt = float(versionStr) except ValueError: versionFlt = 0 # ???? if versionFlt > bestVersion: bestVersion = versionFlt name = win32api.RegQueryValue(subKey, versionStr) subNum = subNum + 1 finally: win32api.RegCloseKey(subKey) if name is not None: ret.append( HLIRegisteredTypeLibrary((keyName, versionStr), name)) num = num + 1 finally: win32api.RegCloseKey(key) win32ui.DoWaitCursor(0) ret.sort() return ret
def OnViewOptions(self, id, code): win32ui.InitRichEdit() sheet = dialog.PropertySheet("Pythonwin Options") # Add property pages we know about that need manual work. from pywin.dialogs import ideoptions sheet.AddPage(ideoptions.OptionsPropPage()) from . import toolmenu sheet.AddPage(toolmenu.ToolMenuPropPage()) # Get other dynamic pages from templates. pages = [] for template in self.GetDocTemplateList(): try: # Dont actually call the function with the exception handler. getter = template.GetPythonPropertyPages except AttributeError: # Template does not provide property pages! continue pages = pages + getter() # Debugger template goes at the end try: from pywin.debugger import configui except ImportError: configui = None if configui is not None: pages.append(configui.DebuggerOptionsPropPage()) # Now simply add the pages, and display the dialog. for page in pages: sheet.AddPage(page) if sheet.DoModal() == win32con.IDOK: win32ui.SetStatusText("Applying configuration changes...", 1) win32ui.DoWaitCursor(1) # Tell every Window in our app that win.ini has changed! win32ui.GetMainFrame().SendMessageToDescendants( win32con.WM_WININICHANGE, 0, 0) win32ui.DoWaitCursor(0)
def GetSubList(self): hkey = win32api.RegOpenKey(self.keyRoot, self.keyName) win32ui.DoWaitCursor(1) try: keyNum = 0 ret = [] while True: try: key = win32api.RegEnumKey(hkey, keyNum) except win32api.error: break ret.append( HLIRegistryKey( self.keyRoot, self.keyName + "\\" + key, key)) keyNum = keyNum + 1 finally: win32api.RegCloseKey(hkey) win32ui.DoWaitCursor(0) return ret
def CheckFile(): """ This code looks for the current window, and gets Python to check it without actually executing any code (ie, by compiling only) """ try: pathName = GetActiveFileName() except KeyboardInterrupt: return what = "check" win32ui.SetStatusText(string.capitalize(what)+'ing module...',1) win32ui.DoWaitCursor(1) try: f = open(pathName) except IOError, details: print "Cant open file '%s' - %s" % (pathName, details) return
# # Sample that uses the mscomm OCX to talk to a serial # device. # Very simple - queries a modem for ATI responses import win32ui, win32uiole import win32con from pywin.mfc import dialog, activex from win32com.client import gencache import pythoncom SERIAL_SETTINGS = '19200,n,8,1' SERIAL_PORT = 2 win32ui.DoWaitCursor(1) serialModule = gencache.EnsureModule("{648A5603-2C6E-101B-82B6-000000000014}", 0, 1, 1) win32ui.DoWaitCursor(0) if serialModule is None: raise ImportError, "MS COMM Control does not appear to be installed on the PC" def MakeDlgTemplate(): style = win32con.DS_MODALFRAME | win32con.WS_POPUP \ | win32con.WS_VISIBLE | win32con.WS_CAPTION \ | win32con.WS_SYSMENU | win32con.DS_SETFONT cs = win32con.WS_CHILD | win32con.WS_VISIBLE dlg = [ ["Very Basic Terminal", (0, 0, 350, 180), style, None, (8, "MS Sans Serif")], ] s = win32con.WS_TABSTOP | cs dlg.append(["RICHEDIT", None, 132, (5, 5, 340, 170),s | win32con.ES_WANTRETURN | win32con.ES_MULTILINE | win32con.ES_AUTOVSCROLL | win32con.WS_VSCROLL])
def GetSubList(self): import os clsidstr, versionStr = self.myobject collected = [] helpPath = "" key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib\\%s\\%s" % (clsidstr, versionStr)) win32ui.DoWaitCursor(1) try: num = 0 while 1: try: subKey = win32api.RegEnumKey(key, num) except win32api.error: break hSubKey = win32api.RegOpenKey(key, subKey) try: value, typ = win32api.RegQueryValueEx(hSubKey, None) if typ == win32con.REG_EXPAND_SZ: value = win32api.ExpandEnvironmentStrings(value) except win32api.error: value = "" if subKey == "HELPDIR": helpPath = value elif subKey == "Flags": flags = value else: try: lcid = int(subKey) lcidkey = win32api.RegOpenKey(key, subKey) # Enumerate the platforms lcidnum = 0 while 1: try: platform = win32api.RegEnumKey( lcidkey, lcidnum) except win32api.error: break try: hplatform = win32api.RegOpenKey( lcidkey, platform) fname, typ = win32api.RegQueryValueEx( hplatform, None) if typ == win32con.REG_EXPAND_SZ: fname = win32api.ExpandEnvironmentStrings( fname) except win32api.error: fname = "" collected.append((lcid, platform, fname)) lcidnum = lcidnum + 1 win32api.RegCloseKey(lcidkey) except ValueError: pass num = num + 1 finally: win32ui.DoWaitCursor(0) win32api.RegCloseKey(key) # Now, loop over my collected objects, adding a TypeLib and a HelpFile ret = [] # if helpPath: ret.append(browser.MakeHLI(helpPath, "Help Path")) ret.append(HLICLSID(clsidstr)) for lcid, platform, fname in collected: extraDescs = [] if platform != "win32": extraDescs.append(platform) if lcid: extraDescs.append("locale=%s" % lcid) extraDesc = "" if extraDescs: extraDesc = " (%s)" % ", ".join(extraDescs) ret.append(HLITypeLib(fname, "Type Library" + extraDesc)) ret.sort() return ret
def ImportFile(): """ This code looks for the current window, and determines if it can be imported. If not, it will prompt for a file name, and allow it to be imported. """ try: pathName = GetActiveFileName() except KeyboardInterrupt: pathName = None if pathName is not None: if string.lower(os.path.splitext(pathName)[1]) <> ".py": pathName = None if pathName is None: openFlags = win32con.OFN_OVERWRITEPROMPT|win32con.OFN_FILEMUSTEXIST dlg = win32ui.CreateFileDialog(1,None,None,openFlags, "Python Scripts (*.py)|*.py||") dlg.SetOFNTitle("Import Script") if dlg.DoModal()!=win32con.IDOK: return 0 pathName = dlg.GetPathName() # If already imported, dont look for package path, modName = os.path.split(pathName) modName, modExt = os.path.splitext(modName) newPath = None for key, mod in sys.modules.items(): if hasattr(mod, '__file__'): fname = mod.__file__ base, ext = os.path.splitext(fname) if string.lower(ext) in ['.pyo', '.pyc']: ext = '.py' fname = base + ext if win32ui.ComparePath(fname, pathName): modName = key break else: # for not broken modName, newPath = GetPackageModuleName(pathName) if newPath: sys.path.append(newPath) if sys.modules.has_key(modName): bNeedReload = 1 what = "reload" else: what = "import" bNeedReload = 0 win32ui.SetStatusText(string.capitalize(what)+'ing module...',1) win32ui.DoWaitCursor(1) # win32ui.GetMainFrame().BeginWaitCursor() try: # always do an import, as it is cheap is already loaded. This ensures # it is in our name space. codeObj = compile('import '+modName,'<auto import>','exec') except SyntaxError: win32ui.SetStatusText('Invalid filename for import: "' +modName+'"') return try: exec codeObj in __main__.__dict__ if bNeedReload: reload(sys.modules[modName]) # codeObj = compile('reload('+modName+')','<auto import>','eval') # exec codeObj in __main__.__dict__ win32ui.SetStatusText('Successfully ' + what + "ed module '"+modName+"'") except: _HandlePythonFailure(what) win32ui.DoWaitCursor(0)
def ImportFile(): """This code looks for the current window, and determines if it can be imported. If not, it will prompt for a file name, and allow it to be imported.""" try: pathName = GetActiveFileName() except KeyboardInterrupt: pathName = None if pathName is not None: if os.path.splitext(pathName)[1].lower() not in (".py", ".pyw", ".pyx"): pathName = None if pathName is None: openFlags = win32con.OFN_OVERWRITEPROMPT | win32con.OFN_FILEMUSTEXIST dlg = win32ui.CreateFileDialog( 1, None, None, openFlags, "Python Scripts (*.py;*.pyw)|*.py;*.pyw;*.pyx||") dlg.SetOFNTitle("Import Script") if dlg.DoModal() != win32con.IDOK: return 0 pathName = dlg.GetPathName() # If already imported, dont look for package path, modName = os.path.split(pathName) modName, modExt = os.path.splitext(modName) newPath = None # note that some packages (*cough* email *cough*) use "lazy importers" # meaning sys.modules can change as a side-effect of looking at # module.__file__ - so we must take a copy (ie, items() in py2k, # list(items()) in py3k) for key, mod in list(sys.modules.items()): if getattr(mod, "__file__", None): fname = mod.__file__ base, ext = os.path.splitext(fname) if ext.lower() in [".pyo", ".pyc"]: ext = ".py" fname = base + ext if win32ui.ComparePath(fname, pathName): modName = key break else: # for not broken modName, newPath = GetPackageModuleName(pathName) if newPath: sys.path.append(newPath) if modName in sys.modules: bNeedReload = 1 what = "reload" else: what = "import" bNeedReload = 0 win32ui.SetStatusText(what.capitalize() + "ing module...", 1) win32ui.DoWaitCursor(1) # win32ui.GetMainFrame().BeginWaitCursor() try: # always do an import, as it is cheap if it's already loaded. This ensures # it is in our name space. codeObj = compile("import " + modName, "<auto import>", "exec") except SyntaxError: win32ui.SetStatusText('Invalid filename for import: "' + modName + '"') return try: exec(codeObj, __main__.__dict__) mod = sys.modules.get(modName) if bNeedReload: from importlib import reload mod = reload(sys.modules[modName]) win32ui.SetStatusText("Successfully " + what + "ed module '" + modName + "': %s" % getattr(mod, "__file__", "<unkown file>")) except: _HandlePythonFailure(what) win32ui.DoWaitCursor(0)
def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None): global lastScript, lastArgs, lastDebuggingType _debugger_stop_frame_ = 1 # Magic variable so the debugger will hide me! # Get the debugger - may be None! debugger = GetDebugger() if defName is None: try: pathName = GetActiveFileName() except KeyboardInterrupt: return # User cancelled save. else: pathName = defName if not pathName: pathName = lastScript if defArgs is None: args = "" if pathName == lastScript: args = lastArgs else: args = defArgs if debuggingType is None: debuggingType = lastDebuggingType if not pathName or bShowDialog: dlg = DlgRunScript(debugger is not None) dlg["script"] = pathName dlg["args"] = args dlg["debuggingType"] = debuggingType if dlg.DoModal() != win32con.IDOK: return script = dlg["script"] args = dlg["args"] debuggingType = dlg["debuggingType"] if not script: return if debuggingType == RS_DEBUGGER_GO and debugger is not None: # This may surprise users - they select "Run under debugger", but # it appears not to! Only warn when they pick from the dialog! # First - ensure the debugger is activated to pickup any break-points # set in the editor. try: # Create the debugger, but _dont_ init the debugger GUI. rd = debugger._GetCurrentDebugger() except AttributeError: rd = None if rd is not None and len(rd.breaks) == 0: msg = "There are no active break-points.\r\n\r\nSelecting this debug option without any\r\nbreak-points is unlikely to have the desired effect\r\nas the debugger is unlikely to be invoked..\r\n\r\nWould you like to step-through in the debugger instead?" rc = win32ui.MessageBox( msg, win32ui.LoadString(win32ui.IDR_DEBUGGER), win32con.MB_YESNOCANCEL | win32con.MB_ICONINFORMATION, ) if rc == win32con.IDCANCEL: return if rc == win32con.IDYES: debuggingType = RS_DEBUGGER_STEP lastDebuggingType = debuggingType lastScript = script lastArgs = args else: script = pathName # try and open the script. if (len(os.path.splitext(script)[1]) == 0 ): # check if no extension supplied, and give one. script = script + ".py" # If no path specified, try and locate the file path, fnameonly = os.path.split(script) if len(path) == 0: try: os.stat(fnameonly) # See if it is OK as is... script = fnameonly except os.error: fullScript = LocatePythonFile(script) if fullScript is None: win32ui.MessageBox("The file '%s' can not be located" % script) return script = fullScript else: path = win32ui.FullPath(path) if not IsOnPythonPath(path): sys.path.append(path) # py3k fun: If we use text mode to open the file, we get \r\n # translated so Python allows the syntax (good!), but we get back # text already decoded from the default encoding (bad!) and Python # ignores any encoding decls (bad!). If we use binary mode we get # the raw bytes and Python looks at the encoding (good!) but \r\n # chars stay in place so Python throws a syntax error (bad!). # So: so the binary thing and manually normalize \r\n. try: f = open(script, "rb") except IOError as exc: win32ui.MessageBox("The file could not be opened - %s (%d)" % (exc.strerror, exc.errno)) return # Get the source-code - as above, normalize \r\n code = f.read().replace(byte_crlf, byte_lf).replace(byte_cr, byte_lf) + byte_lf # Remember and hack sys.argv for the script. oldArgv = sys.argv sys.argv = ParseArgs(args) sys.argv.insert(0, script) # sys.path[0] is the path of the script oldPath0 = sys.path[0] newPath0 = os.path.split(script)[0] if not oldPath0: # if sys.path[0] is empty sys.path[0] = newPath0 insertedPath0 = 0 else: sys.path.insert(0, newPath0) insertedPath0 = 1 bWorked = 0 win32ui.DoWaitCursor(1) base = os.path.split(script)[1] # Allow windows to repaint before starting. win32ui.PumpWaitingMessages() win32ui.SetStatusText("Running script %s..." % base, 1) exitCode = 0 from pywin.framework import interact # Check the debugger flags if debugger is None and (debuggingType != RS_DEBUGGER_NONE): win32ui.MessageBox( "No debugger is installed. Debugging options have been ignored!") debuggingType = RS_DEBUGGER_NONE # Get a code object - ignore the debugger for this, as it is probably a syntax error # at this point try: codeObject = compile(code, script, "exec") except: # Almost certainly a syntax error! _HandlePythonFailure("run script", script) # No code object which to run/debug. return __main__.__file__ = script try: if debuggingType == RS_DEBUGGER_STEP: debugger.run(codeObject, __main__.__dict__, start_stepping=1) elif debuggingType == RS_DEBUGGER_GO: debugger.run(codeObject, __main__.__dict__, start_stepping=0) else: # Post mortem or no debugging exec(codeObject, __main__.__dict__) bWorked = 1 except bdb.BdbQuit: # Dont print tracebacks when the debugger quit, but do print a message. print("Debugging session cancelled.") exitCode = 1 bWorked = 1 except SystemExit as code: exitCode = code bWorked = 1 except KeyboardInterrupt: # Consider this successful, as we dont want the debugger. # (but we do want a traceback!) if interact.edit and interact.edit.currentView: interact.edit.currentView.EnsureNoPrompt() traceback.print_exc() if interact.edit and interact.edit.currentView: interact.edit.currentView.AppendToPrompt([]) bWorked = 1 except: if interact.edit and interact.edit.currentView: interact.edit.currentView.EnsureNoPrompt() traceback.print_exc() if interact.edit and interact.edit.currentView: interact.edit.currentView.AppendToPrompt([]) if debuggingType == RS_DEBUGGER_PM: debugger.pm() del __main__.__file__ sys.argv = oldArgv if insertedPath0: del sys.path[0] else: sys.path[0] = oldPath0 f.close() if bWorked: win32ui.SetStatusText("Script '%s' returned exit code %s" % (script, exitCode)) else: win32ui.SetStatusText("Exception raised while running script %s" % base) try: sys.stdout.flush() except AttributeError: pass win32ui.DoWaitCursor(0)
def ImportFile(): """ This code looks for the current window, and determines if it can be imported. If not, it will prompt for a file name, and allow it to be imported. """ try: pathName = GetActiveFileName() except KeyboardInterrupt: pathName = None if pathName is not None: if os.path.splitext(pathName)[1].lower() not in ('.py','.pyw','.pyx'): pathName = None if pathName is None: openFlags = win32con.OFN_OVERWRITEPROMPT|win32con.OFN_FILEMUSTEXIST dlg = win32ui.CreateFileDialog(1,None,None,openFlags, "Python Scripts (*.py;*.pyw)|*.py;*.pyw;*.pyx||") dlg.SetOFNTitle("Import Script") if dlg.DoModal()!=win32con.IDOK: return 0 pathName = dlg.GetPathName() # If already imported, dont look for package path, modName = os.path.split(pathName) modName, modExt = os.path.splitext(modName) newPath = None # note that some packages (*cough* email *cough*) use "lazy importers" # meaning sys.modules can change as a side-effect of looking at # module.__file__ - so we must take a copy (ie, items() in py2k, # list(items()) in py3k) for key, mod in sys.modules.items(): if hasattr(mod, '__file__'): fname = mod.__file__ base, ext = os.path.splitext(fname) if ext.lower() in ['.pyo', '.pyc']: ext = '.py' fname = base + ext if win32ui.ComparePath(fname, pathName): modName = key break else: # for not broken modName, newPath = GetPackageModuleName(pathName) if newPath: sys.path.append(newPath) if modName in sys.modules: bNeedReload = 1 what = "reload" else: what = "import" bNeedReload = 0 win32ui.SetStatusText(what.capitalize()+'ing module...',1) win32ui.DoWaitCursor(1) # win32ui.GetMainFrame().BeginWaitCursor() try: # always do an import, as it is cheap if it's already loaded. This ensures # it is in our name space. codeObj = compile('import '+modName,'<auto import>','exec') except SyntaxError: win32ui.SetStatusText('Invalid filename for import: "' +modName+'"') return try: exec codeObj in __main__.__dict__ mod = sys.modules.get(modName) if bNeedReload: try: ## The interpreter sees this import as a local assignment, so Python 2.x throws ## UnboundLocalError: local variable 'reload' referenced before assignment ## when you try to use reload after this fails from imp import reload as my_reload # py3k except ImportError: my_reload = reload # reload a builtin in py2k mod = my_reload(sys.modules[modName]) win32ui.SetStatusText('Successfully ' + what + "ed module '"+modName+"': %s" % getattr(mod,'__file__',"<unkown file>")) except: _HandlePythonFailure(what) win32ui.DoWaitCursor(0)
def GetTestCalendarClass(): global calendarParentModule win32ui.DoWaitCursor(1) calendarParentModule = gencache.EnsureModule( "{8E27C92E-1264-101C-8A2F-040224009C02}", 0, 7, 0 ) win32ui.DoWaitCursor(0) if calendarParentModule is None: return None class TestCalDialog(dialog.Dialog): def OnInitDialog(self): class MyCal(activex.Control, calendarParentModule.Calendar): def OnAfterUpdate(self): print("OnAfterUpdate") def OnClick(self): print("OnClick") def OnDblClick(self): print("OnDblClick") def OnKeyDown(self, KeyCode, Shift): print("OnKeyDown", KeyCode, Shift) def OnKeyPress(self, KeyAscii): print("OnKeyPress", KeyAscii) def OnKeyUp(self, KeyCode, Shift): print("OnKeyUp", KeyCode, Shift) def OnBeforeUpdate(self, Cancel): print("OnBeforeUpdate", Cancel) def OnNewMonth(self): print("OnNewMonth") def OnNewYear(self): print("OnNewYear") rc = dialog.Dialog.OnInitDialog(self) self.olectl = MyCal() try: self.olectl.CreateControl( "OCX", win32con.WS_TABSTOP | win32con.WS_VISIBLE, (7, 43, 500, 300), self._obj_, 131, ) except win32ui.error: self.MessageBox("The Calendar Control could not be created") self.olectl = None self.EndDialog(win32con.IDCANCEL) return rc def OnOK(self): self.olectl.AboutBox() return TestCalDialog