diff --git a/CHANGES.txt b/CHANGES.txt index c31fd2dbe6..7a238523fb 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -69,7 +69,7 @@ Build 305, released 2022-11-06 from there. (#1908) * Dropped support for allowing a bytes object to be passed where a COM BSTR - is expected - this support was accidental on the path from 2.x->3.x. + is expected - this support was accidental on the path from Python 2 -> 3. * win32crypt's PyCERTSTORE.CertCloseStore()'s `Flags` argument has been deprecated as it is likely to crash the process if diff --git a/Pythonwin/pywin/Demos/fontdemo.py b/Pythonwin/pywin/Demos/fontdemo.py index 68c353cb21..0c1f7f1d11 100644 --- a/Pythonwin/pywin/Demos/fontdemo.py +++ b/Pythonwin/pywin/Demos/fontdemo.py @@ -72,13 +72,12 @@ def FontDemo(): template = docview.DocTemplate(win32ui.IDR_PYTHONTYPE, None, None, FontView) doc = template.OpenDocumentFile(None) doc.SetTitle("Font Demo") - # print "template is ", template, "obj is", template._obj_ + # print("template is ", template, "obj is", template._obj_) template.close() + # print("closed") + # del template -# print "closed" -# del template - if __name__ == "__main__": import demoutils diff --git a/Pythonwin/pywin/Demos/guidemo.py b/Pythonwin/pywin/Demos/guidemo.py index 95b1dbbc91..887738c244 100644 --- a/Pythonwin/pywin/Demos/guidemo.py +++ b/Pythonwin/pywin/Demos/guidemo.py @@ -17,7 +17,7 @@ ("Dynamic window creation", "import createwin;createwin.demo()"), ("Various Dialog demos", "import dlgtest;dlgtest.demo()"), ("OCX Control Demo", "from ocx import ocxtest;ocxtest.demo()"), - ("OCX Serial Port Demo", "from ocx import ocxserialtest; ocxserialtest.test()"), + ("OCX Serial Port Demo", "from ocx import ocxserialtest; ocxserialtest.test()"), ( "IE4 Control Demo", 'from ocx import webbrowser; webbrowser.Demo("http://www.python.org")', diff --git a/Pythonwin/pywin/Demos/ocx/webbrowser.py b/Pythonwin/pywin/Demos/ocx/webbrowser.py index 914b84a555..1dc318c198 100644 --- a/Pythonwin/pywin/Demos/ocx/webbrowser.py +++ b/Pythonwin/pywin/Demos/ocx/webbrowser.py @@ -24,7 +24,7 @@ def OnBeforeNavigate2( self, pDisp, URL, Flags, TargetFrameName, PostData, Headers, Cancel ): self.GetParent().OnNavigate(URL) - # print "BeforeNavigate2", pDisp, URL, Flags, TargetFrameName, PostData, Headers, Cancel + # print("BeforeNavigate2", pDisp, URL, Flags, TargetFrameName, PostData, Headers, Cancel) class BrowserFrame(window.MDIChildWnd): diff --git a/Pythonwin/pywin/Demos/splittst.py b/Pythonwin/pywin/Demos/splittst.py index 0114bf09a3..2dbeb1e223 100644 --- a/Pythonwin/pywin/Demos/splittst.py +++ b/Pythonwin/pywin/Demos/splittst.py @@ -60,8 +60,8 @@ def __init__(self): ) def InitialUpdateFrame(self, frame, doc, makeVisible): - # print "frame is ", frame, frame._obj_ - # print "doc is ", doc, doc._obj_ + # print("frame is ", frame, frame._obj_) + # print("doc is ", doc, doc._obj_) self._obj_.InitialUpdateFrame(frame, doc, makeVisible) # call default handler. frame.InitialUpdateFrame(doc, makeVisible) diff --git a/Pythonwin/pywin/Demos/threadedgui.py b/Pythonwin/pywin/Demos/threadedgui.py index 556ed18d5c..5b0704ef3b 100644 --- a/Pythonwin/pywin/Demos/threadedgui.py +++ b/Pythonwin/pywin/Demos/threadedgui.py @@ -61,7 +61,7 @@ def OnTimer(self, id, timeVal): self.InvalidateRect() def OnPaint(self): - # print "Paint message from thread", win32api.GetCurrentThreadId() + # print("Paint message from thread", win32api.GetCurrentThreadId()) dc, paintStruct = self.BeginPaint() self.OnPrepareDC(dc, None) diff --git a/Pythonwin/pywin/debugger/debugger.py b/Pythonwin/pywin/debugger/debugger.py index 3b801fc851..17e64f7c5d 100644 --- a/Pythonwin/pywin/debugger/debugger.py +++ b/Pythonwin/pywin/debugger/debugger.py @@ -118,11 +118,11 @@ def __init__(self, debugger): HierListItem.__init__(self, debugger, None) self.last_stack = [] - ## def __del__(self): - ## print "HierStackRoot dieing" + # def __del__(self): + # print("HierStackRoot dieing") def GetSubList(self): debugger = self.myobject - # print self.debugger.stack, self.debugger.curframe + # print(self.debugger.stack, self.debugger.curframe) ret = [] if debugger.debuggerState == DBGSTATE_BREAK: stackUse = debugger.stack[:] diff --git a/Pythonwin/pywin/docking/DockingBar.py b/Pythonwin/pywin/docking/DockingBar.py index 34b14a41a1..3e9b4131a6 100644 --- a/Pythonwin/pywin/docking/DockingBar.py +++ b/Pythonwin/pywin/docking/DockingBar.py @@ -234,15 +234,15 @@ def OnWindowPosChanged(self, msg): return 0 lparam = msg[3] """ LPARAM used with WM_WINDOWPOSCHANGED: - typedef struct { - HWND hwnd; - HWND hwndInsertAfter; - int x; - int y; - int cx; - int cy; - UINT flags;} WINDOWPOS; - """ + typedef struct { + HWND hwnd; + HWND hwndInsertAfter; + int x; + int y; + int cx; + int cy; + UINT flags;} WINDOWPOS; + """ format = "PPiiiii" bytes = win32ui.GetBytes(lparam, struct.calcsize(format)) hwnd, hwndAfter, x, y, cx, cy, flags = struct.unpack(format, bytes) diff --git a/Pythonwin/pywin/framework/editor/ModuleBrowser.py b/Pythonwin/pywin/framework/editor/ModuleBrowser.py index d1437e6a40..d7370e90cd 100644 --- a/Pythonwin/pywin/framework/editor/ModuleBrowser.py +++ b/Pythonwin/pywin/framework/editor/ModuleBrowser.py @@ -148,7 +148,7 @@ def DestroyBrowser(self): self.DestroyList() def OnActivateView(self, activate, av, dv): - # print "AV", self.bDirty, activate + # print("AV", self.bDirty, activate) if activate: self.CheckRefreshList() return self._obj_.OnActivateView(activate, av, dv) diff --git a/Pythonwin/pywin/framework/editor/color/coloreditor.py b/Pythonwin/pywin/framework/editor/color/coloreditor.py index 9de95a392f..6818d82502 100644 --- a/Pythonwin/pywin/framework/editor/color/coloreditor.py +++ b/Pythonwin/pywin/framework/editor/color/coloreditor.py @@ -9,7 +9,10 @@ from pywin.debugger import dbgcon from pywin.framework.editor import GetEditorOption from pywin.framework.editor.document import EditorDocumentBase +from pywin.framework.editor.frame import EditorFrame +from pywin.framework.editor.template import EditorTemplateBase from pywin.scintilla import bindings, scintillacon +from pywin.scintilla.view import CScintillaView as SyntEditViewParent # WARNING: Duplicated in document.py and editor.py MSG_CHECK_EXTERNAL_FILE = win32con.WM_USER + 1999 @@ -36,9 +39,6 @@ def FinalizeViewCreation(self, view): self.GetDocTemplate().CheckIDLEMenus(view.idle) -SyntEditViewParent = pywin.scintilla.view.CScintillaView - - class SyntEditView(SyntEditViewParent): "A view of a SyntEdit. Obtains data from document." @@ -462,7 +462,7 @@ def FoldTopLevelEvent(self, event=None): - scintillacon.SC_FOLDLEVELBASE ) is_header = level & scintillacon.SC_FOLDLEVELHEADERFLAG - # print lineSeek, level_no, is_header + # print(lineSeek, level_no, is_header) if level_no == 0 and is_header: if (expanding and not self.SCIGetFoldExpanded(lineSeek)) or ( not expanding and self.SCIGetFoldExpanded(lineSeek) @@ -571,9 +571,6 @@ def FoldCollapseAllEvent(self, event): win32ui.DoWaitCursor(-1) -from pywin.framework.editor.frame import EditorFrame - - class SplitterFrame(EditorFrame): def OnCreate(self, cs): self.HookCommand(self.OnWindowSplit, win32ui.ID_WINDOW_SPLIT) @@ -584,9 +581,6 @@ def OnWindowSplit(self, id, code): return 1 -from pywin.framework.editor.template import EditorTemplateBase - - class SyntEditTemplate(EditorTemplateBase): def __init__( self, res=win32ui.IDR_TEXTTYPE, makeDoc=None, makeFrame=None, makeView=None diff --git a/Pythonwin/pywin/framework/editor/editor.py b/Pythonwin/pywin/framework/editor/editor.py index e394a06bfb..6c332bd777 100644 --- a/Pythonwin/pywin/framework/editor/editor.py +++ b/Pythonwin/pywin/framework/editor/editor.py @@ -263,7 +263,7 @@ def Indent(self): else: curCol = curCol + 1 nextColumn = ((curCol / self.indentSize) + 1) * self.indentSize - # print "curCol is", curCol, "nextColumn is", nextColumn + # print("curCol is", curCol, "nextColumn is", nextColumn) ins = None if self.bSmartTabs: # Look for some context. diff --git a/Pythonwin/pywin/framework/editor/frame.py b/Pythonwin/pywin/framework/editor/frame.py index e927d16e5f..e0d97f37c4 100644 --- a/Pythonwin/pywin/framework/editor/frame.py +++ b/Pythonwin/pywin/framework/editor/frame.py @@ -25,15 +25,15 @@ def OnCreateClient(self, cp, context): splitter.CreateView(browserView, 0, 0, (0, 0)) sub_splitter.CreateView(view2, 0, 0, (0, 0)) - ## print "First view is", context.doc.GetFirstView() - ## print "Views are", view, view2, browserView - ## print "Parents are", view.GetParent(), view2.GetParent(), browserView.GetParent() - ## print "Splitter is", splitter - ## print "sub splitter is", sub_splitter - ## Old - ## splitter.CreateStatic (self, 1, 2) - ## splitter.CreateView(view, 0, 1, (0,0)) # size ignored. - ## splitter.CreateView (browserView, 0, 0, (0, 0)) + # print("First view is", context.doc.GetFirstView()) + # print("Views are", view, view2, browserView) + # print("Parents are", view.GetParent(), view2.GetParent(), browserView.GetParent()) + # print("Splitter is", splitter) + # print("sub splitter is", sub_splitter) + # Old + # splitter.CreateStatic (self, 1, 2) + # splitter.CreateView(view, 0, 1, (0,0)) # size ignored. + # splitter.CreateView (browserView, 0, 0, (0, 0)) # Restrict the size of the browser splitter (and we can avoid filling # it until it is shown) @@ -62,8 +62,8 @@ def GetBrowserView(self): def OnClose(self): doc = self.GetActiveDocument() if not doc.SaveModified(): - ## Cancel button selected from Save dialog, do not actually close - ## print 'close cancelled' + # Cancel button selected from Save dialog, do not actually close + # print("close cancelled") return 0 ## So the 'Save' dialog doesn't come up twice doc._obj_.SetModifiedFlag(False) diff --git a/Pythonwin/pywin/framework/editor/template.py b/Pythonwin/pywin/framework/editor/template.py index 362a74a62d..bbaed4e689 100644 --- a/Pythonwin/pywin/framework/editor/template.py +++ b/Pythonwin/pywin/framework/editor/template.py @@ -50,11 +50,11 @@ def OpenDocumentFile(self, filename, bMakeVisible=1): if filename is not None: try: path = os.path.split(filename)[0] - # print "The editor is translating", `filename`,"to", + # print("The editor is translating", "filename", "to") filename = win32api.FindFiles(filename)[0][8] filename = os.path.join(path, filename) - # print `filename` + # print("filename") except (win32api.error, IndexError) as details: + # print("Couldnt get the full filename!", details) pass - # print "Couldnt get the full filename!", details return self._obj_.OpenDocumentFile(filename, bMakeVisible) diff --git a/Pythonwin/pywin/framework/intpydde.py b/Pythonwin/pywin/framework/intpydde.py index 1f869b0f68..2401cdc566 100644 --- a/Pythonwin/pywin/framework/intpydde.py +++ b/Pythonwin/pywin/framework/intpydde.py @@ -21,7 +21,7 @@ def __init__(self, app): def Exec(self, data): try: - # print "Executing", cmd + # print("Executing", cmd) self.app.OnDDECommand(data) except: t, v, tb = sys.exc_info() diff --git a/Pythonwin/pywin/framework/mdi_pychecker.py b/Pythonwin/pywin/framework/mdi_pychecker.py index 40fd4472f2..72b70093a7 100644 --- a/Pythonwin/pywin/framework/mdi_pychecker.py +++ b/Pythonwin/pywin/framework/mdi_pychecker.py @@ -432,10 +432,10 @@ def GetParams(self): ) def OnSaveDocument(self, filename): - # print 'OnSaveDocument() filename=',filename + # print("OnSaveDocument() filename=",filename) savefile = open(filename, "wb") txt = self.GetParams() + "\n" - # print 'writing',txt + # print("writing",txt) savefile.write(txt) savefile.close() self.SetModifiedFlag(0) diff --git a/Pythonwin/pywin/framework/scriptutils.py b/Pythonwin/pywin/framework/scriptutils.py index a04ed7bbee..2f9c56e2de 100644 --- a/Pythonwin/pywin/framework/scriptutils.py +++ b/Pythonwin/pywin/framework/scriptutils.py @@ -1,6 +1,7 @@ """ Various utilities for running/importing a script """ + import bdb import linecache import os diff --git a/Pythonwin/pywin/framework/sgrepmdi.py b/Pythonwin/pywin/framework/sgrepmdi.py index 1c0d6339c4..a4068b5cd2 100644 --- a/Pythonwin/pywin/framework/sgrepmdi.py +++ b/Pythonwin/pywin/framework/sgrepmdi.py @@ -344,10 +344,10 @@ def GetParams(self): ) def OnSaveDocument(self, filename): - # print 'OnSaveDocument() filename=',filename + # print("OnSaveDocument() filename=", filename) savefile = open(filename, "wb") txt = self.GetParams() + "\n" - # print 'writing',txt + # print("writing", txt) savefile.write(txt) savefile.close() self.SetModifiedFlag(0) diff --git a/Pythonwin/pywin/framework/toolmenu.py b/Pythonwin/pywin/framework/toolmenu.py index afe06b2b41..1f16f9fca1 100644 --- a/Pythonwin/pywin/framework/toolmenu.py +++ b/Pythonwin/pywin/framework/toolmenu.py @@ -214,7 +214,7 @@ def OnOK(self): return self._obj_.OnOK() def OnCommandEditControls(self, id, cmd): - # print "OnEditControls", id, cmd + # print("OnEditControls", id, cmd) if cmd == win32con.EN_CHANGE and not self.bImChangingEditControls: itemNo = self.listControl.GetNextItem(-1, commctrl.LVNI_SELECTED) newText = self.editMenuCommand.GetWindowText() @@ -228,7 +228,7 @@ def OnNotifyListControlEndLabelEdit(self, id, cmd): self.listControl.SetItemText(itemNo, 0, newText) def OnNotifyListControl(self, id, cmd): - # print id, cmd + # print(id, cmd) try: itemNo = self.listControl.GetNextItem(-1, commctrl.LVNI_SELECTED) except win32ui.error: # No selection! diff --git a/Pythonwin/pywin/mfc/activex.py b/Pythonwin/pywin/mfc/activex.py index a9828e78dc..f3d9939a4b 100644 --- a/Pythonwin/pywin/mfc/activex.py +++ b/Pythonwin/pywin/mfc/activex.py @@ -1,5 +1,6 @@ """Support for ActiveX control hosting in Pythonwin. """ + import win32ui import win32uiole diff --git a/Pythonwin/pywin/mfc/dialog.py b/Pythonwin/pywin/mfc/dialog.py index 280c025aa1..41107e54d3 100644 --- a/Pythonwin/pywin/mfc/dialog.py +++ b/Pythonwin/pywin/mfc/dialog.py @@ -1,6 +1,7 @@ """ \ Base class for Dialogs. Also contains a few useful utility functions """ + # dialog.py # Python class for Dialog Boxes in PythonWin. diff --git a/Pythonwin/pywin/mfc/object.py b/Pythonwin/pywin/mfc/object.py index 063f835f76..62062a5351 100644 --- a/Pythonwin/pywin/mfc/object.py +++ b/Pythonwin/pywin/mfc/object.py @@ -33,7 +33,7 @@ def __getattr__( raise AttributeError(attr) def OnAttachedObjectDeath(self): - # print "object", self.__class__.__name__, "dieing" + # print("object", self.__class__.__name__, "dieing") self._obj_ = None def close(self): diff --git a/Pythonwin/pywin/scintilla/IDLEenvironment.py b/Pythonwin/pywin/scintilla/IDLEenvironment.py index f60f19de36..9114c2c6bd 100644 --- a/Pythonwin/pywin/scintilla/IDLEenvironment.py +++ b/Pythonwin/pywin/scintilla/IDLEenvironment.py @@ -533,30 +533,30 @@ def test(): e.SetSel((4, 4)) skip = """ - TestCheck("insert", e, 4) - TestCheck("insert wordstart", e, 3) - TestCheck("insert wordend", e, 8) - TestCheck("insert linestart", e, 0) - TestCheck("insert lineend", e, 12) - TestCheck("insert + 4 chars", e, 8) - TestCheck("insert +4c", e, 8) - TestCheck("insert - 2 chars", e, 2) - TestCheck("insert -2c", e, 2) - TestCheck("insert-2c", e, 2) - TestCheck("insert-2 c", e, 2) - TestCheck("insert- 2c", e, 2) - TestCheck("1.1", e, 1) - TestCheck("1.0", e, 0) - TestCheck("2.0", e, 13) - try: - TestCheck("sel.first", e, 0) - print "*** sel.first worked with an empty selection" - except TextError: - pass - e.SetSel((4,5)) - TestCheck("sel.first- 2c", e, 2) - TestCheck("sel.last- 2c", e, 3) - """ + TestCheck("insert", e, 4) + TestCheck("insert wordstart", e, 3) + TestCheck("insert wordend", e, 8) + TestCheck("insert linestart", e, 0) + TestCheck("insert lineend", e, 12) + TestCheck("insert + 4 chars", e, 8) + TestCheck("insert +4c", e, 8) + TestCheck("insert - 2 chars", e, 2) + TestCheck("insert -2c", e, 2) + TestCheck("insert-2c", e, 2) + TestCheck("insert-2 c", e, 2) + TestCheck("insert- 2c", e, 2) + TestCheck("1.1", e, 1) + TestCheck("1.0", e, 0) + TestCheck("2.0", e, 13) + try: + TestCheck("sel.first", e, 0) + print("*** sel.first worked with an empty selection") + except TextError: + pass + e.SetSel((4,5)) + TestCheck("sel.first- 2c", e, 2) + TestCheck("sel.last- 2c", e, 3) + """ # Check EOL semantics e.SetSel((4, 4)) TestGet("insert lineend", "insert lineend +1c", t, "\n") diff --git a/Pythonwin/pywin/scintilla/configui.py b/Pythonwin/pywin/scintilla/configui.py index 1c48c6cf65..2a47a0e0da 100644 --- a/Pythonwin/pywin/scintilla/configui.py +++ b/Pythonwin/pywin/scintilla/configui.py @@ -228,7 +228,7 @@ def UpdateUIForStyle(self, style): sel = 0 for c in paletteVGA: if format[4] == c[1]: - # print "Style", style.name, "is", c[0] + # print("Style", style.name, "is", c[0]) break sel = sel + 1 else: diff --git a/Pythonwin/pywin/scintilla/document.py b/Pythonwin/pywin/scintilla/document.py index f7f542d6c0..bf0a2f03be 100644 --- a/Pythonwin/pywin/scintilla/document.py +++ b/Pythonwin/pywin/scintilla/document.py @@ -37,7 +37,7 @@ def DeleteContents(self): def OnOpenDocument(self, filename): # init data members - # print "Opening", filename + # print("Opening", filename) self.SetPathName(filename) # Must set this early! try: # load the text as binary we can get smart diff --git a/Pythonwin/pywin/scintilla/formatter.py b/Pythonwin/pywin/scintilla/formatter.py index 0df8015366..0f91968fa1 100644 --- a/Pythonwin/pywin/scintilla/formatter.py +++ b/Pythonwin/pywin/scintilla/formatter.py @@ -142,7 +142,7 @@ def _ReformatStyle(self, style): return assert style.stylenum is not None, "Unregistered style." - # print "Reformat style", style.name, style.stylenum + # print("Reformat style", style.name, style.stylenum) scintilla = self.scintilla stylenum = style.stylenum # Now we have the style number, indirect for the actual style. @@ -252,7 +252,16 @@ def OnStyleNeeded(self, std, extra): endStyledChar = self.scintilla.SendScintilla(scintillacon.SCI_GETENDSTYLED) lineEndStyled = self.scintilla.LineFromChar(endStyledChar) endStyled = self.scintilla.LineIndex(lineEndStyled) - # print "enPosPaint %d endStyledChar %d lineEndStyled %d endStyled %d" % (endPosPaint, endStyledChar, lineEndStyled, endStyled) + # print( + # "endPosPaint", + # endPosPaint, + # "endStyledChar", + # endStyledChar, + # "lineEndStyled", + # lineEndStyled, + # "endStyled", + # endStyled, + # ) self.Colorize(endStyled, notify.position) def ColorSeg(self, start, end, styleName): diff --git a/Pythonwin/pywin/scintilla/view.py b/Pythonwin/pywin/scintilla/view.py index cf570ea1f2..d877bf3805 100644 --- a/Pythonwin/pywin/scintilla/view.py +++ b/Pythonwin/pywin/scintilla/view.py @@ -691,7 +691,16 @@ def _GetWordSplit(self, pos=-1, bAllowCalls=0): return "".join(before), "".join(after) def OnPrepareDC(self, dc, pInfo): - # print "OnPrepareDC for page", pInfo.GetCurPage(), "of", pInfo.GetFromPage(), "to", pInfo.GetToPage(), ", starts=", self.starts + # print( + # "OnPrepareDC for page", + # pInfo.GetCurPage(), + # "of", + # pInfo.GetFromPage(), + # "to", + # pInfo.GetToPage(), + # ", starts=", + # self.starts, + # ) if dc.IsPrinting(): # Check if we are beyond the end. # (only do this when actually printing, else messes up print preview!) @@ -779,7 +788,7 @@ def FormatRange(self, dc, pageStart, lengthDoc, rc, draw): def OnPrint(self, dc, pInfo): metrics = dc.GetTextMetrics() - # print "dev", w, h, l, metrics['tmAscent'], metrics['tmDescent'] + # print("dev", w, h, l, metrics["tmAscent"], metrics["tmDescent"]) if self.starts is None: self.CalculatePageRanges(dc, pInfo) pageNum = pInfo.GetCurPage() - 1 diff --git a/Pythonwin/pywin/tools/hierlist.py b/Pythonwin/pywin/tools/hierlist.py index cc76f1905a..495eea78f9 100644 --- a/Pythonwin/pywin/tools/hierlist.py +++ b/Pythonwin/pywin/tools/hierlist.py @@ -220,9 +220,9 @@ def Refresh(self, hparent=None): inewlook = inewlook + 1 if matched: # Insert the new items. - # print "Inserting after", old_items[iold], old_handles[iold] + # print("Inserting after", old_items[iold], old_handles[iold]) for i in range(inew, inewlook): - # print "Inserting index %d (%s)" % (i, new_items[i]) + # print(f"Inserting index {i} ({new_items[i]})") hAfter = self.AddItem(hparent, new_items[i], hAfter) inew = inewlook + 1 @@ -232,7 +232,7 @@ def Refresh(self, hparent=None): self.Refresh(hold) else: # Remove the deleted items. - # print "Deleting %d (%s)" % (iold, old_items[iold]) + # print(f"Deleting {iold} ({old_items[iold]})") hdelete = old_handles[iold] # First recurse and remove the children from the map. for hchild in self._GetChildHandles(hdelete): @@ -243,7 +243,7 @@ def Refresh(self, hparent=None): hAfter = old_handles[iold] # Fill any remaining new items: for newItem in new_items[inew:]: - # print "Inserting new item", newItem + # print("Inserting new item", newItem) self.AddItem(hparent, newItem) def AcceptRoot(self, root): diff --git a/Pythonwin/pywin/tools/regedit.py b/Pythonwin/pywin/tools/regedit.py index c62a029910..1f83213ec0 100644 --- a/Pythonwin/pywin/tools/regedit.py +++ b/Pythonwin/pywin/tools/regedit.py @@ -159,9 +159,9 @@ def SelectedItem(self): def SearchSelectedItem(self): handle = self.hierList.GetChildItem(0) while 1: - # print "State is", self.hierList.GetItemState(handle, -1) + # print("State is", self.hierList.GetItemState(handle, -1)) if self.hierList.GetItemState(handle, commctrl.TVIS_SELECTED): - # print "Item is ", self.hierList.ItemFromHandle(handle) + # print("Item is ", self.hierList.ItemFromHandle(handle)) return self.hierList.ItemFromHandle(handle) handle = self.hierList.GetNextSiblingItem(handle) diff --git a/Pythonwin/win32util.cpp b/Pythonwin/win32util.cpp index 294301f7d1..529aae5281 100644 --- a/Pythonwin/win32util.cpp +++ b/Pythonwin/win32util.cpp @@ -933,7 +933,7 @@ BOOL ParseCharFormatTuple(PyObject *args, CHARFORMAT *pFmt) // @tupleitem 6|int|bPitchAndFamily|The charset. See the LOGFONT structure for details. // @tupleitem 7|string|faceName|The font name. - // @comm Executing d=win32ui.CreateFontDialog(); d.DoModal(); print d.GetCharFormat() + // @comm Executing d=win32ui.CreateFontDialog(); d.DoModal(); print(d.GetCharFormat()) // will print a valid CHARFORMAT tuple. } diff --git a/SWIG/swig_lib/timers.i b/SWIG/swig_lib/timers.i index 35924ae56a..1d90e699d3 100644 --- a/SWIG/swig_lib/timers.i +++ b/SWIG/swig_lib/timers.i @@ -134,7 +134,7 @@ performance. To use a timer, simply use code like this : timer_start(0) ... a bunch of Python code ... timer_stop(0) - print timer_elapsed(0)," seconds of CPU time" + print(timer_elapsed(0), " seconds of CPU time") %} #endif diff --git a/adodbapi/__init__.py b/adodbapi/__init__.py index 428bdf432a..94a04bee36 100644 --- a/adodbapi/__init__.py +++ b/adodbapi/__init__.py @@ -3,6 +3,7 @@ Copyright (C) 2002 Henrik Ekelund, version 2.1 by Vernon Cole * http://sourceforge.net/projects/adodbapi """ + import time # Re-exports to keep backward compatibility with existing code diff --git a/adodbapi/adodbapi.py b/adodbapi/adodbapi.py index 36a2c88961..1dcca42c1f 100644 --- a/adodbapi/adodbapi.py +++ b/adodbapi/adodbapi.py @@ -91,7 +91,7 @@ def getIndexedValue(obj, index): from collections.abc import Mapping -# --- define objects to smooth out Python3000 <-> Python 2.x differences +# --- define objects to smooth out Python3000 <-> Python 2 differences unicodeType = str longType = int StringTypes = str diff --git a/adodbapi/apibase.py b/adodbapi/apibase.py index d16265917f..19ae54814e 100644 --- a/adodbapi/apibase.py +++ b/adodbapi/apibase.py @@ -26,7 +26,7 @@ DateTime = type(NotImplemented) # should never be seen on win32 NullTypes = type(None) -# --- define objects to smooth out Python3 <-> Python 2.x differences +# --- define objects to smooth out Python3 <-> Python 2 differences unicodeType = str longType = int StringTypes = str @@ -55,7 +55,7 @@ def standardErrorHandler(connection, cursor, errorclass, errorvalue): raise errorclass(errorvalue) -# Note: _BaseException is defined differently between Python 2.x and 3.x +# Note: _BaseException is defined differently between Python 2 and 3 class Error(_BaseException): pass # Exception that is the base class of all other error # exceptions. You can use this to catch all errors with one diff --git a/adodbapi/examples/db_table_names.py b/adodbapi/examples/db_table_names.py index 2d7bf9df0d..907bdb85ea 100644 --- a/adodbapi/examples/db_table_names.py +++ b/adodbapi/examples/db_table_names.py @@ -1,4 +1,5 @@ """ db_table_names.py -- a simple demo for ADO database table listing.""" + import sys import adodbapi diff --git a/adodbapi/is64bit.py b/adodbapi/is64bit.py index 911c61931e..36a8c63e48 100644 --- a/adodbapi/is64bit.py +++ b/adodbapi/is64bit.py @@ -1,4 +1,5 @@ """is64bit.Python() --> boolean value of detected Python word size. is64bit.os() --> os build version""" + import sys diff --git a/adodbapi/process_connect_string.py b/adodbapi/process_connect_string.py index 3c3f9e7afa..806c0954e8 100644 --- a/adodbapi/process_connect_string.py +++ b/adodbapi/process_connect_string.py @@ -1,4 +1,5 @@ """ a clumsy attempt at a macro language to let the programmer execute code on the server (ex: determine 64bit)""" + from . import is64bit as is64bit diff --git a/adodbapi/quick_reference.md b/adodbapi/quick_reference.md index e4bc9f9cfe..a61cf0a6a2 100644 --- a/adodbapi/quick_reference.md +++ b/adodbapi/quick_reference.md @@ -643,22 +643,22 @@ This is the PEP standard method: row = crsr.fetchone() while row: value = row[1] * row[2] - print('Your {:10s} is worth {:10.2f}'.format(row[0], value)) + print("Your {:10s} is worth {:10.2f}".format(row[0], value)) row = crsr.fetchone() # returns None when no data remains As an extension, a Row object can also be indexed by column name: crsr.execute("SELECT prodname, price, qtyonhand FROM cheese") for row in crsr: # note extension: using crsr as an iterator - value = row['price'] * row['qtyonhand'] - print('Your {:10s} is worth {:10.2f}'.format(row['prodname'], value)) + value = row["price"] * row["qtyonhand"] + print("Your {:10s} is worth {:10.2f}".format(row["prodname"], value)) But, _really_ lazy programmers, like me, use the column names as attributes: crsr.execute("SELECT prodname, price, qtyonhand FROM cheese") for row in crsr: value = row.price * row.qtyonhand - print('Your {:10s} is worth {:10.2f}'.format(row.prodname, value)) + print("Your {:10s} is worth {:10.2f}".format(row.prodname, value)) Now, isn't that easier to read and understand? diff --git a/adodbapi/remote.py b/adodbapi/remote.py index ae22b5a7ea..910c6b49a6 100644 --- a/adodbapi/remote.py +++ b/adodbapi/remote.py @@ -62,7 +62,7 @@ if verbose: print(version) -# --- define objects to smooth out Python3 <-> Python 2.x differences +# --- define objects to smooth out Python3 <-> Python 2 differences unicodeType = str # this line will be altered by 2to3.py to '= str' longType = int # this line will be altered by 2to3.py to '= int' StringTypes = str diff --git a/adodbapi/schema_table.py b/adodbapi/schema_table.py index 21ad37e31d..636766bba5 100644 --- a/adodbapi/schema_table.py +++ b/adodbapi/schema_table.py @@ -1,4 +1,5 @@ """call using an open ADO connection --> list of table names""" + from . import adodbapi diff --git a/adodbapi/setup.py b/adodbapi/setup.py index d25869adf9..51c999e5b4 100644 --- a/adodbapi/setup.py +++ b/adodbapi/setup.py @@ -3,6 +3,7 @@ Adodbapi can be run on CPython 3.5 and later. or IronPython version 2.6 and later (in theory, possibly no longer in practice!) """ + CLASSIFIERS = """\ Development Status :: 5 - Production/Stable Intended Audience :: Developers diff --git a/adodbapi/test/adodbapitest.py b/adodbapi/test/adodbapitest.py index d7a4f2c9bc..a5d4fce867 100644 --- a/adodbapi/test/adodbapitest.py +++ b/adodbapi/test/adodbapitest.py @@ -1,4 +1,5 @@ """ Unit tests version 2.6.1.0 for adodbapi""" + """ adodbapi - A python DB API 2.0 interface to Microsoft ADO @@ -251,9 +252,9 @@ def testUserDefinedConversionForExactNumericTypes(self): ) finally: # now reset the converter to its original function - adodbapi.variantConversions[ - ado_consts.adNumeric - ] = oldconverter # Restore the original convertion function + adodbapi.variantConversions[ado_consts.adNumeric] = ( + oldconverter # Restore the original convertion function + ) def helpTestDataType( self, @@ -1387,13 +1388,13 @@ def testOkConnect(self): assert c is not None # def testStoredProcedure(self): - # crsr=self.conn.cursor() + # crsr = self.conn.cursor() # try: # crsr.execute("DROP PROCEDURE DeleteMeOnlyForTesting") # self.conn.commit() - # except: #Make sure it is empty + # except: # Make sure it is empty # pass - # spdef= """ + # spdef = """ # DELIMITER $$ # CREATE PROCEDURE DeleteMeOnlyForTesting (onein CHAR(10), twoin CHAR(10), OUT theout CHAR(20)) # DETERMINISTIC @@ -1405,16 +1406,20 @@ def testOkConnect(self): # # crsr.execute(spdef) # - # retvalues=crsr.callproc('DeleteMeOnlyForTesting',('Dodsworth','Anne',' ')) - # print 'return value (mysql)=',repr(crsr.returnValue) ### - # assert retvalues[0]=='Dodsworth', '%s is not "Dodsworth"'%repr(retvalues[0]) - # assert retvalues[1]=='Anne','%s is not "Anne"'%repr(retvalues[1]) - # assert retvalues[2]=='DodsworthAnne','%s is not "DodsworthAnne"'%repr(retvalues[2]) + # retvalues = crsr.callproc( + # "DeleteMeOnlyForTesting", ("Dodsworth", "Anne", " ") + # ) + # print("return value (mysql)=", repr(crsr.returnValue)) + # assert retvalues[0] == "Dodsworth", '%s is not "Dodsworth"' % repr(retvalues[0]) + # assert retvalues[1] == "Anne", '%s is not "Anne"' % repr(retvalues[1]) + # assert retvalues[2] == "DodsworthAnne", '%s is not "DodsworthAnne"' % repr( + # retvalues[2] + # ) # # try: # crsr.execute("DROP PROCEDURE, DeleteMeOnlyForTesting") # self.conn.commit() - # except: #Make sure it is empty + # except: # Make sure it is empty # pass @@ -1453,8 +1458,8 @@ def testOkConnect(self): assert c is not None # def testStoredProcedure(self): - # crsr=self.conn.cursor() - # spdef= """ + # crsr = self.conn.cursor() + # spdef = """ # CREATE OR REPLACE FUNCTION DeleteMeOnlyForTesting (text, text) # RETURNS text AS $funk$ # BEGIN @@ -1463,18 +1468,22 @@ def testOkConnect(self): # $funk$ # LANGUAGE SQL; # """ - # + # crsr.execute(spdef) - # retvalues = crsr.callproc('DeleteMeOnlyForTesting',('Dodsworth','Anne',' ')) - # ### print 'return value (pg)=',repr(crsr.returnValue) ### - # assert retvalues[0]=='Dodsworth', '%s is not "Dodsworth"'%repr(retvalues[0]) - # assert retvalues[1]=='Anne','%s is not "Anne"'%repr(retvalues[1]) - # assert retvalues[2]=='Dodsworth Anne','%s is not "Dodsworth Anne"'%repr(retvalues[2]) + # retvalues = crsr.callproc( + # "DeleteMeOnlyForTesting", ("Dodsworth", "Anne", " ") + # ) + # # print("return value (pg)=", repr(crsr.returnValue)) + # assert retvalues[0] == "Dodsworth", '%s is not "Dodsworth"' % repr(retvalues[0]) + # assert retvalues[1] == "Anne", '%s is not "Anne"' % repr(retvalues[1]) + # assert retvalues[2] == "Dodsworth Anne", '%s is not "Dodsworth Anne"' % repr( + # retvalues[2] + # ) # self.conn.rollback() # try: # crsr.execute("DROP PROCEDURE, DeleteMeOnlyForTesting") # self.conn.commit() - # except: #Make sure it is empty + # except: # Make sure it is empty # pass diff --git a/adodbapi/test/dbapi20.py b/adodbapi/test/dbapi20.py index 5f983cdc8d..2cd8335776 100644 --- a/adodbapi/test/dbapi20.py +++ b/adodbapi/test/dbapi20.py @@ -18,13 +18,13 @@ import time import unittest -if sys.version[0] >= "3": # python 3.x +if sys.version[0] >= "3": # Python 3 _BaseException = Exception def _failUnless(self, expr, msg=None): self.assertTrue(expr, msg) -else: # python 2.x +else: # Python 2 from exceptions import Exception as _BaseException def _failUnless(self, expr, msg=None): diff --git a/adodbapi/test/is64bit.py b/adodbapi/test/is64bit.py index ed390fad00..33d0244302 100644 --- a/adodbapi/test/is64bit.py +++ b/adodbapi/test/is64bit.py @@ -1,4 +1,5 @@ """is64bit.Python() --> boolean value of detected Python word size. is64bit.os() --> os build version""" + import sys diff --git a/adodbapi/test/test_adodbapi_dbapi20.py b/adodbapi/test/test_adodbapi_dbapi20.py index 6115138336..ccf7e7cbf5 100644 --- a/adodbapi/test/test_adodbapi_dbapi20.py +++ b/adodbapi/test/test_adodbapi_dbapi20.py @@ -51,9 +51,9 @@ else: conn_kws["host"] = host -conn_kws[ - "provider" -] = "Provider=MSOLEDBSQL;DataTypeCompatibility=80;MARS Connection=True;" +conn_kws["provider"] = ( + "Provider=MSOLEDBSQL;DataTypeCompatibility=80;MARS Connection=True;" +) connStr = "%(provider)s; %(security)s; Initial Catalog=%(name)s;Data Source=%(host)s" if onWindows and node != "z-PC": @@ -108,7 +108,7 @@ def setUp(self): if self.getTestMethodName() == "test_callproc": con = self._connect() engine = con.dbms_name - ## print('Using database Engine=%s' % engine) ## + # print(f"Using database Engine={engine}") if engine != "MS Jet": sql = """ create procedure templower diff --git a/com/help/active_directory.html b/com/help/active_directory.html index d7764002ba..4b93d8b0a7 100644 --- a/com/help/active_directory.html +++ b/com/help/active_directory.html @@ -114,7 +114,7 @@

Discovery

for i in servers: ex_servers.append(i.cn) - print '\texchange servers'," ".join(ex_servers) + print("\texchange servers"," ".join(ex_servers)) ex_first_store='CN=First Storage Group,CN=InformationStore,CN=%s,CN=Servers,CN=%s,%s'%(ex_servers[-1],admin_grp,ex_admin_grps) @@ -122,7 +122,7 @@

Discovery

for i in win32com.client.GetObject('LDAP://'+ex_first_store): ex_stores.append('cn='+i.cn+','+ex_first_store) - print '\tExchange stores:',"',".join(ex_stores) + print("\tExchange stores:","',".join(ex_stores))

Making the object

@@ -137,11 +137,11 @@

Making the object

This then allows things like:
-print('The last name: ',opends('fred').sn) #sn =surname +print("The last name: ",opends("fred").sn) #sn =surname
or to get the groups fred is a member of
-print("groups=',opends('fred').memberOf) +print("groups=",opends("fred").memberOf) def opends(loc,server=''): @@ -189,23 +189,23 @@

What does the object have?

def ad_dict(ldapobj,attr_dict={},recurse=0,auth=1,filter=()): if ldapobj.find(',')==-1: ldapobj='cn='+ldapobj+','+Ad.ldap_main_loc if auth: #setup authenticated connections - if debug: print 'auth' + if debug: print("auth") adobj=opends(ldapobj) - #if debug: print 'authenticated to',ldapobj + # if debug: print("authenticated to",ldapobj) else: adobj=win32com.client.GetObject('LDAP://'+ldapobj) - if debug: print 'connected to',ldapobj + if debug: print("connected to",ldapobj) if not(filter): #check for children for i in adobj: - if debug: print '****at',i.cn,str(adobj.cn) + if debug: print("****at",i.cn,str(adobj.cn)) if recurse: pass #get children's attributes too #attr_dict[i.distinguishedName]={} #get_all(i.distinguishedName,attr_dict[i.distinguishedName],recurse,auth) - if debug: print 'getting schema' + if debug: print("getting schema") schema_obj=win32com.client.GetObject(adobj.schema) for i in schema_obj.MandatoryProperties: if i =='nTSecurityDescriptor':continue #takes a long time, skip it @@ -246,7 +246,7 @@

The time property

user=opends('fred') -print 'time in seconds',conv_time(user.pwdLastSet.lowpart,user.pwdLastSet.highpart) +print("time in seconds",conv_time(user.pwdLastSet.lowpart,user.pwdLastSet.highpart)) user.pwdLastSet returns a com object, not a python data type. diff --git a/com/help/adsi.html b/com/help/adsi.html index 6fd2ab119e..d97b0d6838 100644 --- a/com/help/adsi.html +++ b/com/help/adsi.html @@ -152,7 +152,7 @@

Getting/Modify user info

myDSObject.Getinfo() # To access a user's data try: attribute = myDSObject.Get('Extension-Attribute-1') -print attribute +print(attribute) # To modify a user try: myDSObject.Put('Extension-Attribute-1','barney was here') myDSObject.Setinfo() @@ -188,7 +188,7 @@

Deleting a user from exchange

dsobj.Delete("OrganizationalPerson", "cn="+login) dsobj.Setinfo() except: - print 'Error deleting '+login, sys.exc_type , sys.exc_value + print("Error deleting "+login, sys.exc_type , sys.exc_value)


@@ -245,7 +245,7 @@

Recursively listing all unique members of a distribution elif dsobj.Class=='Public-Folder': pass else: - print 'skipped',dsobj.Class,dsobj.uid + print("skipped",dsobj.Class,dsobj.uid) return user_dict diff --git a/com/help/mts.d b/com/help/mts.d index 2e20835073..321091b6e1 100644 --- a/com/help/mts.d +++ b/com/help/mts.d @@ -83,9 +83,9 @@ from win32com.server.exception import COMException import win32com.server.util import win32com.client.dynamic -#to generate guids use: -#import pythoncom -#print pythoncom.CreateGuid() +# to generate guids use: +# import pythoncom +# print(pythoncom.CreateGuid()) class Mts: # COM attributes. diff --git a/com/pythoncom.py b/com/pythoncom.py index 2180ecc32e..ef68dc6666 100644 --- a/com/pythoncom.py +++ b/com/pythoncom.py @@ -1,4 +1,4 @@ -# Magic utility that "redirects" to pythoncomxx.dll +# Magic utility that "redirects" to pythoncomXX.dll import pywintypes pywintypes.__import_pywin32_system_module__("pythoncom", globals()) diff --git a/com/win32com/HTML/QuickStartClientCom.html b/com/win32com/HTML/QuickStartClientCom.html index f3a0274256..c6e7c259fb 100644 --- a/com/win32com/HTML/QuickStartClientCom.html +++ b/com/win32com/HTML/QuickStartClientCom.html @@ -26,11 +26,11 @@

To use a COM object from Python

o = win32com.client.Dispatch("Object.Name")
o.Method()
o.property = "New Value"
-print o.property

+print(o.property)

Example

o = win32com.client.Dispatch("Excel.Application")
o.Visible = 1
-o.Workbooks.Add() # for office 97 – 95 a bit different!
+o.Workbooks.Add() # for office 97 – 95 a bit different!
o.Cells(1,1).Value = "Hello"

And we will see the word "Hello" appear in the top cell.

How do I know which methods and properties are available?

diff --git a/com/win32com/HTML/QuickStartServerCom.html b/com/win32com/HTML/QuickStartServerCom.html index b956daaf01..584e34e80d 100644 --- a/com/win32com/HTML/QuickStartServerCom.html +++ b/com/win32com/HTML/QuickStartServerCom.html @@ -39,7 +39,7 @@

Implement a stand-alone Python class with your functionality

This is obviously a very simple server. In particular, custom error handling would be needed for a production class server. In addition, there are some contrived properties just for demonstration purposes.

Make Unicode concessions

-

At this stage, Python and Unicode don’t really work well together. All strings which come from COM will actually be Unicode objects rather than string objects.

+

At this stage, Python and Unicode don’t really work well together. All strings which come from COM will actually be Unicode objects rather than string objects.

To make this code work in a COM environment, the last line of the "Hello" method must become:

@@ -85,7 +85,7 @@

Annotate the class with win32com specific attributes

_public_attrs_ = ['softspace', 'noCalls']

_readonly_attrs_ = ['noCalls']

def __init__(self):

-

[Same from here…]

+

[Same from here…]

Registering and assigning a CLSID for the object

@@ -93,7 +93,7 @@

Annotate the class with win32com specific attributes

Generating the CLSID

Microsoft Visual C++ comes with various tools for generating CLSID's, which are quite suitable. Alternatively, the pythoncom module exports the function CreateGuid() to generate these identifiers.

>>> import pythoncom
->>> print pythoncom.CreateGuid()
+>>> print(pythoncom.CreateGuid())
{7CC9F362-486D-11D1-BB48-0000E838A65F}

Obviously the GUID that you get will be different than that displayed here.

Preparing for registration of the Class

@@ -179,13 +179,13 @@

Exception Handling

Default Policy attributes

The default policy object has a few special attributes that define who the object is exposed to COM. The example above shows the _public_methods attribute, but this section describes all such attributes in detail.

_public_methods_
-

Required list of strings, containing the names of all methods to be exposed to COM. It is possible this will be enhanced in the future (eg, possibly '*' will be recognised to say all methods, or some other ideas…)

+

Required list of strings, containing the names of all methods to be exposed to COM. It is possible this will be enhanced in the future (eg, possibly '*' will be recognised to say all methods, or some other ideas…)

_public_attrs_

Optional list of strings containing all attribute names to be exposed, both for reading and writing. The attribute names must be valid instance variables.

_readonly_attrs_

Optional list of strings defining the name of attributes exposed read-only.

_com_interfaces_
-

Optional list of IIDs exposed by this object. If this attribute is missing, IID_IDispatch is assumed (ie, if not supplied, the COM object will be created as a normal Automation object.

+

Optional list of IIDs exposed by this object. If this attribute is missing, IID_IDispatch is assumed (ie, if not supplied, the COM object will be created as a normal Automation object).

and actual instance attributes:

_dynamic_ : optional method

_value_ : optional attribute

diff --git a/com/win32com/client/CLSIDToClass.py b/com/win32com/client/CLSIDToClass.py index fde3274332..88b742e0ac 100644 --- a/com/win32com/client/CLSIDToClass.py +++ b/com/win32com/client/CLSIDToClass.py @@ -16,6 +16,7 @@ This obviously applies to all cooperating objects, not just DAO and Access. """ + mapCLSIDToClass = {} diff --git a/com/win32com/client/__init__.py b/com/win32com/client/__init__.py index 6f8ad07088..36f2c1d778 100644 --- a/com/win32com/client/__init__.py +++ b/com/win32com/client/__init__.py @@ -303,7 +303,7 @@ class object that derives from three classes: >>> class IEEvents: ... def OnVisible(self, visible): - ... print "Visible changed:", visible + ... print("Visible changed:", visible) ... >>> ie = DispatchWithEvents("InternetExplorer.Application", IEEvents) >>> ie.Visible = 1 @@ -358,7 +358,7 @@ def WithEvents(disp, user_event_class): >>> class IEEvents: ... def OnVisible(self, visible): - ... print "Visible changed:", visible + ... print("Visible changed:", visible) ... >>> ie = Dispatch("InternetExplorer.Application") >>> ie_events = WithEvents(ie, IEEvents) @@ -437,7 +437,7 @@ def getevents(clsid): >>> >>> class InternetExplorerEvents(win32com.client.getevents("InternetExplorer.Application.1")): ... def OnVisible(self, Visible): - ... print "Visibility changed: ", Visible + ... print("Visibility changed: ", Visible) ... >>> >>> ie=win32com.client.Dispatch("InternetExplorer.Application.1") diff --git a/com/win32com/client/build.py b/com/win32com/client/build.py index 1035ecdff9..8318b88949 100644 --- a/com/win32com/client/build.py +++ b/com/win32com/client/build.py @@ -69,9 +69,7 @@ class NotSupportedException(Exception): pythoncom.VT_VOID, ] -NoTranslateMap = {} -for v in NoTranslateTypes: - NoTranslateMap[v] = None +NoTranslateMap = set(NoTranslateTypes) class MapEntry: diff --git a/com/win32com/client/combrowse.py b/com/win32com/client/combrowse.py index 18576251ee..a5e76a85ba 100644 --- a/com/win32com/client/combrowse.py +++ b/com/win32com/client/combrowse.py @@ -22,6 +22,7 @@ work. """ + import sys import pythoncom diff --git a/com/win32com/client/connect.py b/com/win32com/client/connect.py index 24788204ec..7cb3969464 100644 --- a/com/win32com/client/connect.py +++ b/com/win32com/client/connect.py @@ -1,4 +1,5 @@ """Utilities for working with Connections""" + import pythoncom import win32com.server.util diff --git a/com/win32com/client/dynamic.py b/com/win32com/client/dynamic.py index dc938e8cbe..51d4702f8a 100644 --- a/com/win32com/client/dynamic.py +++ b/com/win32com/client/dynamic.py @@ -15,6 +15,7 @@ >>> xl.Visible = 1 # The Excel window becomes visible. """ + import traceback import types @@ -234,7 +235,7 @@ def __repr__(self): return "" % (self._username_) def __str__(self): - # __str__ is used when the user does "print object", so we gracefully + # __str__ is used when the user does "print(object)", so we gracefully # fall back to the __repr__ if the object has no default method. try: return str(self.__call__()) @@ -330,7 +331,7 @@ def __getitem__(self, index): # syver modified def __setitem__(self, index, *args): # XXX - todo - We should support calling Item() here too! - # print "__setitem__ with", index, args + # print("__setitem__ with", index, args) if self._olerepr_.defaultDispatchName: invkind, dispid = self._find_dispatch_type_( self._olerepr_.defaultDispatchName @@ -414,8 +415,8 @@ def _make_method_(self, name): ) methodCode = "\n".join(methodCodeList) try: - # print "Method code for %s is:\n" % self._username_, methodCode - # self._print_details_() + # print(f"Method code for {self._username_} is:\n", methodCode) + # self._print_details_() codeObject = compile(methodCode, "" % self._username_, "exec") # Exec the code object tempNameSpace = {} diff --git a/com/win32com/client/gencache.py b/com/win32com/client/gencache.py index debe796213..cc23afdf7d 100644 --- a/com/win32com/client/gencache.py +++ b/com/win32com/client/gencache.py @@ -20,6 +20,7 @@ Currently just uses a pickled dictionary, but should used some sort of indexed file. Maybe an OLE2 compound file, or a bsddb file? """ + import glob import os import sys @@ -458,7 +459,7 @@ def EnsureModule( # If we get an ImportError # We may still find a valid cache file under a different MinorVersion # # (which windows will search out for us) - # print "Loading reg typelib", typelibCLSID, major, minor, lcid + # print("Loading reg typelib", typelibCLSID, major, minor, lcid) module = None try: tlbAttr = pythoncom.LoadRegTypeLib( @@ -467,7 +468,7 @@ def EnsureModule( # if the above line doesn't throw a pythoncom.com_error, check if # it is actually a different lib than we requested, and if so, suck it in if tlbAttr[1] != lcid or tlbAttr[4] != minor: - # print "Trying 2nd minor #", tlbAttr[1], tlbAttr[3], tlbAttr[4] + # print("Trying 2nd minor #", tlbAttr[1], tlbAttr[3], tlbAttr[4]) try: module = GetModuleForTypelib( typelibCLSID, tlbAttr[1], tlbAttr[3], tlbAttr[4] @@ -525,7 +526,7 @@ def EnsureModule( module.MinorVersion != tlbAttributes[4] or genpy.makepy_version != module.makepy_version ): - # print "Version skew: %d, %d" % (module.MinorVersion, tlbAttributes[4]) + # print(f"Version skew: {module.MinorVersion}, {tlbAttributes[4]}") # try to erase the bad file from the cache try: os.unlink(filePath) @@ -550,21 +551,21 @@ def EnsureModule( ) filePath = filePathPrefix + ".py" filePathPyc = filePathPrefix + ".pyc" - # print "Trying py stat: ", filePath + # print("Trying py stat: ", filePath) fModTimeSet = 0 try: pyModTime = os.stat(filePath)[8] fModTimeSet = 1 except OSError as e: # If .py file fails, try .pyc file - # print "Trying pyc stat", filePathPyc + # print("Trying pyc stat", filePathPyc) try: pyModTime = os.stat(filePathPyc)[8] fModTimeSet = 1 except OSError as e: pass - # print "Trying stat typelib", pyModTime - # print str(typLibPath) + # print("Trying stat typelib", pyModTime) + # print(typLibPath) typLibModTime = os.stat(typLibPath)[8] if fModTimeSet and (typLibModTime > pyModTime): bReloadNeeded = 1 @@ -598,7 +599,7 @@ def EnsureModule( # remember and return versionRedirectMap[key] = ret return ret - # print "Rebuilding: ", major, minor + # print("Rebuilding: ", major, minor) module = MakeModuleForTypelib( typelibCLSID, lcid, @@ -768,12 +769,12 @@ def _Dump(): def usage(): usageString = """\ - Usage: gencache [-q] [-d] [-r] + Usage: gencache [-q] [-d] [-r] - -q - Quiet - -d - Dump the cache (typelibrary description and filename). - -r - Rebuild the cache dictionary from the existing .py files - """ + -q - Quiet + -d - Dump the cache (typelibrary description and filename). + -r - Rebuild the cache dictionary from the existing .py files + """ print(usageString) sys.exit(1) diff --git a/com/win32com/client/genpy.py b/com/win32com/client/genpy.py index 06f11889cd..d23cd3079f 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -207,10 +207,10 @@ def __init__(self, typeinfo, attr, doc=None, bForUser=1): name = typeinfo.GetNames(vdesc[0])[0] self.mapVars[name] = build.MapEntry(vdesc) - ## def WriteEnumerationHeaders(self, aliasItems, stream): - ## enumName = self.doc[0] - ## print >> stream "%s=constants # Compatibility with previous versions." % (enumName) - ## WriteAliasesForItem(self, aliasItems) + # def WriteEnumerationHeaders(self, aliasItems, stream): + # enumName = self.doc[0] + # print(f"{enumName}=constants # Compatibility with previous versions.", file=stream) + # WriteAliasesForItem(self, aliasItems) def WriteEnumerationItems(self, stream): num = 0 diff --git a/com/win32com/client/util.py b/com/win32com/client/util.py index 1925843ab3..33f5763367 100644 --- a/com/win32com/client/util.py +++ b/com/win32com/client/util.py @@ -3,6 +3,7 @@ This module contains utility functions, used primarily by advanced COM programmers, or other COM modules. """ + import pythoncom from win32com.client import Dispatch, _get_good_object_ diff --git a/com/win32com/makegw/makegw.py b/com/win32com/makegw/makegw.py index 196fce4276..92e3354628 100644 --- a/com/win32com/makegw/makegw.py +++ b/com/win32com/makegw/makegw.py @@ -144,11 +144,11 @@ def _write_ifc_h(f, interface): class Py{interface.name} : public Py{interface.base} {{ public: - MAKE_PYCOM_CTOR(Py{interface.name}); - static {interface.name} *GetI(PyObject *self); - static PyComTypeObject type; + MAKE_PYCOM_CTOR(Py{interface.name}); + static {interface.name} *GetI(PyObject *self); + static PyComTypeObject type; - // The Python methods + // The Python methods """ ) for method in interface.methods: @@ -159,8 +159,8 @@ class Py{interface.name} : public Py{interface.base} f"""\ protected: - Py{interface.name}(IUnknown *pdisp); - ~Py{interface.name}(); + Py{interface.name}(IUnknown *pdisp); + ~Py{interface.name}(); }}; """ ) @@ -175,9 +175,9 @@ def _write_ifc_cpp(f, interface): // Interface Implementation Py{name}::Py{name}(IUnknown *pdisp): - Py{base}(pdisp) + Py{base}(pdisp) {{ - ob_type = &type; + ob_type = &type; }} Py{name}::~Py{name}() @@ -186,7 +186,7 @@ def _write_ifc_cpp(f, interface): /* static */ {name} *Py{name}::GetI(PyObject *self) {{ - return ({name} *)Py{base}::GetI(self); + return ({name} *)Py{base}::GetI(self); }} """.format( @@ -203,18 +203,16 @@ def _write_ifc_cpp(f, interface): // @pymethod |Py{interfacename}|{method}|Description of {method}. PyObject *Py{interfacename}::{method}(PyObject *self, PyObject *args) {{ - {interfacename} *p{ptr} = GetI(self); - if ( p{ptr} == NULL ) - return NULL; + {interfacename} *p{ptr} = GetI(self); + if ( p{ptr} == NULL ) + return NULL; """.format( **strdict ) ) - argsParseTuple = ( - argsCOM - ) = ( - formatChars - ) = codePost = codePobjects = codeCobjects = cleanup = cleanup_gil = "" + argsParseTuple = argsCOM = formatChars = codePost = codePobjects = ( + codeCobjects + ) = cleanup = cleanup_gil = "" needConversion = 0 # if method.name=="Stat": import win32dbg;win32dbg.brk() for arg in method.args: @@ -282,14 +280,14 @@ def _write_ifc_cpp(f, interface): strdict["cleanup"] = cleanup strdict["cleanup_gil"] = cleanup_gil f.write( - """ HRESULT hr; - PY_INTERFACE_PRECALL; - hr = p{ptr}->{method}({argsCOM} ); + """ HRESULT hr; + PY_INTERFACE_PRECALL; + hr = p{ptr}->{method}({argsCOM} ); {cleanup} - PY_INTERFACE_POSTCALL; + PY_INTERFACE_POSTCALL; {cleanup_gil} - if ( FAILED(hr) ) - return PyCom_BuildPyException(hr, p{ptr}, IID_{interfacename} ); + if ( FAILED(hr) ) + return PyCom_BuildPyException(hr, p{ptr}, IID_{interfacename} ); """.format( **strdict ) @@ -336,14 +334,14 @@ def _write_ifc_cpp(f, interface): interfacebase = interface.base f.write( """\ - {{ NULL }} + {{ NULL }} }}; PyComTypeObject Py{name}::type("Py{name}", - &Py{interfacebase}::type, - sizeof(Py{name}), - Py{name}_methods, - GET_PYCOM_CTOR(Py{name})); + &Py{interfacebase}::type, + sizeof(Py{name}), + Py{name}_methods, + GET_PYCOM_CTOR(Py{name})); """.format( **locals() ) @@ -372,8 +370,8 @@ def _write_gw_h(f, interface): class {gname} : public {base_name}, public {name} {{ protected: - {gname}(PyObject *instance) : {base_name}(instance) {{ ; }} - PYGATEWAY_MAKE_SUPPORT2({gname}, {name}, IID_{name}, {base_name}) + {gname}(PyObject *instance) : {base_name}(instance) {{ ; }} + PYGATEWAY_MAKE_SUPPORT2({gname}, {name}, IID_{name}, {base_name}) """ ) @@ -420,9 +418,7 @@ def _write_gw_cpp(f, interface): // --------------------------------------------------- // // Gateway Implementation -""".format( - name=name, gname=gname, base_name=base_name - ) +""" ) for method in interface.methods: diff --git a/com/win32com/makegw/makegwenum.py b/com/win32com/makegw/makegwenum.py index d541307d12..662dff4b67 100644 --- a/com/win32com/makegw/makegwenum.py +++ b/com/win32com/makegw/makegwenum.py @@ -7,6 +7,7 @@ This module is notmally not used directly - the @makegw@ module automatically calls this. """ + # # INTERNAL FUNCTIONS # @@ -44,9 +45,9 @@ def _write_enumifc_cpp(f, interface): // Interface Implementation PyIEnum{enumtype}::PyIEnum{enumtype}(IUnknown *pdisp): - PyIUnknown(pdisp) + PyIUnknown(pdisp) {{ - ob_type = &type; + ob_type = &type; }} PyIEnum{enumtype}::~PyIEnum{enumtype}() @@ -55,141 +56,141 @@ def _write_enumifc_cpp(f, interface): /* static */ IEnum{enumtype} *PyIEnum{enumtype}::GetI(PyObject *self) {{ - return (IEnum{enumtype} *)PyIUnknown::GetI(self); + return (IEnum{enumtype} *)PyIUnknown::GetI(self); }} // @pymethod object|PyIEnum{enumtype}|Next|Retrieves a specified number of items in the enumeration sequence. PyObject *PyIEnum{enumtype}::Next(PyObject *self, PyObject *args) {{ - long celt = 1; - // @pyparm int|num|1|Number of items to retrieve. - if ( !PyArg_ParseTuple(args, "|l:Next", &celt) ) - return NULL; - - IEnum{enumtype} *pIE{enumtype} = GetI(self); - if ( pIE{enumtype} == NULL ) - return NULL; - - {arraydeclare} - if ( rgVar == NULL ) {{ - PyErr_SetString(PyExc_MemoryError, "allocating result {enumtype}s"); - return NULL; - }} - - int i; -/* for ( i = celt; i--; ) - // *** possibly init each structure element??? + long celt = 1; + // @pyparm int|num|1|Number of items to retrieve. + if ( !PyArg_ParseTuple(args, "|l:Next", &celt) ) + return NULL; + + IEnum{enumtype} *pIE{enumtype} = GetI(self); + if ( pIE{enumtype} == NULL ) + return NULL; + + {arraydeclare} + if ( rgVar == NULL ) {{ + PyErr_SetString(PyExc_MemoryError, "allocating result {enumtype}s"); + return NULL; + }} + + int i; +/* for ( i = celt; i--; ) + // *** possibly init each structure element??? */ - ULONG celtFetched = 0; - PY_INTERFACE_PRECALL; - HRESULT hr = pIE{enumtype}->Next(celt, rgVar, &celtFetched); - PY_INTERFACE_POSTCALL; - if ( HRESULT_CODE(hr) != ERROR_NO_MORE_ITEMS && FAILED(hr) ) - {{ - delete [] rgVar; - return PyCom_BuildPyException(hr,pIE{enumtype}, IID_IE{enumtype}); - }} - - PyObject *result = PyTuple_New(celtFetched); - if ( result != NULL ) - {{ - for ( i = celtFetched; i--; ) - {{ - {converter} - if ( ob == NULL ) - {{ - Py_DECREF(result); - result = NULL; - break; - }} - PyTuple_SET_ITEM(result, i, ob); - }} - }} - -/* for ( i = celtFetched; i--; ) - // *** possibly cleanup each structure element??? + ULONG celtFetched = 0; + PY_INTERFACE_PRECALL; + HRESULT hr = pIE{enumtype}->Next(celt, rgVar, &celtFetched); + PY_INTERFACE_POSTCALL; + if ( HRESULT_CODE(hr) != ERROR_NO_MORE_ITEMS && FAILED(hr) ) + {{ + delete [] rgVar; + return PyCom_BuildPyException(hr,pIE{enumtype}, IID_IE{enumtype}); + }} + + PyObject *result = PyTuple_New(celtFetched); + if ( result != NULL ) + {{ + for ( i = celtFetched; i--; ) + {{ + {converter} + if ( ob == NULL ) + {{ + Py_DECREF(result); + result = NULL; + break; + }} + PyTuple_SET_ITEM(result, i, ob); + }} + }} + +/* for ( i = celtFetched; i--; ) + // *** possibly cleanup each structure element??? */ - delete [] rgVar; - return result; + delete [] rgVar; + return result; }} // @pymethod |PyIEnum{enumtype}|Skip|Skips over the next specified elementes. PyObject *PyIEnum{enumtype}::Skip(PyObject *self, PyObject *args) {{ - long celt; - if ( !PyArg_ParseTuple(args, "l:Skip", &celt) ) - return NULL; - - IEnum{enumtype} *pIE{enumtype} = GetI(self); - if ( pIE{enumtype} == NULL ) - return NULL; - - PY_INTERFACE_PRECALL; - HRESULT hr = pIE{enumtype}->Skip(celt); - PY_INTERFACE_POSTCALL; - if ( FAILED(hr) ) - return PyCom_BuildPyException(hr, pIE{enumtype}, IID_IE{enumtype}); - - Py_INCREF(Py_None); - return Py_None; + long celt; + if ( !PyArg_ParseTuple(args, "l:Skip", &celt) ) + return NULL; + + IEnum{enumtype} *pIE{enumtype} = GetI(self); + if ( pIE{enumtype} == NULL ) + return NULL; + + PY_INTERFACE_PRECALL; + HRESULT hr = pIE{enumtype}->Skip(celt); + PY_INTERFACE_POSTCALL; + if ( FAILED(hr) ) + return PyCom_BuildPyException(hr, pIE{enumtype}, IID_IE{enumtype}); + + Py_INCREF(Py_None); + return Py_None; }} // @pymethod |PyIEnum{enumtype}|Reset|Resets the enumeration sequence to the beginning. PyObject *PyIEnum{enumtype}::Reset(PyObject *self, PyObject *args) {{ - if ( !PyArg_ParseTuple(args, ":Reset") ) - return NULL; + if ( !PyArg_ParseTuple(args, ":Reset") ) + return NULL; - IEnum{enumtype} *pIE{enumtype} = GetI(self); - if ( pIE{enumtype} == NULL ) - return NULL; + IEnum{enumtype} *pIE{enumtype} = GetI(self); + if ( pIE{enumtype} == NULL ) + return NULL; - PY_INTERFACE_PRECALL; - HRESULT hr = pIE{enumtype}->Reset(); - PY_INTERFACE_POSTCALL; - if ( FAILED(hr) ) - return PyCom_BuildPyException(hr, pIE{enumtype}, IID_IE{enumtype}); + PY_INTERFACE_PRECALL; + HRESULT hr = pIE{enumtype}->Reset(); + PY_INTERFACE_POSTCALL; + if ( FAILED(hr) ) + return PyCom_BuildPyException(hr, pIE{enumtype}, IID_IE{enumtype}); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; }} // @pymethod |PyIEnum{enumtype}|Clone|Creates another enumerator that contains the same enumeration state as the current one PyObject *PyIEnum{enumtype}::Clone(PyObject *self, PyObject *args) {{ - if ( !PyArg_ParseTuple(args, ":Clone") ) - return NULL; + if ( !PyArg_ParseTuple(args, ":Clone") ) + return NULL; - IEnum{enumtype} *pIE{enumtype} = GetI(self); - if ( pIE{enumtype} == NULL ) - return NULL; + IEnum{enumtype} *pIE{enumtype} = GetI(self); + if ( pIE{enumtype} == NULL ) + return NULL; - IEnum{enumtype} *pClone; - PY_INTERFACE_PRECALL; - HRESULT hr = pIE{enumtype}->Clone(&pClone); - PY_INTERFACE_POSTCALL; - if ( FAILED(hr) ) - return PyCom_BuildPyException(hr, pIE{enumtype}, IID_IE{enumtype}); + IEnum{enumtype} *pClone; + PY_INTERFACE_PRECALL; + HRESULT hr = pIE{enumtype}->Clone(&pClone); + PY_INTERFACE_POSTCALL; + if ( FAILED(hr) ) + return PyCom_BuildPyException(hr, pIE{enumtype}, IID_IE{enumtype}); - return PyCom_PyObjectFromIUnknown(pClone, IID_IEnum{enumtype}, FALSE); + return PyCom_PyObjectFromIUnknown(pClone, IID_IEnum{enumtype}, FALSE); }} // @object PyIEnum{enumtype}|A Python interface to IEnum{enumtype} static struct PyMethodDef PyIEnum{enumtype}_methods[] = {{ - {{ "Next", PyIEnum{enumtype}::Next, 1 }}, // @pymeth Next|Retrieves a specified number of items in the enumeration sequence. - {{ "Skip", PyIEnum{enumtype}::Skip, 1 }}, // @pymeth Skip|Skips over the next specified elementes. - {{ "Reset", PyIEnum{enumtype}::Reset, 1 }}, // @pymeth Reset|Resets the enumeration sequence to the beginning. - {{ "Clone", PyIEnum{enumtype}::Clone, 1 }}, // @pymeth Clone|Creates another enumerator that contains the same enumeration state as the current one. - {{ NULL }} + {{ "Next", PyIEnum{enumtype}::Next, 1 }}, // @pymeth Next|Retrieves a specified number of items in the enumeration sequence. + {{ "Skip", PyIEnum{enumtype}::Skip, 1 }}, // @pymeth Skip|Skips over the next specified elementes. + {{ "Reset", PyIEnum{enumtype}::Reset, 1 }}, // @pymeth Reset|Resets the enumeration sequence to the beginning. + {{ "Clone", PyIEnum{enumtype}::Clone, 1 }}, // @pymeth Clone|Creates another enumerator that contains the same enumeration state as the current one. + {{ NULL }} }}; PyComEnumTypeObject PyIEnum{enumtype}::type("PyIEnum{enumtype}", - &PyIUnknown::type, - sizeof(PyIEnum{enumtype}), - PyIEnum{enumtype}_methods, - GET_PYCOM_CTOR(PyIEnum{enumtype})); + &PyIUnknown::type, + sizeof(PyIEnum{enumtype}), + PyIEnum{enumtype}_methods, + GET_PYCOM_CTOR(PyIEnum{enumtype})); """.format( **locals() ) @@ -230,103 +231,103 @@ def _write_enumgw_cpp(f, interface): /* [length_is][size_is][out] */ {argdeclare}, /* [out] */ ULONG __RPC_FAR *pCeltFetched) {{ - PY_GATEWAY_METHOD; - PyObject *result; - HRESULT hr = InvokeViaPolicy("Next", &result, "i", celt); - if ( FAILED(hr) ) - return hr; - - if ( !PySequence_Check(result) ) - goto error; - int len; - len = PyObject_Length(result); - if ( len == -1 ) - goto error; - if ( len > (int)celt) - len = celt; - - if ( pCeltFetched ) - *pCeltFetched = len; - - int i; - for ( i = 0; i < len; ++i ) - {{ - PyObject *ob = PySequence_GetItem(result, i); - if ( ob == NULL ) - goto error; - - {converter} - {{ - Py_DECREF(result); - return PyCom_SetCOMErrorFromPyException(IID_IEnum{enumtype}); - }} - }} - - Py_DECREF(result); - - return len < (int)celt ? S_FALSE : S_OK; + PY_GATEWAY_METHOD; + PyObject *result; + HRESULT hr = InvokeViaPolicy("Next", &result, "i", celt); + if ( FAILED(hr) ) + return hr; + + if ( !PySequence_Check(result) ) + goto error; + int len; + len = PyObject_Length(result); + if ( len == -1 ) + goto error; + if ( len > (int)celt) + len = celt; + + if ( pCeltFetched ) + *pCeltFetched = len; + + int i; + for ( i = 0; i < len; ++i ) + {{ + PyObject *ob = PySequence_GetItem(result, i); + if ( ob == NULL ) + goto error; + + {converter} + {{ + Py_DECREF(result); + return PyCom_SetCOMErrorFromPyException(IID_IEnum{enumtype}); + }} + }} + + Py_DECREF(result); + + return len < (int)celt ? S_FALSE : S_OK; error: - PyErr_Clear(); // just in case - Py_DECREF(result); - return PyCom_HandleIEnumNoSequence(IID_IEnum{enumtype}); + PyErr_Clear(); // just in case + Py_DECREF(result); + return PyCom_HandleIEnumNoSequence(IID_IEnum{enumtype}); }} STDMETHODIMP PyGEnum{enumtype}::Skip( /* [in] */ ULONG celt) {{ - PY_GATEWAY_METHOD; - return InvokeViaPolicy("Skip", NULL, "i", celt); + PY_GATEWAY_METHOD; + return InvokeViaPolicy("Skip", NULL, "i", celt); }} STDMETHODIMP PyGEnum{enumtype}::Reset(void) {{ - PY_GATEWAY_METHOD; - return InvokeViaPolicy("Reset"); + PY_GATEWAY_METHOD; + return InvokeViaPolicy("Reset"); }} STDMETHODIMP PyGEnum{enumtype}::Clone( /* [out] */ IEnum{enumtype} __RPC_FAR *__RPC_FAR *ppEnum) {{ - PY_GATEWAY_METHOD; - PyObject * result; - HRESULT hr = InvokeViaPolicy("Clone", &result); - if ( FAILED(hr) ) - return hr; - - /* - ** Make sure we have the right kind of object: we should have some kind - ** of IUnknown subclass wrapped into a PyIUnknown instance. - */ - if ( !PyIBase::is_object(result, &PyIUnknown::type) ) - {{ - /* the wrong kind of object was returned to us */ - Py_DECREF(result); - return PyCom_SetCOMErrorFromSimple(E_FAIL, IID_IEnum{enumtype}); - }} - - /* - ** Get the IUnknown out of the thing. note that the Python ob maintains - ** a reference, so we don't have to explicitly AddRef() here. - */ - IUnknown *punk = ((PyIUnknown *)result)->m_obj; - if ( !punk ) - {{ - /* damn. the object was released. */ - Py_DECREF(result); - return PyCom_SetCOMErrorFromSimple(E_FAIL, IID_IEnum{enumtype}); - }} - - /* - ** Get the interface we want. note it is returned with a refcount. - ** This QI is actually going to instantiate a PyGEnum{enumtype}. - */ - hr = punk->QueryInterface(IID_IEnum{enumtype}, (LPVOID *)ppEnum); - - /* done with the result; this DECREF is also for */ - Py_DECREF(result); - - return PyCom_CheckIEnumNextResult(hr, IID_IEnum{enumtype}); + PY_GATEWAY_METHOD; + PyObject * result; + HRESULT hr = InvokeViaPolicy("Clone", &result); + if ( FAILED(hr) ) + return hr; + + /* + ** Make sure we have the right kind of object: we should have some kind + ** of IUnknown subclass wrapped into a PyIUnknown instance. + */ + if ( !PyIBase::is_object(result, &PyIUnknown::type) ) + {{ + /* the wrong kind of object was returned to us */ + Py_DECREF(result); + return PyCom_SetCOMErrorFromSimple(E_FAIL, IID_IEnum{enumtype}); + }} + + /* + ** Get the IUnknown out of the thing. note that the Python ob maintains + ** a reference, so we don't have to explicitly AddRef() here. + */ + IUnknown *punk = ((PyIUnknown *)result)->m_obj; + if ( !punk ) + {{ + /* damn. the object was released. */ + Py_DECREF(result); + return PyCom_SetCOMErrorFromSimple(E_FAIL, IID_IEnum{enumtype}); + }} + + /* + ** Get the interface we want. note it is returned with a refcount. + ** This QI is actually going to instantiate a PyGEnum{enumtype}. + */ + hr = punk->QueryInterface(IID_IEnum{enumtype}, (LPVOID *)ppEnum); + + /* done with the result; this DECREF is also for */ + Py_DECREF(result); + + return PyCom_CheckIEnumNextResult(hr, IID_IEnum{enumtype}); }} """.format( **locals() diff --git a/com/win32com/makegw/makegwparse.py b/com/win32com/makegw/makegwparse.py index ba32c7fa36..63b4692b8a 100644 --- a/com/win32com/makegw/makegwparse.py +++ b/com/win32com/makegw/makegwparse.py @@ -11,6 +11,7 @@ See the @win32com.makegw@ module for information in building a COM interface """ + import re import traceback @@ -34,10 +35,10 @@ def __init__(self, msg="The required functionality is not supported"): class ArgFormatter: - """An instance for a specific type of argument. Knows how to convert itself""" + """An instance for a specific type of argument. Knows how to convert itself""" def __init__(self, arg, builtinIndirection, declaredIndirection=0): - # print 'init:', arg.name, builtinIndirection, declaredIndirection, arg.indirectionLevel + # print("init:", arg.name, builtinIndirection, declaredIndirection, arg.indirectionLevel) self.arg = arg self.builtinIndirection = builtinIndirection self.declaredIndirection = declaredIndirection @@ -64,7 +65,14 @@ def _IndirectPrefix(self, indirectionFrom, indirectionTo): raise error_not_supported("Can't indirect this far - please fix me :-)") def GetIndirectedArgName(self, indirectFrom, indirectionTo): - # print 'get:',self.arg.name, indirectFrom,self._GetDeclaredIndirection() + self.builtinIndirection, indirectionTo, self.arg.indirectionLevel + # print( + # "get:", + # self.arg.name, + # indirectFrom, + # self._GetDeclaredIndirection() + self.builtinIndirection, + # indirectionTo, + # self.arg.indirectionLevel, + # ) if indirectFrom is None: ### ACK! this does not account for [in][out] variables. @@ -206,7 +214,7 @@ def GetAutoduckString(self): ) def _GetPythonTypeDesc(self): - "Returns a string with the description of the type. Used for doco purposes" + "Returns a string with the description of the type. Used for doco purposes" return None def NeedUSES_CONVERSION(self): @@ -835,7 +843,7 @@ def BuildFromFile(self, file): if VERBOSE: print( - " Arg {} of type {}{} ({})".format( + " Arg {} of type {}{} ({})".format( self.name, self.type, "*" * self.indirectionLevel, self.inout ) ) @@ -895,7 +903,7 @@ def BuildFromFile(self, file): "Method %s - Only HRESULT return types are supported." % self.name ) # raise error_not_supported, if VERBOSE: - print(f" Method {self.result} {self.name}(") + print(f" Method {self.result} {self.name}(") while 1: arg = Argument(self.good_interface_names) try: diff --git a/com/win32com/server/connect.py b/com/win32com/server/connect.py index 5c9a2dfe4a..f9ffcd29ae 100644 --- a/com/win32com/server/connect.py +++ b/com/win32com/server/connect.py @@ -2,6 +2,7 @@ A collection of helpers for server side connection points. """ + import pythoncom import win32com.server.util import winerror diff --git a/com/win32com/server/dispatcher.py b/com/win32com/server/dispatcher.py index 0b21d3c089..8f7fa46127 100644 --- a/com/win32com/server/dispatcher.py +++ b/com/win32com/server/dispatcher.py @@ -2,6 +2,7 @@ Please see policy.py for a discussion on dispatchers and policies """ + import traceback from sys import exc_info diff --git a/com/win32com/server/exception.py b/com/win32com/server/exception.py index 5a4b304271..3004f5f43a 100644 --- a/com/win32com/server/exception.py +++ b/com/win32com/server/exception.py @@ -2,16 +2,17 @@ Exceptions - To better support COM exceptions, the framework allows for an instance to be - raised. This instance may have a certain number of known attributes, which are - translated into COM exception details. - - This means, for example, that Python could raise a COM exception that includes details - on a Help file and location, and a description for the user. - - This module provides a class which provides the necessary attributes. + To better support COM exceptions, the framework allows for an instance to be + raised. This instance may have a certain number of known attributes, which are + translated into COM exception details. + + This means, for example, that Python could raise a COM exception that includes details + on a Help file and location, and a description for the user. + + This module provides a class which provides the necessary attributes. """ + import sys import pythoncom @@ -90,10 +91,7 @@ def __repr__(self): def IsCOMException(t=None): if t is None: t = sys.exc_info()[0] - try: - return issubclass(t, pythoncom.com_error) - except TypeError: # 1.5 in -X mode? - return t is pythoncom.com_error + return issubclass(t, pythoncom.com_error) def IsCOMServerException(t=None): diff --git a/com/win32com/server/policy.py b/com/win32com/server/policy.py index 7d46d83d02..a36213eb9c 100644 --- a/com/win32com/server/policy.py +++ b/com/win32com/server/policy.py @@ -66,6 +66,7 @@ problem, rather than a COM error. """ + __author__ = "Greg Stein and Mark Hammond" import sys diff --git a/com/win32com/server/register.py b/com/win32com/server/register.py index 211e7428b6..ad38133176 100644 --- a/com/win32com/server/register.py +++ b/com/win32com/server/register.py @@ -6,6 +6,7 @@ construct the necessary Python object, and dispatch COM events. """ + import os import sys @@ -96,7 +97,7 @@ def _cat_registrar(): def _find_localserver_exe(mustfind): if sys.platform != "win32": return sys.executable - if pythoncom.__file__.find("_d") < 0: + if os.path.splitext(os.path.basename(pythoncom.__file__))[0].endswith("_d"): exeBaseName = "pythonw.exe" else: exeBaseName = "pythonw_d.exe" @@ -234,7 +235,13 @@ def RegisterServer( # Although now we prefer a 'loader' DLL if it exists to avoid some # manifest issues (the 'loader' DLL has a manifest, but pythoncom does not) pythoncom_dir = os.path.dirname(pythoncom.__file__) - suffix = "_d" if "_d" in pythoncom.__file__ else "" + suffix = ( + "_d" + if os.path.splitext(os.path.basename(pythoncom.__file__))[0].endswith( + "_d" + ) + else "" + ) # Always register with the full path to the DLLs. loadername = os.path.join( pythoncom_dir, diff --git a/com/win32com/server/util.py b/com/win32com/server/util.py index c46dd375d9..d8682460a9 100644 --- a/com/win32com/server/util.py +++ b/com/win32com/server/util.py @@ -1,5 +1,6 @@ """ General Server side utilities """ + import pythoncom import winerror @@ -144,7 +145,7 @@ def __init__(self, data=None, readOnly=0): self._public_methods_ = ["Item", "Count"] # This method is also used as the "default" method. - # Thus "print ob" will cause this to be called with zero + # Thus "print(ob)" will cause this to be called with zero # params. Handle this slightly more elegantly here. # Ideally the policy should handle this. def Item(self, *args): diff --git a/com/win32com/servers/dictionary.py b/com/win32com/servers/dictionary.py index c8ec986377..12cd3be5b1 100644 --- a/com/win32com/servers/dictionary.py +++ b/com/win32com/servers/dictionary.py @@ -27,11 +27,10 @@ the dictionary's keys. This allows for the following type of VB code: for each name in ob - debug.print name, ob(name) + debug.print(name, ob(name)) next """ - import pythoncom import pywintypes import winerror diff --git a/com/win32com/servers/perfmon.py b/com/win32com/servers/perfmon.py index 861c694097..0a0aaaf812 100644 --- a/com/win32com/servers/perfmon.py +++ b/com/win32com/servers/perfmon.py @@ -1,9 +1,10 @@ """A COM Server which exposes the NT Performance monitor in a very rudimentary way Usage from VB: - set ob = CreateObject("Python.PerfmonQuery") - freeBytes = ob.Query("Memory", "Available Bytes") + set ob = CreateObject("Python.PerfmonQuery") + freeBytes = ob.Query("Memory", "Available Bytes") """ + import pythoncom import win32pdhutil import winerror diff --git a/com/win32com/src/PythonCOMLoader.cpp b/com/win32com/src/PythonCOMLoader.cpp index daca9ac3ad..e9a149748b 100644 --- a/com/win32com/src/PythonCOMLoader.cpp +++ b/com/win32com/src/PythonCOMLoader.cpp @@ -1,5 +1,5 @@ -// *sob* - a simple loader for pythoncomxx.dll - but this DLL has a -// manifest referencing the CRT whereas pythoncomxx.dll does not. +// *sob* - a simple loader for pythoncomXX.dll - but this DLL has a +// manifest referencing the CRT whereas pythoncomXX.dll does not. #include "windows.h" #include "tchar.h" @@ -61,7 +61,7 @@ typedef HRESULT(STDAPICALLTYPE *PFNDllGetClassObject)(REFCLSID rclsid, REFIID ri PFNDllGetClassObject pfnDllGetClassObject = NULL; ///////////////////////////////////////////////////////////////////////////// -// Loads pythoncomxx.dll after activating our context and delegates the call to it. +// Loads pythoncomXX.dll after activating our context and delegates the call to it. STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv) { if (pfnDllGetClassObject == 0) { diff --git a/com/win32com/src/include/PythonCOM.h b/com/win32com/src/include/PythonCOM.h index e759971792..c8b7da82fa 100644 --- a/com/win32com/src/include/PythonCOM.h +++ b/com/win32com/src/include/PythonCOM.h @@ -77,10 +77,10 @@ #define PYCOM_EXPORT #else #ifdef BUILD_PYTHONCOM -/* We are building pythoncomxx.dll */ +/* We are building pythoncomXX.dll */ #define PYCOM_EXPORT __declspec(dllexport) #else -/* This module uses pythoncomxx.dll */ +/* This module uses pythoncomXX.dll */ #define PYCOM_EXPORT __declspec(dllimport) #ifndef _DEBUG #pragma comment(lib, "pythoncom.lib") diff --git a/com/win32com/src/oleargs.cpp b/com/win32com/src/oleargs.cpp index a28bbc0d64..c6fad6c215 100644 --- a/com/win32com/src/oleargs.cpp +++ b/com/win32com/src/oleargs.cpp @@ -127,7 +127,7 @@ BOOL PyCom_VariantFromPyObject(PyObject *obj, VARIANT *var) } V_VT(var) = VT_BSTR; } - // For 3.x, bool checks need to be above PyLong_Check, which now succeeds for booleans. + // For Python 3, bool checks need to be above PyLong_Check, which now succeeds for booleans. else if (obj == Py_True) { V_VT(var) = VT_BOOL; V_BOOL(var) = VARIANT_TRUE; @@ -593,7 +593,7 @@ static BOOL PyCom_SAFEARRAYFromPyObjectBuildDimension(PyObject *obj, SAFEARRAY * static long PyCom_CalculatePyObjectDimension(PyObject *obItemCheck, long lDimension, PyObject *ppyobDimensionDictionary) { // Buffers are a special case - they define 1 new dimension. - // Buffers supported sequence semantics in 2.x, but for some reason memoryview objects + // Buffers supported sequence semantics in Python 2, but for some reason memoryview objects // in py3k do not, so check separately if (PYWIN_BUFFER_CHECK(obItemCheck)) return lDimension + 1; diff --git a/com/win32com/test/pippo_server.py b/com/win32com/test/pippo_server.py index 1c2219d8c9..ac3a00c788 100644 --- a/com/win32com/test/pippo_server.py +++ b/com/win32com/test/pippo_server.py @@ -41,7 +41,10 @@ def Method3(self, in1): def BuildTypelib(): - from distutils.dep_util import newer + if sys.version_info >= (3, 8): + from setuptools.modified import newer + else: + from distutils.dep_util import newer this_dir = os.path.dirname(__file__) idl = os.path.abspath(os.path.join(this_dir, "pippo.idl")) diff --git a/com/win32com/test/testAccess.py b/com/win32com/test/testAccess.py index 1d41eb6fc5..50332db021 100644 --- a/com/win32com/test/testAccess.py +++ b/com/win32com/test/testAccess.py @@ -122,8 +122,8 @@ def DoDumpAccessInfo(dbname): forms = a.Forms print("There are %d forms open." % (len(forms))) # Uncommenting these lines means Access remains open. - # for form in forms: - # print " %s" % form.Name + # for form in forms: + # print(f" {form.Name}") reports = a.Reports print("There are %d reports open" % (len(reports))) finally: diff --git a/com/win32com/test/testCollections.py b/com/win32com/test/testCollections.py index 999c65b09f..10bfce775b 100644 --- a/com/win32com/test/testCollections.py +++ b/com/win32com/test/testCollections.py @@ -102,10 +102,10 @@ def TestEnum(quiet=None): TestEnumAgainst(o, check) ### This does not work! - # if not quiet: print "Indexed replace item test" - # o[2] = 'Replaced Item' - # check[2] = 'Replaced Item' - # TestEnumAgainst(o, check) + # if not quiet: print("Indexed replace item test") + # o[2] = 'Replaced Item' + # check[2] = 'Replaced Item' + # TestEnumAgainst(o, check) try: o() diff --git a/com/win32com/test/testExchange.py b/com/win32com/test/testExchange.py index bad0e121e6..fa2ac5cb05 100644 --- a/com/win32com/test/testExchange.py +++ b/com/win32com/test/testExchange.py @@ -75,8 +75,8 @@ def DumpFolders(session): def TestAddress(session): - # entry = session.GetAddressEntry("Skip") - # print entry + # entry = session.GetAddressEntry("Skip") + # print(entry) pass diff --git a/com/win32com/test/testGIT.py b/com/win32com/test/testGIT.py index 2ec6bc44b9..3f9a5f420a 100644 --- a/com/win32com/test/testGIT.py +++ b/com/win32com/test/testGIT.py @@ -134,7 +134,7 @@ def test(fn): if __name__ == "__main__": test(BeginThreadsSimpleMarshal) win32api.Sleep(500) - # Doing CoUninit here stop Pythoncom.dll hanging when DLLMain shuts-down the process + # Doing CoUninit here stop pythoncom.dll hanging when DLLMain shuts-down the process pythoncom.CoUninitialize() if pythoncom._GetInterfaceCount() != 0 or pythoncom._GetGatewayCount() != 0: print( diff --git a/com/win32com/test/testMarshal.py b/com/win32com/test/testMarshal.py index c57d445f87..6c9a6ce902 100644 --- a/com/win32com/test/testMarshal.py +++ b/com/win32com/test/testMarshal.py @@ -52,7 +52,7 @@ def _doTestInThread(self, interp): interp = win32com.client.Dispatch(interp) interp.Exec("import win32api") - # print "The test thread id is %d, Python.Interpreter's thread ID is %d" % (myThread, interp.Eval("win32api.GetCurrentThreadId()")) + # print(f"The test thread id is {myThread}, Python.Interpreter's thread ID is {interp.Eval('win32api.GetCurrentThreadId()')}") pythoncom.CoUninitialize() def BeginThreadsSimpleMarshal(self, numThreads): @@ -108,7 +108,7 @@ def BeginThreadsFastMarshal(self, numThreads): return threads, events def _DoTestMarshal(self, fn, bCoWait=0): - # print "The main thread is %d" % (win32api.GetCurrentThreadId()) + # print(f"The main thread is {win32api.GetCurrentThreadId()}") threads, events = fn(2) numFinished = 0 while 1: diff --git a/com/win32com/test/testPersist.py b/com/win32com/test/testPersist.py index 76f7d84c96..5ca6053f7d 100644 --- a/com/win32com/test/testPersist.py +++ b/com/win32com/test/testPersist.py @@ -45,7 +45,7 @@ def WriteAt(self, offset, data): print("WriteAt " + str(offset)) print("len " + str(len(data))) print("data:") - # print data + # print(data) if len(self.data) >= offset: newdata = self.data[0:offset] + data print(len(newdata)) diff --git a/com/win32com/test/testROT.py b/com/win32com/test/testROT.py index 5a4ccbcc8c..91e30894d5 100644 --- a/com/win32com/test/testROT.py +++ b/com/win32com/test/testROT.py @@ -22,7 +22,7 @@ def testit(self): raise # if num < 2: - # print "Only", num, "objects in the ROT - this is unusual" + # print("Only", num, "objects in the ROT - this is unusual") if __name__ == "__main__": diff --git a/com/win32com/test/util.py b/com/win32com/test/util.py index 73dfd1f2a0..a809875989 100644 --- a/com/win32com/test/util.py +++ b/com/win32com/test/util.py @@ -61,7 +61,7 @@ def RegisterPythonServer(filename, progids=None, verbose=0): ) break else: - # print "Skipping registration of '%s' - already registered" % filename + # print(f"Skipping registration of '{filename}' - already registered") return # needs registration - see if its likely! try: @@ -89,7 +89,7 @@ def RegisterPythonServer(filename, progids=None, verbose=0): cmd = f'{win32api.GetModuleFileName(0)} "{filename}" --unattended > nul 2>&1' if verbose: print("Registering engine", filename) - # print cmd + # print(cmd) rc = os.system(cmd) if rc: print("Registration command was:") diff --git a/com/win32com/universal.py b/com/win32com/universal.py index 6a87f6857e..055312acdc 100644 --- a/com/win32com/universal.py +++ b/com/win32com/universal.py @@ -68,7 +68,7 @@ def RegisterInterfaces(typelibGUID, lcid, major, minor, interface_names=None): raise ValueError( f"Interface '{name}' does not exist in this cached typelib" ) - # print "Processing interface", name + # print("Processing interface", name) sub_mod = gencache.GetModuleForCLSID(iid) is_dispatch = getattr(sub_mod, name + "_vtables_dispatch_", None) method_defs = getattr(sub_mod, name + "_vtables_", None) @@ -100,10 +100,10 @@ def _CalcTypeSize(typeTuple): # is trying to. We need to better place to warn about this, but it # isn't here. # try: - # import warnings - # warnings.warn("warning: records are known to not work for vtable interfaces") + # import warnings + # warnings.warn("warning: records are known to not work for vtable interfaces") # except ImportError: - # print "warning: records are known to not work for vtable interfaces" + # print("warning: records are known to not work for vtable interfaces") cb = _univgw.SizeOfVT(pythoncom.VT_PTR)[1] # cb = typeInfo.GetTypeAttr().cbSizeInstance else: diff --git a/com/win32com/util.py b/com/win32com/util.py index 767e34a7cb..0a5748f1e1 100644 --- a/com/win32com/util.py +++ b/com/win32com/util.py @@ -2,6 +2,7 @@ This module contains a collection of general purpose utility functions. """ + import pythoncom import win32api import win32con diff --git a/com/win32comext/axdebug/adb.py b/com/win32comext/axdebug/adb.py index 7f0984535d..2345ce5d69 100644 --- a/com/win32comext/axdebug/adb.py +++ b/com/win32comext/axdebug/adb.py @@ -1,5 +1,6 @@ """The glue between the Python debugger interface and the Active Debugger interface """ + import _thread import bdb import os diff --git a/com/win32comext/axdebug/contexts.py b/com/win32comext/axdebug/contexts.py index 8953f5ab9c..08443b2515 100644 --- a/com/win32comext/axdebug/contexts.py +++ b/com/win32comext/axdebug/contexts.py @@ -1,6 +1,7 @@ """ A module for managing the AXDebug I*Contexts """ + from . import adb, axdebug, gateways # Utility function for wrapping object created by this module. diff --git a/com/win32comext/axdebug/documents.py b/com/win32comext/axdebug/documents.py index 4b93e8c1d0..560901fb42 100644 --- a/com/win32comext/axdebug/documents.py +++ b/com/win32comext/axdebug/documents.py @@ -1,7 +1,6 @@ """ Management of documents for AXDebugging. """ - import pythoncom import win32api from win32com.server.util import unwrap diff --git a/com/win32comext/axscript/asputil.py b/com/win32comext/axscript/asputil.py index b61c35373e..ad1c878daa 100644 --- a/com/win32comext/axscript/asputil.py +++ b/com/win32comext/axscript/asputil.py @@ -1,7 +1,7 @@ """A utility module for ASP (Active Server Pages on MS Internet Info Server. Contains: - iif -- A utility function to avoid using "if" statements in ASP <% tags + iif -- A utility function to avoid using "if" statements in ASP <% tags """ diff --git a/com/win32comext/axscript/client/debug.py b/com/win32comext/axscript/client/debug.py index b1d7dabec7..bdae7aac62 100644 --- a/com/win32comext/axscript/client/debug.py +++ b/com/win32comext/axscript/client/debug.py @@ -99,7 +99,7 @@ def Close(self): self.adb.CloseApp() self.adb = None - # print "Close complete" + # print("Close complete") def IsAnyHost(self): "Do we have _any_ debugging interfaces installed?" diff --git a/com/win32comext/axscript/client/framework.py b/com/win32comext/axscript/client/framework.py index f94c553111..9dbdfd5533 100644 --- a/com/win32comext/axscript/client/framework.py +++ b/com/win32comext/axscript/client/framework.py @@ -6,6 +6,7 @@ There are classes defined for the engine itself, and for ScriptItems """ + import re import sys @@ -168,7 +169,7 @@ def Build(self, typeinfo, funcdesc): self.name = typeinfo.GetNames(self.dispid)[0] -# print "Event.Build() - Event Name is ", self.name +# print("Event.Build() - Event Name is ", self.name) class EventSink: @@ -207,7 +208,7 @@ def _invoke_(self, dispid, lcid, wFlags, args): event = self.events[dispid] except: raise Exception(scode=winerror.DISP_E_MEMBERNOTFOUND) - # print "Invoke for ", event, "on", self.myScriptItem, " - calling", self.myInvokeMethod + # print("Invoke for ", event, "on", self.myScriptItem, " - calling", self.myInvokeMethod) return self.myInvokeMethod(self.myScriptItem, event, lcid, wFlags, args) def GetSourceTypeInfo(self, typeinfo): @@ -352,16 +353,16 @@ def Register(self): if self.isRegistered: return # Get the type info to use to build this item. - # if not self.dispatch: - # id = self.parentItem.dispatch.GetIDsOfNames(self.name) - # print "DispID of me is", id - # result = self.parentItem.dispatch.Invoke(id, 0, pythoncom.DISPATCH_PROPERTYGET,1) - # if isinstance(result, pythoncom.TypeIIDs[pythoncom.IID_IDispatch]): - # self.dispatch = result - # else: - # print "*** No dispatch" - # return - # print "**** Made dispatch" + # if not self.dispatch: + # id = self.parentItem.dispatch.GetIDsOfNames(self.name) + # print("DispID of me is", id) + # result = self.parentItem.dispatch.Invoke(id, 0, pythoncom.DISPATCH_PROPERTYGET,1) + # if isinstance(result, pythoncom.TypeIIDs[pythoncom.IID_IDispatch]): + # self.dispatch = result + # else: + # print("*** No dispatch") + # return + # print("**** Made dispatch") self.isRegistered = 1 # Register the sub-items. for item in self.subItems.values(): @@ -516,7 +517,18 @@ def FindBuildSubItemEvents(self): subObj = self.GetCreateSubItem( self, name, result, axscript.SCRIPTITEM_ISVISIBLE ) - # print "subobj", name, "flags are", subObj.flags, "mydisp=", self.dispatch, "result disp=", result, "compare=", self.dispatch==result + # print( + # "subobj", + # name, + # "flags are", + # subObj.flags, + # "mydisp=", + # self.dispatch, + # "result disp=", + # result, + # "compare=", + # self.dispatch == result, + # ) subObj.BuildEvents() subObj.Register() except pythoncom.com_error: @@ -762,7 +774,7 @@ def GetScriptSite(self, iid): return self.scriptSite.QueryInterface(iid) def SetScriptState(self, state): - # print "SetScriptState with %s - currentstate = %s" % (state_map.get(state),state_map.get(self.scriptState)) + # print(f"SetScriptState with {state_map.get(state)} - currentstate = {state_map.get(self.scriptState)}" if state == self.scriptState: return # If closed, allow no other state transitions @@ -1049,7 +1061,7 @@ def Reset(self): self.ChangeScriptState(axscript.SCRIPTSTATE_INITIALIZED) def ChangeScriptState(self, state): - # print " ChangeScriptState with %s - currentstate = %s" % (state_map.get(state),state_map.get(self.scriptState)) + # print(f" ChangeScriptState with {state_map.get(state)} - currentstate = {state_map.get(self.scriptState)}") self.DisableInterrupts() try: self.scriptState = state @@ -1076,7 +1088,7 @@ def ApplyInScriptedSection(self, codeBlock, fn, args): self.BeginScriptedSection() try: try: - # print "ApplyInSS", codeBlock, fn, args + # print("ApplyInSS", codeBlock, fn, args) return self._ApplyInScriptedSection(fn, args) finally: if self.debugManager: diff --git a/com/win32comext/axscript/client/pyscript.py b/com/win32comext/axscript/client/pyscript.py index 0ce08fc35e..dfa52e9b9a 100644 --- a/com/win32comext/axscript/client/pyscript.py +++ b/com/win32comext/axscript/client/pyscript.py @@ -252,9 +252,9 @@ def RegisterNamedItem(self, item): if item.IsGlobal(): # Global items means sub-items are also added... for subitem in item.subItems.values(): - self.globalNameSpaceModule.__dict__[ - subitem.name - ] = subitem.attributeObject + self.globalNameSpaceModule.__dict__[subitem.name] = ( + subitem.attributeObject + ) # Also add all methods for name, entry in item.dispatchContainer._olerepr_.mapFuncs.items(): if not entry.hidden: diff --git a/com/win32comext/axscript/client/pyscript_rexec.py b/com/win32comext/axscript/client/pyscript_rexec.py index a07b5a1654..3224be89cf 100644 --- a/com/win32comext/axscript/client/pyscript_rexec.py +++ b/com/win32comext/axscript/client/pyscript_rexec.py @@ -31,7 +31,12 @@ class PyScriptRExec(pyscript.PyScript): _reg_threading_ = "Apartment" def _GetSupportedInterfaceSafetyOptions(self): - # print "**** calling", pyscript.PyScript._GetSupportedInterfaceSafetyOptions, "**->", pyscript.PyScript._GetSupportedInterfaceSafetyOptions(self) + # print( + # "**** calling", + # pyscript.PyScript._GetSupportedInterfaceSafetyOptions, + # "**->", + # pyscript.PyScript._GetSupportedInterfaceSafetyOptions(self), + # ) return ( INTERFACE_USES_DISPEX | INTERFACE_USES_SECURITY_MANAGER diff --git a/com/win32comext/axscript/demos/client/asp/caps.asp b/com/win32comext/axscript/demos/client/asp/caps.asp index 6b0342aa32..8ea7cf8de4 100644 --- a/com/win32comext/axscript/demos/client/asp/caps.asp +++ b/com/win32comext/axscript/demos/client/asp/caps.asp @@ -23,11 +23,11 @@ Response.Write("

Win32 username is "+win32api.GetUserName()) <% import sys -print sys.path +print(sys.path) from win32com.axscript.asputil import * -print "Hello" -print "There" -print "How are you" +print("Hello") +print("There") +print("How are you") %> <%bc = Server.CreateObject("MSWC.BrowserType")%> diff --git a/com/win32comext/axscript/demos/client/ie/CHARTPY.HTM b/com/win32comext/axscript/demos/client/ie/CHARTPY.HTM index 4bba12c19e..fe7d1b5fbd 100644 --- a/com/win32comext/axscript/demos/client/ie/CHARTPY.HTM +++ b/com/win32comext/axscript/demos/client/ie/CHARTPY.HTM @@ -75,7 +75,7 @@ def DoChartType(WhatType): # Turns horizontal gridlines on or off depending on value of chkHorizontal checkbox def DoHorizontalGrid(): - print ax.chkHorizontal.Checked + print(ax.chkHorizontal.Checked) if ax.chkHorizontal.Checked: ax.Chart1.HGridStyle = 1 else: diff --git a/com/win32comext/axscript/demos/client/ie/FOO.HTM b/com/win32comext/axscript/demos/client/ie/FOO.HTM index 840672ff9c..34a880fa8d 100644 --- a/com/win32comext/axscript/demos/client/ie/FOO.HTM +++ b/com/win32comext/axscript/demos/client/ie/FOO.HTM @@ -39,7 +39,7 @@ End Sub diff --git a/com/win32comext/axscript/demos/client/ie/calc.htm b/com/win32comext/axscript/demos/client/ie/calc.htm index 46ef9a41fe..8c190b1abd 100644 --- a/com/win32comext/axscript/demos/client/ie/calc.htm +++ b/com/win32comext/axscript/demos/client/ie/calc.htm @@ -10,7 +10,7 @@ numberButNames = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] def NumPressed(Num): - print "NumPressed", Num + print("NumPressed", Num) global FlagNewNum if FlagNewNum: ax.document.Keypad.ReadOut.Value = Num @@ -42,7 +42,7 @@ def Operation(Op, fn): global FlagNewNum, PendingOp, Accum ReadOut = ax.document.Keypad.ReadOut.Value - print "Operation", Op, ReadOut, PendingOp, Accum + print("Operation", Op, ReadOut, PendingOp, Accum) if FlagNewNum: # User is hitting op keys repeatedly, so don't do anything PendingOp = NullOp diff --git a/com/win32comext/axscript/demos/client/ie/dbgtest.htm b/com/win32comext/axscript/demos/client/ie/dbgtest.htm index 7ee9468d58..a36d83ceee 100644 --- a/com/win32comext/axscript/demos/client/ie/dbgtest.htm +++ b/com/win32comext/axscript/demos/client/ie/dbgtest.htm @@ -6,7 +6,7 @@ diff --git a/com/win32comext/axscript/demos/client/ie/foo2.htm b/com/win32comext/axscript/demos/client/ie/foo2.htm index d5e0c4a624..d967822b9e 100644 --- a/com/win32comext/axscript/demos/client/ie/foo2.htm +++ b/com/win32comext/axscript/demos/client/ie/foo2.htm @@ -8,9 +8,9 @@ @@ -36,10 +36,10 @@ @@ -54,7 +54,7 @@ - +
@@ -79,23 +79,23 @@ def foo1(): y = 14 for name, item in globals().items(): - print name, `item` + print(name, "item") alert ("Hello from AXCode") - print "Y is ",y + print("Y is ", y) def PythonGlobalFunction(): window.alert("Hello from Python - Im about to call JScript!") window.JScriptFunction() def Window_OnLoad(): - print "X is", x - print "a is", a -# print "------ GLOBALS ----------" + print("X is", x) + print("a is", a) +# print("------ GLOBALS ----------") # for n,v in globals().items(): -# print n,'=',v - print "MyForm is", MyForm - print "MyForm is repr", `MyForm` - print "MyForm.Button1 is", `MyForm.Button1` +# print(n, '=', v) + print("MyForm is", MyForm) + print("MyForm is repr", "MyForm") + print("MyForm.Button1 is", "MyForm.Button1") MyForm.Button1.Value = "Python Rules!" Form2.Button1.value = "Form2!" MyForm.Text1.value = document.location diff --git a/com/win32comext/axscript/demos/client/ie/mousetrack.htm b/com/win32comext/axscript/demos/client/ie/mousetrack.htm index d307a4a6fe..fee059b906 100644 --- a/com/win32comext/axscript/demos/client/ie/mousetrack.htm +++ b/com/win32comext/axscript/demos/client/ie/mousetrack.htm @@ -20,7 +20,7 @@