From ba9e475904a5c6c55635d1eda145c51627de43f3 Mon Sep 17 00:00:00 2001 From: Avasam Date: Thu, 10 Aug 2023 13:25:52 -0400 Subject: [PATCH 01/22] Cleanup unsupported python code (except for adodbapi) (#1990) --- Pythonwin/pywin/debugger/debugger.py | 9 ++-- Pythonwin/pywin/framework/app.py | 22 +++------ Pythonwin/pywin/framework/mdi_pychecker.py | 2 +- Pythonwin/pywin/framework/scriptutils.py | 7 ++- Pythonwin/pywin/framework/stdin.py | 2 +- Pythonwin/pywin/idle/PyParse.py | 2 +- Pythonwin/pywin/idle/readme.txt | 13 +++--- Pythonwin/pywin/mfc/dialog.py | 5 ++- Pythonwin/pywin/mfc/object.py | 2 +- Pythonwin/pywin/tools/browser.py | 19 ++------ Pythonwin/pywin/tools/hierlist.py | 11 +---- com/win32com/client/__init__.py | 8 ++-- com/win32com/client/build.py | 9 +--- com/win32com/client/combrowse.py | 4 +- com/win32com/client/genpy.py | 15 ++----- com/win32com/client/makepy.py | 10 +---- com/win32com/client/selecttlb.py | 4 +- com/win32com/demos/connect.py | 3 -- com/win32com/demos/excelRTDServer.py | 4 +- com/win32com/demos/iebutton.py | 2 +- com/win32com/demos/ietoolbar.py | 2 +- com/win32com/server/dispatcher.py | 5 --- com/win32com/server/register.py | 2 +- com/win32com/test/testPersist.py | 4 +- com/win32com/test/testPippo.py | 5 +-- com/win32com/test/testPyComTest.py | 42 ++--------------- com/win32com/test/testStreams.py | 2 +- com/win32com/test/testvb.py | 45 +++++++++---------- com/win32com/test/util.py | 4 -- .../axdebug/src/PyIDebugStackFrame.cpp | 2 +- com/win32comext/axscript/client/framework.py | 1 - com/win32comext/axscript/test/leakTest.py | 13 +++--- com/win32comext/axscript/test/testHost.py | 12 ----- com/win32comext/mapi/mapiutil.py | 1 - .../shell/demos/ITransferAdviseSink.py | 1 - .../taskscheduler/test/test_addtask_1.py | 3 +- .../taskscheduler/test/test_addtask_2.py | 4 +- pywin32_postinstall.py | 2 +- setup.py | 39 ++++++++-------- win32/Demos/BackupRead_BackupWrite.py | 1 - win32/Demos/OpenEncryptedFileRaw.py | 1 - win32/Demos/win32clipboardDemo.py | 5 +-- win32/Demos/win32gui_dialog.py | 2 +- win32/Demos/win32gui_menu.py | 5 --- win32/Demos/win32gui_taskbar.py | 5 --- win32/Lib/dbi.py | 27 ----------- win32/Lib/pywintypes.py | 2 +- win32/Lib/sspi.py | 4 +- win32/Lib/win32timezone.py | 10 ++--- win32/Lib/win32traceutil.py | 2 +- win32/Lib/winnt.py | 20 ++------- win32/help/win32net.html | 2 +- win32/scripts/regsetup.py | 2 +- win32/scripts/setup_d.py | 4 +- win32/src/PyHANDLE.cpp | 4 +- win32/test/test_clipboard.py | 2 +- win32/test/test_exceptions.py | 16 ++----- win32/test/test_pywintypes.py | 10 ++--- win32/test/test_sspi.py | 1 - win32/test/test_win32timezone.py | 11 ----- 60 files changed, 139 insertions(+), 339 deletions(-) delete mode 100644 win32/Lib/dbi.py diff --git a/Pythonwin/pywin/debugger/debugger.py b/Pythonwin/pywin/debugger/debugger.py index 3821854f2f..320e34ddf5 100644 --- a/Pythonwin/pywin/debugger/debugger.py +++ b/Pythonwin/pywin/debugger/debugger.py @@ -695,13 +695,12 @@ def user_exception(self, frame, exc_info): if self.get_option(OPT_STOP_EXCEPTIONS): frame.f_locals["__exception__"] = exc_type, exc_value print("Unhandled exception while debugging...") - # on both py2k and py3k, we may be called with exc_value + # We may be called with exc_value # being the args to the exception, or it may already be # instantiated (IOW, PyErr_Normalize() hasn't been - # called on the args). In py2k this is fine, but in - # py3k, traceback.print_exception fails. So on py3k - # we instantiate an exception instance to print. - if sys.version_info > (3,) and not isinstance(exc_value, BaseException): + # called on the args). traceback.print_exception fails. + # So we instantiate an exception instance to print. + if not isinstance(exc_value, BaseException): # they are args - may be a single item or already a tuple if not isinstance(exc_value, tuple): exc_value = (exc_value,) diff --git a/Pythonwin/pywin/framework/app.py b/Pythonwin/pywin/framework/app.py index b582423072..298a79b4fb 100644 --- a/Pythonwin/pywin/framework/app.py +++ b/Pythonwin/pywin/framework/app.py @@ -400,8 +400,8 @@ def OnButHomePage(self, id, code): ) -def Win32RawInput(prompt=None): - "Provide raw_input() for gui apps" +def Win32Input(prompt=None): + "Provide input() for gui apps" # flush stderr/out first. try: sys.stdout.flush() @@ -416,22 +416,10 @@ def Win32RawInput(prompt=None): return ret -def Win32Input(prompt=None): - "Provide input() for gui apps" - return eval(input(prompt)) - - def HookInput(): - try: - raw_input - # must be py2x... - sys.modules["__builtin__"].raw_input = Win32RawInput - sys.modules["__builtin__"].input = Win32Input - except NameError: - # must be py3k - import code - - sys.modules["builtins"].input = Win32RawInput + import code + + sys.modules["builtins"].input = Win32Input def HaveGoodGUI(): diff --git a/Pythonwin/pywin/framework/mdi_pychecker.py b/Pythonwin/pywin/framework/mdi_pychecker.py index db1662b46e..06fbcc82b0 100644 --- a/Pythonwin/pywin/framework/mdi_pychecker.py +++ b/Pythonwin/pywin/framework/mdi_pychecker.py @@ -17,7 +17,7 @@ ## the PATH. Example pychecker.bat: ## ## REM pychecker.bat -## C:\bin\python.exe C:\PYTHON23\Lib\site-packages\pychecker\checker.py %1 %2 %3 %4 %5 %6 %7 %8 %9 +## C:\bin\python.exe C:\PythonXX\Lib\site-packages\pychecker\checker.py %1 %2 %3 %4 %5 %6 %7 %8 %9 ## ## Adding it as default module in PythonWin: ## diff --git a/Pythonwin/pywin/framework/scriptutils.py b/Pythonwin/pywin/framework/scriptutils.py index 0f4830d42f..5bb8544d34 100644 --- a/Pythonwin/pywin/framework/scriptutils.py +++ b/Pythonwin/pywin/framework/scriptutils.py @@ -89,7 +89,7 @@ def IsOnPythonPath(path): # must check that the command line arg's path is in sys.path for syspath in sys.path: try: - # Python 1.5 and later allows an empty sys.path entry. + # sys.path can have an empty entry. if syspath and win32ui.FullPath(syspath) == path: return 1 except win32ui.error as details: @@ -305,7 +305,7 @@ def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None): # ignores any encoding decls (bad!). If we use binary mode we get # the raw bytes and Python looks at the encoding (good!) but \r\n # chars stay in place so Python throws a syntax error (bad!). - # So: so the binary thing and manually normalize \r\n. + # So: do the binary thing and manually normalize \r\n. try: f = open(script, "rb") except IOError as exc: @@ -438,8 +438,7 @@ def ImportFile(): newPath = None # note that some packages (*cough* email *cough*) use "lazy importers" # meaning sys.modules can change as a side-effect of looking at - # module.__file__ - so we must take a copy (ie, items() in py2k, - # list(items()) in py3k) + # module.__file__ - so we must take a copy (ie, list(items())) for key, mod in list(sys.modules.items()): if getattr(mod, "__file__", None): fname = mod.__file__ diff --git a/Pythonwin/pywin/framework/stdin.py b/Pythonwin/pywin/framework/stdin.py index 26c8895fd2..a9b56e9f15 100644 --- a/Pythonwin/pywin/framework/stdin.py +++ b/Pythonwin/pywin/framework/stdin.py @@ -140,7 +140,7 @@ def readlines(self, *sizehint): """ def fake_input(prompt=None): - """Replacement for raw_input() which pulls lines out of global test_input. + """Replacement for input() which pulls lines out of global test_input. For testing only! """ global test_input diff --git a/Pythonwin/pywin/idle/PyParse.py b/Pythonwin/pywin/idle/PyParse.py index 97629eee50..b11b4744e9 100644 --- a/Pythonwin/pywin/idle/PyParse.py +++ b/Pythonwin/pywin/idle/PyParse.py @@ -150,7 +150,7 @@ def set_str(self, str): # no way to tell the differences between output, >>> etc and # user input. Indeed, IDLE's first output line makes the rest # look like it's in an unclosed paren!: - # Python 1.5.2 (#0, Apr 13 1999, ... + # Python X.X.X (#0, Apr 13 1999, ... def find_good_parse_start(self, use_ps1, is_char_in_string=None): str, pos = self.str, None diff --git a/Pythonwin/pywin/idle/readme.txt b/Pythonwin/pywin/idle/readme.txt index 8ded39fc72..9a28195a22 100644 --- a/Pythonwin/pywin/idle/readme.txt +++ b/Pythonwin/pywin/idle/readme.txt @@ -2,15 +2,14 @@ Pythonwin IDLE directory ------------------------ This directory contains IDLE extensions used by -Pythonwin. In ALL cases, the files in this directory that also appear -in the main IDLE directory should be indentical to the latest available -for IDLE. +Pythonwin. The files in this directory that also appear in the main IDLE +directory are intended be indentical to the latest available for IDLE. -Eg, If you have Python 1.5.2 installed, the files in this -directory will be later than the IDLE versions. If you use IDLE from -the CVS sources, then the files should be identical. +If you use IDLE from the CVS sources, then the files should be +identical. If you have a Python version installed that is more recent +than when this release was made, then you may notice differences. Pythonwin will look for IDLE extensions first in this directory, then on the global sys.path. Thus, if you have IDLE installed and run it from the CVS sources, you may remove most of the extensions from this -directory, and the latest CVS version will then be used. +directory, and the latest CVS version will then be used. diff --git a/Pythonwin/pywin/mfc/dialog.py b/Pythonwin/pywin/mfc/dialog.py index 6e528d9b6a..280c025aa1 100644 --- a/Pythonwin/pywin/mfc/dialog.py +++ b/Pythonwin/pywin/mfc/dialog.py @@ -90,10 +90,11 @@ def items(self): def values(self): return list(self.data.values()) - # XXX - needs py3k work! - def has_key(self, key): + def __contains__(self, key): return key in self.data + has_key = __contains__ + class PrintDialog(Dialog): "Base class for a print dialog" diff --git a/Pythonwin/pywin/mfc/object.py b/Pythonwin/pywin/mfc/object.py index 70138b6ee2..063f835f76 100644 --- a/Pythonwin/pywin/mfc/object.py +++ b/Pythonwin/pywin/mfc/object.py @@ -23,7 +23,7 @@ def __getattr__( if o is not None: return getattr(o, attr) # Only raise this error for non "internal" names - - # Python may be calling __len__, __nonzero__, etc, so + # Python may be calling __len__, __bool__, etc, so # we dont want this exception if attr[0] != "_" and attr[-1] != "_": raise win32ui.error("The MFC object has died.") diff --git a/Pythonwin/pywin/tools/browser.py b/Pythonwin/pywin/tools/browser.py index 188993259c..6dfe3a24fa 100644 --- a/Pythonwin/pywin/tools/browser.py +++ b/Pythonwin/pywin/tools/browser.py @@ -241,21 +241,10 @@ def IsExpandable(self): return 1 def GetSubList(self): - ret = [] - # ret.append( MakeHLI( self.myobject.func_argcount, "Arg Count" )) - try: - ret.append(MakeHLI(self.myobject.func_argdefs, "Arg Defs")) - except AttributeError: - pass - try: - code = self.myobject.__code__ - globs = self.myobject.__globals__ - except AttributeError: - # must be py2.5 or earlier... - code = self.myobject.func_code - globs = self.myobject.func_globals - ret.append(MakeHLI(code, "Code")) - ret.append(MakeHLI(globs, "Globals")) + ret = [ + MakeHLI(self.myobject.__code__, "Code"), + MakeHLI(self.myobject.__globals__, "Globals"), + ] self.InsertDocString(ret) return ret diff --git a/Pythonwin/pywin/tools/hierlist.py b/Pythonwin/pywin/tools/hierlist.py index 2ab7f616dd..4f27da9a91 100644 --- a/Pythonwin/pywin/tools/hierlist.py +++ b/Pythonwin/pywin/tools/hierlist.py @@ -13,7 +13,6 @@ # choice. However, you should investigate using the tree control directly # to provide maximum flexibility (but with extra work). -import sys import commctrl import win32api @@ -123,12 +122,8 @@ def DeleteAllItems(self): def HierTerm(self): # Dont want notifies as we kill the list. parent = self.notify_parent # GetParentFrame() - if sys.version_info[0] < 3: - parent.HookNotify(None, commctrl.TVN_ITEMEXPANDINGA) - parent.HookNotify(None, commctrl.TVN_SELCHANGEDA) - else: - parent.HookNotify(None, commctrl.TVN_ITEMEXPANDINGW) - parent.HookNotify(None, commctrl.TVN_SELCHANGEDW) + parent.HookNotify(None, commctrl.TVN_ITEMEXPANDINGW) + parent.HookNotify(None, commctrl.TVN_SELCHANGEDW) parent.HookNotify(None, commctrl.NM_DBLCLK) self.DeleteAllItems() @@ -351,11 +346,9 @@ def GetBitmapColumn(self): def GetSelectedBitmapColumn(self): return None # same as other - # for py3k/rich-comp sorting compatibility. def __lt__(self, other): # we want unrelated items to be sortable... return id(self) < id(other) - # for py3k/rich-comp equality compatibility. def __eq__(self, other): return False diff --git a/com/win32com/client/__init__.py b/com/win32com/client/__init__.py index 3ce1120462..6e23e70540 100644 --- a/com/win32com/client/__init__.py +++ b/com/win32com/client/__init__.py @@ -623,7 +623,7 @@ def __init__(self, oobj=None): "__int__", "__iter__", "__len__", - "__nonzero__", + "__bool__", ]: if hasattr(dispobj, maybe): setattr(self, maybe, getattr(self, "__maybe" + maybe)) @@ -673,8 +673,8 @@ def __maybe__iter__(self): def __maybe__len__(self): return self.__dict__["_dispobj_"].__len__() - def __maybe__nonzero__(self): - return self.__dict__["_dispobj_"].__nonzero__() + def __maybe__bool__(self): + return self.__dict__["_dispobj_"].__bool__() # A very simple VARIANT class. Only to be used with poorly-implemented COM @@ -682,7 +682,7 @@ def __maybe__nonzero__(self): # is very pickly about the actual variant type (eg, isn't happy with a VT_I4, # which it would get from a Python integer), you can use this to force a # particular VT. -class VARIANT(object): +class VARIANT: def __init__(self, vt, value): self.varianttype = vt self._value = value diff --git a/com/win32com/client/build.py b/com/win32com/client/build.py index dc43aae0a9..84dacb566a 100644 --- a/com/win32com/client/build.py +++ b/com/win32com/client/build.py @@ -18,7 +18,6 @@ import datetime import string -import sys from keyword import iskeyword import pythoncom @@ -30,8 +29,6 @@ # literals like a quote char and backslashes makes life a little painful to # always render the string perfectly - so just punt and fall-back to a repr() def _makeDocString(s): - if sys.version_info < (3,): - s = s.encode("mbcs") return repr(s) @@ -631,8 +628,7 @@ def _BuildArgList(fdesc, names): while len(names) < numArgs: names.append("arg%d" % (len(names),)) # As per BuildCallList(), avoid huge lines. - # Hack a "\n" at the end of every 5th name - "strides" would be handy - # here but don't exist in 2.2 + # Hack a "\n" at the end of every 5th name for i in range(0, len(names), 5): names[i] = names[i] + "\n\t\t\t" return "," + ", ".join(names) @@ -667,7 +663,7 @@ def MakePublicAttributeName(className, is_global=False): # it would get picked up below className = "NONE" elif iskeyword(className): - # most keywords are lower case (except True, False etc in py3k) + # most keywords are lower case (except True, False, etc) ret = className.capitalize() # but those which aren't get forced upper. if ret == className: @@ -769,7 +765,6 @@ def BuildCallList( defArgVal = defUnnamedArg argName = MakePublicAttributeName(argName) - # insanely long lines with an 'encoding' flag crashes python 2.4.0 # keep 5 args per line # This may still fail if the arg names are insane, but that seems # unlikely. See also _BuildArgList() diff --git a/com/win32com/client/combrowse.py b/com/win32com/client/combrowse.py index be2e7805e0..6e1e836240 100644 --- a/com/win32com/client/combrowse.py +++ b/com/win32com/client/combrowse.py @@ -45,8 +45,8 @@ def GetSubList(self): HLIHeadingRegisterdTypeLibs(), ] - def __cmp__(self, other): - return cmp(self.name, other.name) + def __lt__(self, other): + return self.name < other.name class HLICOM(browser.HLIPythonObject): diff --git a/com/win32com/client/genpy.py b/com/win32com/client/genpy.py index a494815244..c00a77e190 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -107,16 +107,7 @@ def WriteSinkEventMap(obj, stream): # MI is used to join my writable helpers, and the OLE # classes. class WritableItem: - # __cmp__ used for sorting in py2x... - def __cmp__(self, other): - "Compare for sorting" - ret = cmp(self.order, other.order) - if ret == 0 and self.doc: - ret = cmp(self.doc[0], other.doc[0]) - return ret - - # ... but not used in py3k - __lt__ minimum needed there - def __lt__(self, other): # py3k variant + def __lt__(self, other): if self.order == other.order: return self.doc < other.doc return self.order < other.order @@ -747,12 +738,12 @@ def WriteClassBody(self, generator): ) for line in ret: print(line, file=stream) - # Also include a __nonzero__ + # Also include a __bool__ print( "\t#This class has a __len__ - this is needed so 'if object:' always returns TRUE.", file=stream, ) - print("\tdef __nonzero__(self):", file=stream) + print("\tdef __bool__(self):", file=stream) print("\t\treturn True", file=stream) diff --git a/com/win32com/client/makepy.py b/com/win32com/client/makepy.py index 901c974296..18974305b4 100644 --- a/com/win32com/client/makepy.py +++ b/com/win32com/client/makepy.py @@ -72,8 +72,6 @@ bForDemandDefault = 0 # Default value of bForDemand - toggle this to change the world - see also gencache.py -error = "makepy.error" - def usage(): sys.stderr.write(usageHelp) @@ -407,7 +405,7 @@ def main(): elif o == "-d": bForDemand = not bForDemand - except (getopt.error, error) as msg: + except getopt.error as msg: sys.stderr.write(str(msg) + "\n") usage() @@ -427,12 +425,8 @@ def main(): path = os.path.dirname(outputName) if path != "" and not os.path.exists(path): os.makedirs(path) - if sys.version_info > (3, 0): - f = open(outputName, "wt", encoding="mbcs") - else: - import codecs # not available in py3k. + f = open(outputName, "wt", encoding="mbcs") - f = codecs.open(outputName, "w", "mbcs") else: f = None diff --git a/com/win32com/client/selecttlb.py b/com/win32com/client/selecttlb.py index bb21a42915..1337bc468b 100644 --- a/com/win32com/client/selecttlb.py +++ b/com/win32com/client/selecttlb.py @@ -27,7 +27,7 @@ def __getitem__(self, item): return self.ver_desc raise IndexError("Cant index me!") - def __lt__(self, other): # rich-cmp/py3k-friendly version + def __lt__(self, other): me = ( (self.ver_desc or "").lower(), (self.desc or "").lower(), @@ -42,7 +42,7 @@ def __lt__(self, other): # rich-cmp/py3k-friendly version ) return me < them - def __eq__(self, other): # rich-cmp/py3k-friendly version + def __eq__(self, other): return ( (self.ver_desc or "").lower() == (other.ver_desc or "").lower() and (self.desc or "").lower() == (other.desc or "").lower() diff --git a/com/win32com/demos/connect.py b/com/win32com/demos/connect.py index cb5928b6a5..3099214c94 100644 --- a/com/win32com/demos/connect.py +++ b/com/win32com/demos/connect.py @@ -8,7 +8,6 @@ import pythoncom import win32com.server.connect import win32com.server.util -from win32com.server.exception import Exception # This is the IID of the Events interface both Client and Server support. IID_IConnectDemoEvents = pythoncom.MakeIID("{A4988850-49C3-11d0-AE5D-52342E000000}") @@ -50,8 +49,6 @@ def __init__(self): # A client must implement QI, and respond to a query for the Event interface. # In addition, it must provide a COM object (which server.util.wrap) does. def _query_interface_(self, iid): - import win32com.server.util - # Note that this seems like a necessary hack. I am responding to IID_IConnectDemoEvents # but only creating an IDispatch gateway object. if iid == IID_IConnectDemoEvents: diff --git a/com/win32com/demos/excelRTDServer.py b/com/win32com/demos/excelRTDServer.py index c50e1ac786..6eda469530 100644 --- a/com/win32com/demos/excelRTDServer.py +++ b/com/win32com/demos/excelRTDServer.py @@ -69,7 +69,7 @@ ) -class ExcelRTDServer(object): +class ExcelRTDServer: """Base RTDServer class. Provides most of the features needed to implement the IRtdServer interface. @@ -260,7 +260,7 @@ def OnServerTerminate(self): pass -class RTDTopic(object): +class RTDTopic: """Base RTD Topic. Only method required by our RTDServer implementation is GetValue(). The others are more for convenience.""" diff --git a/com/win32com/demos/iebutton.py b/com/win32com/demos/iebutton.py index bc3ce99bf8..0feb0e4883 100644 --- a/com/win32com/demos/iebutton.py +++ b/com/win32com/demos/iebutton.py @@ -3,7 +3,7 @@ # PyWin32 Internet Explorer Button # # written by Leonard Ritter (paniq@gmx.net) -# and Robert Förtsch (info@robert-foertsch.com) +# and Robert Förtsch (info@robert-foertsch.com) """ diff --git a/com/win32com/demos/ietoolbar.py b/com/win32com/demos/ietoolbar.py index 084db3c1ae..b259c406df 100644 --- a/com/win32com/demos/ietoolbar.py +++ b/com/win32com/demos/ietoolbar.py @@ -3,7 +3,7 @@ # PyWin32 Internet Explorer Toolbar # # written by Leonard Ritter (paniq@gmx.net) -# and Robert Förtsch (info@robert-foertsch.com) +# and Robert Förtsch (info@robert-foertsch.com) """ diff --git a/com/win32com/server/dispatcher.py b/com/win32com/server/dispatcher.py index ac98312500..71b91e7a59 100644 --- a/com/win32com/server/dispatcher.py +++ b/com/win32com/server/dispatcher.py @@ -8,8 +8,6 @@ import pythoncom import win32api import win32com - -# from win32com.server.exception import IsCOMServerException from win32com.util import IIDToInterfaceName @@ -243,9 +241,6 @@ class DispatcherWin32dbg(DispatcherBase): """ def __init__(self, policyClass, ob): - # No one uses this, and it just causes py2exe to drag all of - # pythonwin in. - # import pywin.debugger pywin.debugger.brk() print("The DispatcherWin32dbg dispatcher is deprecated!") print("Please let me know if this is a problem.") diff --git a/com/win32com/server/register.py b/com/win32com/server/register.py index ae513c754f..6c8922e5ac 100644 --- a/com/win32com/server/register.py +++ b/com/win32com/server/register.py @@ -94,7 +94,7 @@ def _cat_registrar(): def _find_localserver_exe(mustfind): - if not sys.platform.startswith("win32"): + if sys.platform != "win32": return sys.executable if pythoncom.__file__.find("_d") < 0: exeBaseName = "pythonw.exe" diff --git a/com/win32com/test/testPersist.py b/com/win32com/test/testPersist.py index a75ec64360..76f7d84c96 100644 --- a/com/win32com/test/testPersist.py +++ b/com/win32com/test/testPersist.py @@ -7,6 +7,7 @@ import win32com.client import win32com.client.dynamic import win32com.server.util +import win32timezone import win32ui from win32com import storagecon from win32com.axcontrol import axcontrol @@ -14,9 +15,6 @@ S_OK = 0 - -import win32timezone - now = win32timezone.now() diff --git a/com/win32com/test/testPippo.py b/com/win32com/test/testPippo.py index a1a762c2c8..414483b53e 100644 --- a/com/win32com/test/testPippo.py +++ b/com/win32com/test/testPippo.py @@ -52,9 +52,8 @@ def testNumpyArrays(self): def testByteArrays(self): if "bytes" in dir(__builtins__): - # Use eval to avoid compilation error in Python 2. - self._testArray(eval("b'abcdef'")) - self._testArray(eval("bytearray(b'abcdef')")) + self._testArray(b"abcdef") + self._testArray(bytearray(b"abcdef")) def _testArray(self, inArray): outArray = self.object.Method3(inArray) diff --git a/com/win32com/test/testPyComTest.py b/com/win32com/test/testPyComTest.py index 59b601bc67..c48490aefe 100644 --- a/com/win32com/test/testPyComTest.py +++ b/com/win32com/test/testPyComTest.py @@ -17,7 +17,7 @@ import win32timezone import winerror from win32com.client import VARIANT, CastTo, DispatchBaseClass, constants -from win32com.test.util import CheckClean, RegisterPythonServer +from win32com.test.util import RegisterPythonServer importMsg = "**** PyCOMTest is not installed ***\n PyCOMTest is a Python test specific COM client and server.\n It is likely this server is not installed on this machine\n To install the server, you must get the win32com sources\n and build it using MS Visual C++" @@ -126,38 +126,6 @@ def _DumpFireds(self): progress("ID %d fired %d times" % (firedId, no)) -# A simple handler class that derives from object (ie, a "new style class") - -# only relevant for Python 2.x (ie, the 2 classes should be identical in 3.x) -class NewStyleRandomEventHandler(object): - def _Init(self): - self.fireds = {} - - def OnFire(self, no): - try: - self.fireds[no] = self.fireds[no] + 1 - except KeyError: - self.fireds[no] = 0 - - def OnFireWithNamedParams(self, no, a_bool, out1, out2): - # This test exists mainly to help with an old bug, where named - # params would come in reverse. - Missing = pythoncom.Missing - if no is not Missing: - # We know our impl called 'OnFire' with the same ID - assert no in self.fireds - assert no + 1 == out1, "expecting 'out1' param to be ID+1" - assert no + 2 == out2, "expecting 'out2' param to be ID+2" - # The middle must be a boolean. - assert a_bool is Missing or isinstance(a_bool, bool), "middle param not a bool" - return out1 + 2, out2 + 2 - - def _DumpFireds(self): - if not self.fireds: - print("ERROR: Nothing was received!") - for firedId, no in self.fireds.items(): - progress("ID %d fired %d times" % (firedId, no)) - - # Test everything which can be tested using both the "dynamic" and "generated" # COM objects (or when there are very subtle differences) def TestCommon(o, is_generated): @@ -228,9 +196,9 @@ def TestCommon(o, is_generated): if o.GetSetUnsignedLong(-1) != 0xFFFFFFFF: raise error("unsigned -1 failed") - # We want to explicitly test > 32 bits. py3k has no 'maxint' and + # We want to explicitly test > 32 bits. # 'maxsize+1' is no good on 64bit platforms as its 65 bits! - big = 2147483647 # sys.maxint on py2k + big = 2147483647 for l in big, big + 1, 1 << 65: check_get_set(o.GetSetVariant, l) @@ -532,13 +500,9 @@ def TestGenerated(): progress("Testing connection points") o2 = win32com.client.DispatchWithEvents(o, RandomEventHandler) TestEvents(o2, o2) - o2 = win32com.client.DispatchWithEvents(o, NewStyleRandomEventHandler) - TestEvents(o2, o2) # and a plain "WithEvents". handler = win32com.client.WithEvents(o, RandomEventHandler) TestEvents(o, handler) - handler = win32com.client.WithEvents(o, NewStyleRandomEventHandler) - TestEvents(o, handler) progress("Finished generated .py test.") diff --git a/com/win32com/test/testStreams.py b/com/win32com/test/testStreams.py index da0329d5b4..b43da524f3 100644 --- a/com/win32com/test/testStreams.py +++ b/com/win32com/test/testStreams.py @@ -127,7 +127,7 @@ def testit(self): def testseek(self): s = Stream(b"yo") s = win32com.server.util.wrap(s, pythoncom.IID_IStream) - # we used to die in py3k passing a value > 32bits + # we used to die passing a value > 32bits s.Seek(0x100000000, pythoncom.STREAM_SEEK_SET) def testerrors(self): diff --git a/com/win32com/test/testvb.py b/com/win32com/test/testvb.py index 46d0f08f02..c82b4e73fb 100644 --- a/com/win32com/test/testvb.py +++ b/com/win32com/test/testvb.py @@ -3,7 +3,6 @@ # This requires the PythonCOM VB Test Harness. # -import sys import traceback import pythoncom @@ -11,7 +10,7 @@ import win32com.client.dynamic import win32com.client.gencache import winerror -from win32com.server.util import NewCollection, wrap +from win32com.server.util import wrap from win32com.test import util # for debugging @@ -423,17 +422,16 @@ def TestStructs(vbtest): # Now do some object equality tests. assert s == s assert s is not None - if sys.version_info > (3, 0): - try: - s < None - raise error("Expected type error") - except TypeError: - pass - try: - None < s - raise error("Expected type error") - except TypeError: - pass + try: + s < None + raise error("Expected type error") + except TypeError: + pass + try: + None < s + raise error("Expected type error") + except TypeError: + pass assert s != s.sub_val import copy @@ -527,17 +525,16 @@ def TestObjectSemantics(ob): assert None != ob._oleobj_ assert ob is not None assert None != ob - if sys.version_info > (3, 0): - try: - ob < None - raise error("Expected type error") - except TypeError: - pass - try: - None < ob - raise error("Expected type error") - except TypeError: - pass + try: + ob < None + raise error("Expected type error") + except TypeError: + pass + try: + None < ob + raise error("Expected type error") + except TypeError: + pass assert ob._oleobj_.QueryInterface(pythoncom.IID_IUnknown) == ob._oleobj_ assert not ob._oleobj_.QueryInterface(pythoncom.IID_IUnknown) != ob._oleobj_ diff --git a/com/win32com/test/util.py b/com/win32com/test/util.py index 691be85190..d36a0da917 100644 --- a/com/win32com/test/util.py +++ b/com/win32com/test/util.py @@ -19,10 +19,6 @@ def CheckClean(): # Ensure no lingering exceptions - Python should have zero outstanding # COM objects - try: - sys.exc_clear() - except AttributeError: - pass # py3k c = _GetInterfaceCount() if c: print("Warning - %d com interface objects still alive" % c) diff --git a/com/win32comext/axdebug/src/PyIDebugStackFrame.cpp b/com/win32comext/axdebug/src/PyIDebugStackFrame.cpp index f715d2d05e..c119e29a0a 100644 --- a/com/win32comext/axdebug/src/PyIDebugStackFrame.cpp +++ b/com/win32comext/axdebug/src/PyIDebugStackFrame.cpp @@ -71,7 +71,7 @@ PyObject *PyIDebugStackFrame::GetLanguageString(PyObject *self, PyObject *args) BSTR pbstrDescription; BOOL flong; // @pyparm int|fLong||If False, just the language name should be provided, eg, "Python". If True a full product - // description may be provided (eg, "Python 1.4 ActiveX Debugging Host") + // description may be provided (eg, "Python X.X ActiveX Debugging Host") if (!PyArg_ParseTuple(args, "i:GetLanguageString", &flong)) return NULL; PY_INTERFACE_PRECALL; diff --git a/com/win32comext/axscript/client/framework.py b/com/win32comext/axscript/client/framework.py index 7203e4ef39..85021c4488 100644 --- a/com/win32comext/axscript/client/framework.py +++ b/com/win32comext/axscript/client/framework.py @@ -1057,7 +1057,6 @@ def ChangeScriptState(self, state): self.scriptSite.OnStateChange(state) except pythoncom.com_error as xxx_todo_changeme: (hr, desc, exc, arg) = xxx_todo_changeme.args - # Ignore all errors here - E_NOTIMPL likely from scriptlets. finally: self.EnableInterrupts() diff --git a/com/win32comext/axscript/test/leakTest.py b/com/win32comext/axscript/test/leakTest.py index d8ccac57b6..36bd8cf2b9 100644 --- a/com/win32comext/axscript/test/leakTest.py +++ b/com/win32comext/axscript/test/leakTest.py @@ -80,7 +80,7 @@ def NotifyDoneIt(self, interface, arg): sub hello(arg1) test.echo arg1 end sub - + sub testcollection test.verbose = 1 for each item in test.collection @@ -88,16 +88,15 @@ def NotifyDoneIt(self, interface, arg): next end sub """ -if sys.version_info < (3,): - PyScript = """print "PyScript is being parsed..."\n""" -else: - PyScript = """print("PyScript is being parsed...")\n""" -PyScript += """\ + +PyScript = """\ +print("PyScript is being parsed...")\n + prop = "Property Value" def hello(arg1): test.echo(arg1) pass - + def testcollection(): test.verbose = 1 # test.collection[1] = "New one" diff --git a/com/win32comext/axscript/test/testHost.py b/com/win32comext/axscript/test/testHost.py index 8ef8bcc09a..466bdb3ac5 100644 --- a/com/win32comext/axscript/test/testHost.py +++ b/com/win32comext/axscript/test/testHost.py @@ -135,14 +135,6 @@ def testcollection(): pass """ -# XXX - needs py3k work! Throwing a bytes string with an extended char -# doesn't make much sense, but py2x allows it. What it gets upset with -# is a real unicode arg - which is the only thing py3k allows! -PyScript_Exc = """\ -def hello(arg1): - raise RuntimeError("exc with extended \xa9har") -""" - ErrScript = """\ bad code for everyone! """ @@ -248,10 +240,6 @@ def testPythonUnicodeError(self): def testVBExceptions(self): self.assertRaises(pythoncom.com_error, self._TestEngine, "VBScript", ErrScript) - def testPythonExceptions(self): - expected = "RuntimeError: exc with extended \xa9har" - self._TestEngine("Python", PyScript_Exc, expected) - if __name__ == "__main__": unittest.main() diff --git a/com/win32comext/mapi/mapiutil.py b/com/win32comext/mapi/mapiutil.py index b0f20dc882..03d2a63982 100644 --- a/com/win32comext/mapi/mapiutil.py +++ b/com/win32comext/mapi/mapiutil.py @@ -1,5 +1,4 @@ # General utilities for MAPI and MAPI objects. -# We used to use these old names from the 'types' module... import pythoncom from pywintypes import TimeType diff --git a/com/win32comext/shell/demos/ITransferAdviseSink.py b/com/win32comext/shell/demos/ITransferAdviseSink.py index fd00ca15f5..fc766fb0b2 100644 --- a/com/win32comext/shell/demos/ITransferAdviseSink.py +++ b/com/win32comext/shell/demos/ITransferAdviseSink.py @@ -8,7 +8,6 @@ (k, v) for k, v in list(shellcon.__dict__.items()) if k.startswith("TSF_") ) - TRANSFER_ADVISE_STATES = {} for k, v in list(shellcon.__dict__.items()): if k.startswith("TS_"): diff --git a/com/win32comext/taskscheduler/test/test_addtask_1.py b/com/win32comext/taskscheduler/test/test_addtask_1.py index 29c9e08d2e..284e3511e0 100644 --- a/com/win32comext/taskscheduler/test/test_addtask_1.py +++ b/com/win32comext/taskscheduler/test/test_addtask_1.py @@ -33,12 +33,11 @@ ) new_task.SetIdleWait(1, 10000) new_task.SetComment("test task with idle trigger") -new_task.SetApplicationName("c:\\python23\\python.exe") +new_task.SetApplicationName("py.exe") new_task.SetPriority(taskscheduler.REALTIME_PRIORITY_CLASS) new_task.SetParameters( "-c\"import win32ui,time;win32ui.MessageBox('why aint you doing no work ?');\"" ) -new_task.SetWorkingDirectory("c:\\python23") new_task.SetCreator("test_addtask_1.py") new_task.SetAccountInformation(win32api.GetUserName(), None) ## None is only valid for local system acct or if Flags contain TASK_FLAG_RUN_ONLY_IF_LOGGED_ON diff --git a/com/win32comext/taskscheduler/test/test_addtask_2.py b/com/win32comext/taskscheduler/test/test_addtask_2.py index 4663bea46f..5c2f7c8dd3 100644 --- a/com/win32comext/taskscheduler/test/test_addtask_2.py +++ b/com/win32comext/taskscheduler/test/test_addtask_2.py @@ -20,10 +20,10 @@ t = ts.NewWorkItem(task_name) t.SetComment("Test a task running as local system acct") -t.SetApplicationName("c:\\python23\\python.exe") +t.SetApplicationName("c:\\Python37\\python.exe") t.SetPriority(taskscheduler.REALTIME_PRIORITY_CLASS) t.SetParameters("test_localsystem.py") -t.SetWorkingDirectory("c:\\python23") +t.SetWorkingDirectory("c:\\Python37") t.SetCreator("test_addtask_2.py") t.SetMaxRunTime(20000) # milliseconds t.SetFlags(taskscheduler.TASK_FLAG_DELETE_WHEN_DONE) diff --git a/pywin32_postinstall.py b/pywin32_postinstall.py index 147f0cde7b..5b6a6da749 100644 --- a/pywin32_postinstall.py +++ b/pywin32_postinstall.py @@ -69,7 +69,7 @@ def flush(self): try: # When this script is run from inside the bdist_wininst installer, # file_created() and directory_created() are additional builtin - # functions which write lines to Python23\pywin32-install.log. This is + # functions which write lines to PythonXX\pywin32-install.log. This is # a list of actions for the uninstaller, the format is inspired by what # the Wise installer also creates. file_created diff --git a/setup.py b/setup.py index 82fd384a6f..ecaa7a692b 100644 --- a/setup.py +++ b/setup.py @@ -2410,23 +2410,22 @@ def maybe_fixup_exes(): if "install" in dist.command_obj: # just to be purdy what_string += "/installed" # Print the list of extension modules we skipped building. - if "build_ext" in dist.command_obj: - excluded_extensions = dist.command_obj["build_ext"].excluded_extensions - if excluded_extensions: - skip_whitelist = {"exchdapi", "exchange", "axdebug", "winxpgui"} - skipped_ex = [] - print("*** NOTE: The following extensions were NOT %s:" % what_string) - for ext, why in excluded_extensions: - print(" %s: %s" % (ext.name, why)) - if ext.name not in skip_whitelist: - skipped_ex.append(ext.name) - print("For more details on installing the correct libraries and headers,") - print("please execute this script with no arguments (or see the docstring)") - if skipped_ex: - print( - "*** Non-zero exit status. Missing for complete release build: %s" - % skipped_ex - ) - sys.exit(1000 + len(skipped_ex)) - else: - print("All extension modules %s OK" % (what_string,)) + excluded_extensions = dist.command_obj["build_ext"].excluded_extensions + if excluded_extensions: + skip_whitelist = {"exchdapi", "exchange", "axdebug", "winxpgui"} + skipped_ex = [] + print("*** NOTE: The following extensions were NOT %s:" % what_string) + for ext, why in excluded_extensions: + print(" %s: %s" % (ext.name, why)) + if ext.name not in skip_whitelist: + skipped_ex.append(ext.name) + print("For more details on installing the correct libraries and headers,") + print("please execute this script with no arguments (or see the docstring)") + if skipped_ex: + print( + "*** Non-zero exit status. Missing for complete release build: %s" + % skipped_ex + ) + sys.exit(1000 + len(skipped_ex)) + else: + print("All extension modules %s OK" % (what_string,)) diff --git a/win32/Demos/BackupRead_BackupWrite.py b/win32/Demos/BackupRead_BackupWrite.py index 02aae91038..76ce996b11 100644 --- a/win32/Demos/BackupRead_BackupWrite.py +++ b/win32/Demos/BackupRead_BackupWrite.py @@ -1,6 +1,5 @@ ## demonstrates using BackupRead and BackupWrite to copy all of a file's data streams - import ntsecuritycon import pythoncom import pywintypes diff --git a/win32/Demos/OpenEncryptedFileRaw.py b/win32/Demos/OpenEncryptedFileRaw.py index aa0f2a7c15..c9e2d54d87 100644 --- a/win32/Demos/OpenEncryptedFileRaw.py +++ b/win32/Demos/OpenEncryptedFileRaw.py @@ -9,7 +9,6 @@ def ReadCallback(input_buffer, data, buflen): fnamein, fnameout, f = data ## print fnamein, fnameout, buflen f.write(input_buffer) - ## python 2.3 throws an error if return value is a plain int return winerror.ERROR_SUCCESS diff --git a/win32/Demos/win32clipboardDemo.py b/win32/Demos/win32clipboardDemo.py index c65f546643..5794be6ff2 100644 --- a/win32/Demos/win32clipboardDemo.py +++ b/win32/Demos/win32clipboardDemo.py @@ -1,7 +1,6 @@ # win32clipboardDemo.py # # Demo/test of the win32clipboard module. - import win32con from win32clipboard import * @@ -115,8 +114,8 @@ class Foo: def __init__(self, **kw): self.__dict__.update(kw) - def __cmp__(self, other): - return cmp(self.__dict__, other.__dict__) + def __lt__(self, other): + return self.__dict__ < other.__dict__ def __eq__(self, other): return self.__dict__ == other.__dict__ diff --git a/win32/Demos/win32gui_dialog.py b/win32/Demos/win32gui_dialog.py index e3b89ba9d3..c4086563b5 100644 --- a/win32/Demos/win32gui_dialog.py +++ b/win32/Demos/win32gui_dialog.py @@ -146,7 +146,7 @@ def _RegisterWndClass(self): wc.cbWndExtra = win32con.DLGWINDOWEXTRA + struct.calcsize("Pi") icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE - ## py.ico went away in python 2.5, load from executable instead + ## load icon from executable this_app = win32api.GetModuleHandle(None) try: wc.hIcon = win32gui.LoadIcon(this_app, 1) ## python.exe and pythonw.exe diff --git a/win32/Demos/win32gui_menu.py b/win32/Demos/win32gui_menu.py index c462b06227..38c4827eb4 100644 --- a/win32/Demos/win32gui_menu.py +++ b/win32/Demos/win32gui_menu.py @@ -60,11 +60,6 @@ def __init__(self): ) UpdateWindow(self.hwnd) iconPathName = os.path.abspath(os.path.join(sys.prefix, "pyc.ico")) - # py2.5 includes the .ico files in the DLLs dir for some reason. - if not os.path.isfile(iconPathName): - iconPathName = os.path.abspath( - os.path.join(os.path.split(sys.executable)[0], "DLLs", "pyc.ico") - ) if not os.path.isfile(iconPathName): # Look in the source tree. iconPathName = os.path.abspath( diff --git a/win32/Demos/win32gui_taskbar.py b/win32/Demos/win32gui_taskbar.py index 84d642a9cd..eca439baa1 100644 --- a/win32/Demos/win32gui_taskbar.py +++ b/win32/Demos/win32gui_taskbar.py @@ -58,11 +58,6 @@ def _DoCreateIcons(self): iconPathName = os.path.abspath( os.path.join(os.path.split(sys.executable)[0], "pyc.ico") ) - if not os.path.isfile(iconPathName): - # Look in DLLs dir, a-la py 2.5 - iconPathName = os.path.abspath( - os.path.join(os.path.split(sys.executable)[0], "DLLs", "pyc.ico") - ) if not os.path.isfile(iconPathName): # Look in the source tree. iconPathName = os.path.abspath( diff --git a/win32/Lib/dbi.py b/win32/Lib/dbi.py deleted file mode 100644 index c33d6721ea..0000000000 --- a/win32/Lib/dbi.py +++ /dev/null @@ -1,27 +0,0 @@ -""" -Skeleton replacement for removed dbi module. -Use of objects created by this module should be replaced with native Python objects. -Dates are now returned as datetime.datetime objects, but will still accept PyTime -objects also. -Raw data for binary fields should be passed as buffer objects for Python 2.x, -and memoryview objects in Py3k. -""" - -import warnings - -warnings.warn( - "dbi module is obsolete, code should now use native python datetime and buffer/memoryview objects", - DeprecationWarning, -) - -import datetime - -dbDate = dbiDate = datetime.datetime - -try: - dbRaw = dbiRaw = buffer -except NameError: - dbRaw = dbiRaw = memoryview - -# type names are still exported by odbc module -from odbc import * diff --git a/win32/Lib/pywintypes.py b/win32/Lib/pywintypes.py index 115c4f82f7..631e7db884 100644 --- a/win32/Lib/pywintypes.py +++ b/win32/Lib/pywintypes.py @@ -31,7 +31,7 @@ def __import_pywin32_system_module__(modname, globs): suffix, ) if hasattr(sys, "frozen"): - # If we are running from a frozen program (py2exe, McMillan, freeze) + # If we are running from a frozen program (py2exe, McMillan, freeze, PyInstaller) # then we try and load the DLL from our sys.path # XXX - This path may also benefit from _win32sysloader? However, # MarkH has never seen the DLL load problem with py2exe programs... diff --git a/win32/Lib/sspi.py b/win32/Lib/sspi.py index 855a4c35b8..b10f63dbc7 100644 --- a/win32/Lib/sspi.py +++ b/win32/Lib/sspi.py @@ -19,7 +19,7 @@ error = win32security.error -class _BaseAuth(object): +class _BaseAuth: def __init__(self): self.reset() @@ -384,7 +384,7 @@ def authorize(self, sec_buffer_in): print("Initiator name from the service side:", sspiserver.initiator_name) print("Service name from the client side: ", sspiclient.service_name) - data = b"hello" # py3k-friendly + data = b"hello" # Simple signature, not compatible with GSSAPI. sig = sspiclient.sign(data) diff --git a/win32/Lib/win32timezone.py b/win32/Lib/win32timezone.py index fb0b36b54b..b65dabdfef 100644 --- a/win32/Lib/win32timezone.py +++ b/win32/Lib/win32timezone.py @@ -248,7 +248,7 @@ # A couple of objects for working with objects as if they were native C-type # structures. -class _SimpleStruct(object): +class _SimpleStruct: _fields_ = None # must be overridden by subclasses def __init__(self, *args, **kw): @@ -678,8 +678,8 @@ def GetDSTEndTime(self, year): "Given a year, determines the time when daylight savings ends." return self.getWinInfo(year).locate_standard_start(year) - def __cmp__(self, other): - return cmp(self.__dict__, other.__dict__) + def __le__(self, other): + return self.__dict__ < other.__dict__ def __eq__(self, other): return self.__dict__ == other.__dict__ @@ -874,7 +874,7 @@ def GetTZCapabilities(): return locals() -class DLLHandleCache(object): +class DLLHandleCache: def __init__(self): self.__cache = {} @@ -914,7 +914,7 @@ class RangeMap(dict): the sorted list of keys. One may supply keyword parameters to be passed to the sort function used - to sort keys (i.e. cmp [python 2 only], keys, reverse) as sort_params. + to sort keys (i.e. keys, reverse) as sort_params. Let's create a map that maps 1-3 -> 'a', 4-6 -> 'b' >>> r = RangeMap({3: 'a', 6: 'b'}) # boy, that was easy diff --git a/win32/Lib/win32traceutil.py b/win32/Lib/win32traceutil.py index 0eb38423e1..87f4ee9876 100644 --- a/win32/Lib/win32traceutil.py +++ b/win32/Lib/win32traceutil.py @@ -11,7 +11,7 @@ # # then, switch to a DOS prompt, and type: # C:>python.exe -# Python 1.4 etc... +# Python X.X.X (#0, Apr 13 1999, ... # >>> import win32traceutil # Redirecting output to win32trace remote collector # >>> print "Hello" diff --git a/win32/Lib/winnt.py b/win32/Lib/winnt.py index e997527c97..a88627e0fd 100644 --- a/win32/Lib/winnt.py +++ b/win32/Lib/winnt.py @@ -161,34 +161,22 @@ def PRIMARYLANGID(lgid): - return (WORD)(lgid) & 1023 + return (lgid) & 1023 def SUBLANGID(lgid): - return (WORD)(lgid) >> 10 + return (lgid) >> 10 NLS_VALID_LOCALE_MASK = 1048575 def LANGIDFROMLCID(lcid): - return (WORD)(lcid) + return lcid def SORTIDFROMLCID(lcid): - return (WORD)((((DWORD)(lcid)) & NLS_VALID_LOCALE_MASK) >> 16) - - -def UNREFERENCED_PARAMETER(P): - return - - -def DBG_UNREFERENCED_PARAMETER(P): - return - - -def DBG_UNREFERENCED_LOCAL_VARIABLE(V): - return + return (((lcid)) & NLS_VALID_LOCALE_MASK) >> 16 MAXIMUM_WAIT_OBJECTS = 64 diff --git a/win32/help/win32net.html b/win32/help/win32net.html index 0ec994900e..6ad7ecd2fa 100644 --- a/win32/help/win32net.html +++ b/win32/help/win32net.html @@ -70,7 +70,7 @@

Introduction

win32net called win32netcon that houses all of the constants needed by the win32net modules.

-Because of unicode support in python2.0, some of the string handling +Because of unicode support in Python 2.0, some of the string handling done w/the examples are no longer necessary. Before one needed to convert PyUnicode to a regular python string, before you could use string functions with it. The examples will work w/both versions of diff --git a/win32/scripts/regsetup.py b/win32/scripts/regsetup.py index f04dbda766..cf8c5e980e 100644 --- a/win32/scripts/regsetup.py +++ b/win32/scripts/regsetup.py @@ -504,7 +504,7 @@ def RegisterShellInfo(searchPaths): "regsetup c:\\wierd\\spot\\1 c:\\wierd\\spot\\2" Attempts to setup the core Python. Looks in some standard places, as well as the 2 wierd spots to locate the core Python files (eg, Python.exe, -python14.dll, the standard library and Win32 Extensions. +pythonXX.dll, the standard library and Win32 Extensions. "regsetup -a myappname . .\subdir" Registers a new Pythonpath entry named myappname, with "C:\\I\\AM\\HERE" and diff --git a/win32/scripts/setup_d.py b/win32/scripts/setup_d.py index babd835967..8d009dfa59 100644 --- a/win32/scripts/setup_d.py +++ b/win32/scripts/setup_d.py @@ -1,4 +1,4 @@ -# Install and register pythonxx_d.dll, pywintypesxx_d.dll and pythoncomxx_d.dll +# Install and register pythonXX_d.dll, pywintypesxx_d.dll and pythoncomxx_d.dll # # Assumes the _d files can be found in the same directory as this script # or in the cwd. @@ -14,7 +14,7 @@ def usage_and_die(rc): print() print("This script is designed to copy and register the Python debug") - print("binaries. It looks for pythonxx_d.dll, pythoncomxx_d.dll etc,") + print("binaries. It looks for pythonXX_d.dll, pythoncomxx_d.dll etc,") print("and installs them to work correctly with Python debug builds.") print() print("You will generally find this script in the. zip file that") diff --git a/win32/src/PyHANDLE.cpp b/win32/src/PyHANDLE.cpp index dd2290aa45..4fdad48f06 100644 --- a/win32/src/PyHANDLE.cpp +++ b/win32/src/PyHANDLE.cpp @@ -120,7 +120,7 @@ static PyNumberMethods PyHANDLE_NumberMethods = { PyHANDLE::unaryFailureFunc, /* nb_negative */ PyHANDLE::unaryFailureFunc, /* nb_positive */ PyHANDLE::unaryFailureFunc, /* nb_absolute */ - // @pymeth __nonzero__|Used for detecting true/false. + // @pymeth __bool__|Used for detecting true/false. PyHANDLE::nonzeroFunc, /* is nb_bool in Python 3.0 */ PyHANDLE::unaryFailureFunc, /* nb_invert */ PyHANDLE::binaryFailureFunc, /* nb_lshift */ @@ -234,7 +234,7 @@ BOOL PyHANDLE::Close(void) return rc; } -// @pymethod |PyHANDLE|__nonzero__|Used for detecting true/false. +// @pymethod |PyHANDLE|__bool__|Used for detecting true/false. // @rdesc The result is 1 if the attached handle is non zero, else 0. /*static*/ int PyHANDLE::nonzeroFunc(PyObject *ob) { return ((PyHANDLE *)ob)->m_handle != 0; } diff --git a/win32/test/test_clipboard.py b/win32/test/test_clipboard.py index 820dd18160..8f74e8575e 100644 --- a/win32/test/test_clipboard.py +++ b/win32/test/test_clipboard.py @@ -14,7 +14,7 @@ class CrashingTestCase(unittest.TestCase): def test_722082(self): - class crasher(object): + class crasher: pass obj = crasher() diff --git a/win32/test/test_exceptions.py b/win32/test/test_exceptions.py index 331011073b..2944da364c 100644 --- a/win32/test/test_exceptions.py +++ b/win32/test/test_exceptions.py @@ -1,5 +1,4 @@ """Test pywin32's error semantics""" -import sys import unittest import pythoncom @@ -11,10 +10,7 @@ class TestBase(unittest.TestCase): def _testExceptionIndex(self, exc, index, expected): - # check the exception itself can be indexed if not py3k - if sys.version_info < (3,): - self.assertEqual(exc[index], expected) - # and that exception.args can is the same. + # Check that exception.args is the same. self.assertEqual(exc.args[index], expected) @@ -66,10 +62,7 @@ def testAsTuple(self): err_msg = win32api.FormatMessage(winerror.ERROR_INVALID_HANDLE).rstrip() # early on the result actually *was* a tuple - it must be able to be one err_tuple = (winerror.ERROR_INVALID_HANDLE, "CloseHandle", err_msg) - if sys.version_info < (3,): - self.assertEqual(tuple(exc), err_tuple) - else: - self.assertEqual(exc.args, err_tuple) + self.assertEqual(exc.args, err_tuple) def testClassName(self): exc = self._getInvalidHandleException() @@ -159,10 +152,7 @@ def testAsTuple(self): err_msg = win32api.FormatMessage(winerror.STG_E_INVALIDFLAG).rstrip() # early on the result actually *was* a tuple - it must be able to be one err_tuple = (winerror.STG_E_INVALIDFLAG, err_msg, None, None) - if sys.version_info < (3,): - self.assertEqual(tuple(exc), err_tuple) - else: - self.assertEqual(exc.args, err_tuple) + self.assertEqual(exc.args, err_tuple) def testClassName(self): exc = self._getException() diff --git a/win32/test/test_pywintypes.py b/win32/test/test_pywintypes.py index 35962be32c..0a932fcd33 100644 --- a/win32/test/test_pywintypes.py +++ b/win32/test/test_pywintypes.py @@ -1,6 +1,5 @@ import datetime import operator -import sys import time import unittest @@ -96,11 +95,10 @@ def testGUIDRichCmp(self): self.assertFalse(None == s) self.assertTrue(s is not None) self.assertTrue(None != s) - if sys.version_info > (3, 0): - self.assertRaises(TypeError, operator.gt, None, s) - self.assertRaises(TypeError, operator.gt, s, None) - self.assertRaises(TypeError, operator.lt, None, s) - self.assertRaises(TypeError, operator.lt, s, None) + self.assertRaises(TypeError, operator.gt, None, s) + self.assertRaises(TypeError, operator.gt, s, None) + self.assertRaises(TypeError, operator.lt, None, s) + self.assertRaises(TypeError, operator.lt, s, None) def testGUIDInDict(self): s = "{00020400-0000-0000-C000-000000000046}" diff --git a/win32/test/test_sspi.py b/win32/test/test_sspi.py index 63003b0bca..a9db878e93 100644 --- a/win32/test/test_sspi.py +++ b/win32/test/test_sspi.py @@ -206,7 +206,6 @@ def testSecBufferRepr(self): r"PySecBuffer\(cbBuffer: 0 \| BufferType: 2 \| pvBuffer: 0x[\da-fA-F]{8,16}\)", repr(buffer1), ) - "PySecBuffer(cbBuffer: 0 | BufferType: 2 | pvBuffer: 0x000001B8CC6D8020)" desc.append(buffer1) assert re.match( diff --git a/win32/test/test_win32timezone.py b/win32/test/test_win32timezone.py index 6dba51edc9..4f77d437bb 100644 --- a/win32/test/test_win32timezone.py +++ b/win32/test/test_win32timezone.py @@ -1,7 +1,6 @@ # Test module for win32timezone import doctest -import sys import unittest import win32timezone @@ -9,16 +8,6 @@ class Win32TimeZoneTest(unittest.TestCase): def testWin32TZ(self): - # On 3.7 and later, the repr() for datetime objects changed to use kwargs - eg, - # eg, `datetime.timedelta(0, 10800)` is now `datetime.timedelta(seconds=10800)`. - # So we just skip the tests on 3.5 and 3.6 - if sys.version_info < (3, 7): - from pywin32_testutil import TestSkipped - - raise TestSkipped( - "The repr() for datetime objects makes this test fail in 3.5 and 3.6" - ) - failed, total = doctest.testmod(win32timezone, verbose=False) self.assertFalse(failed) From 59136fdf31c962804fe2d9cba24d598540be95e3 Mon Sep 17 00:00:00 2001 From: Avasam Date: Thu, 17 Aug 2023 11:38:00 -0400 Subject: [PATCH 02/22] Missed SetApplicationName in tests (#2099) --- com/win32comext/taskscheduler/test/test_addtask_2.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/com/win32comext/taskscheduler/test/test_addtask_2.py b/com/win32comext/taskscheduler/test/test_addtask_2.py index 5c2f7c8dd3..b803db4373 100644 --- a/com/win32comext/taskscheduler/test/test_addtask_2.py +++ b/com/win32comext/taskscheduler/test/test_addtask_2.py @@ -20,10 +20,9 @@ t = ts.NewWorkItem(task_name) t.SetComment("Test a task running as local system acct") -t.SetApplicationName("c:\\Python37\\python.exe") +t.SetApplicationName("py.exe") t.SetPriority(taskscheduler.REALTIME_PRIORITY_CLASS) t.SetParameters("test_localsystem.py") -t.SetWorkingDirectory("c:\\Python37") t.SetCreator("test_addtask_2.py") t.SetMaxRunTime(20000) # milliseconds t.SetFlags(taskscheduler.TASK_FLAG_DELETE_WHEN_DONE) From 2a7137f21965013020ef9e4f27565db6dea59003 Mon Sep 17 00:00:00 2001 From: Avasam Date: Thu, 17 Aug 2023 15:42:26 -0400 Subject: [PATCH 03/22] Add GitHub Action concurency groups (#2103) --- .github/workflows/main.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 21a9962c6d..260d16047b 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -6,6 +6,10 @@ on: branches: - main +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + jobs: test: name: Build and test From c72d2548cebddf039099db0017cfab8dc227fa10 Mon Sep 17 00:00:00 2001 From: Avasam Date: Thu, 21 Sep 2023 10:51:45 -0400 Subject: [PATCH 04/22] zero arguments super (#2106) --- com/win32com/demos/excelRTDServer.py | 8 ++++---- com/win32com/makegw/makegwparse.py | 4 ++-- win32/Lib/pywin32_testutil.py | 6 +++--- win32/Lib/win32timezone.py | 6 +++--- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/com/win32com/demos/excelRTDServer.py b/com/win32com/demos/excelRTDServer.py index 6eda469530..6f512dbf90 100644 --- a/com/win32com/demos/excelRTDServer.py +++ b/com/win32com/demos/excelRTDServer.py @@ -132,7 +132,7 @@ class ExcelRTDServer: def __init__(self): """Constructor""" - super(ExcelRTDServer, self).__init__() + super().__init__() self.IsAlive = self.ALIVE self.__callback = None self.topics = {} @@ -266,7 +266,7 @@ class RTDTopic: The others are more for convenience.""" def __init__(self, TopicStrings): - super(RTDTopic, self).__init__() + super().__init__() self.TopicStrings = TopicStrings self.__currentValue = None self.__dirty = False @@ -332,7 +332,7 @@ class TimeServer(ExcelRTDServer): INTERVAL = 0.5 # secs. Threaded timer will wake us up at this interval. def __init__(self): - super(TimeServer, self).__init__() + super().__init__() # Simply timer thread to ensure we get to update our topics, and # tell excel about any changes. This is a pretty basic and dirty way to @@ -384,7 +384,7 @@ class TimeTopic(RTDTopic): """ def __init__(self, TopicStrings): - super(TimeTopic, self).__init__(TopicStrings) + super().__init__(TopicStrings) try: self.cmd, self.delay = self.TopicStrings except Exception as E: diff --git a/com/win32com/makegw/makegwparse.py b/com/win32com/makegw/makegwparse.py index ffe69cb4c7..178ab7adc8 100644 --- a/com/win32com/makegw/makegwparse.py +++ b/com/win32com/makegw/makegwparse.py @@ -17,12 +17,12 @@ class error_not_found(Exception): def __init__(self, msg="The requested item could not be found"): - super(error_not_found, self).__init__(msg) + super().__init__(msg) class error_not_supported(Exception): def __init__(self, msg="The required functionality is not supported"): - super(error_not_supported, self).__init__(msg) + super().__init__(msg) VERBOSE = 0 diff --git a/win32/Lib/pywin32_testutil.py b/win32/Lib/pywin32_testutil.py index 63cd87ea21..41a971967c 100644 --- a/win32/Lib/pywin32_testutil.py +++ b/win32/Lib/pywin32_testutil.py @@ -217,7 +217,7 @@ class TestSkipped(Exception): # handling for the TestSkipped exception. class TestResult(TextTestResult): def __init__(self, *args, **kw): - super(TestResult, self).__init__(*args, **kw) + super().__init__(*args, **kw) self.skips = {} # count of skips for each reason. def addError(self, test, err): @@ -265,10 +265,10 @@ def addError(self, test, err): self.stream.write("S") self.stream.flush() return - super(TestResult, self).addError(test, err) + super().addError(test, err) def printErrors(self): - super(TestResult, self).printErrors() + super().printErrors() for reason, num_skipped in self.skips.items(): self.stream.writeln("SKIPPED: %d tests - %s" % (num_skipped, reason)) diff --git a/win32/Lib/win32timezone.py b/win32/Lib/win32timezone.py index b65dabdfef..5a5445a0fd 100644 --- a/win32/Lib/win32timezone.py +++ b/win32/Lib/win32timezone.py @@ -337,7 +337,7 @@ def __init__(self, *args, **kwargs): c) a byte structure (using _from_bytes) """ try: - super(TimeZoneDefinition, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) return except (TypeError, ValueError): pass @@ -369,7 +369,7 @@ def __init_from_bytes( bias, standard_bias, daylight_bias = components[:3] standard_start = SYSTEMTIME(*components[3:11]) daylight_start = SYSTEMTIME(*components[11:19]) - super(TimeZoneDefinition, self).__init__( + super().__init__( bias, standard_name, standard_start, @@ -393,7 +393,7 @@ def __init_from_other(self, other): # ctypes.memmove(ctypes.addressof(self), other, size) def __getattribute__(self, attr): - value = super(TimeZoneDefinition, self).__getattribute__(attr) + value = super().__getattribute__(attr) if "bias" in attr: value = datetime.timedelta(minutes=value) return value From 6df85336c6ca9e0b12f168efd6950d75e586f3dc Mon Sep 17 00:00:00 2001 From: Avasam Date: Thu, 21 Sep 2023 10:55:24 -0400 Subject: [PATCH 05/22] Update and standardise obsolete `OSError` aliases: (#2107) - IOError - WindowsError - mmap.error - select.error - socket.error - os.error --- AutoDuck/fixHelpCompression.py | 2 +- Pythonwin/Scintilla/src/LexGen.py | 4 ++-- Pythonwin/pywin/Demos/hiertest.py | 2 +- Pythonwin/pywin/framework/app.py | 2 +- Pythonwin/pywin/framework/bitmap.py | 2 +- Pythonwin/pywin/framework/editor/document.py | 14 ++++++------- Pythonwin/pywin/framework/editor/editor.py | 2 +- Pythonwin/pywin/framework/scriptutils.py | 8 ++++---- Pythonwin/pywin/framework/winout.py | 2 +- Pythonwin/pywin/scintilla/config.py | 6 +++--- Pythonwin/pywin/scintilla/document.py | 4 ++-- com/win32com/client/gencache.py | 20 +++++++++---------- com/win32com/client/genpy.py | 6 +++--- com/win32com/client/makepy.py | 6 +++--- com/win32com/demos/excelAddin.py | 2 +- com/win32com/demos/iebutton.py | 4 ++-- com/win32com/demos/ietoolbar.py | 4 ++-- com/win32com/demos/outlookAddin.py | 2 +- com/win32com/server/register.py | 6 +++--- com/win32com/test/GenTestScripts.py | 8 ++++---- com/win32com/test/testAccess.py | 2 +- com/win32com/test/testShell.py | 2 +- com/win32com/test/testxslt.py | 2 +- com/win32com/test/util.py | 2 +- com/win32comext/axdebug/Test/host.py | 2 +- com/win32comext/axdebug/codecontainer.py | 2 +- com/win32comext/ifilter/demo/filterDemo.py | 2 +- .../shell/demos/servers/column_provider.py | 2 +- .../shell/demos/servers/context_menu.py | 2 +- .../shell/demos/servers/copy_hook.py | 4 ++-- .../shell/demos/servers/empty_volume_cache.py | 2 +- .../shell/demos/servers/folder_view.py | 2 +- .../shell/demos/servers/icon_handler.py | 2 +- .../shell/demos/servers/shell_view.py | 2 +- isapi/__init__.py | 2 +- isapi/install.py | 2 +- pywin32_postinstall.py | 16 +++++++-------- setup.py | 4 ++-- win32/Demos/winprocess.py | 4 ++-- win32/Lib/regcheck.py | 5 ++--- win32/Lib/regutil.py | 6 +++--- win32/Lib/win32rcparser.py | 4 ++-- win32/Lib/win32serviceutil.py | 2 +- win32/Lib/win32timezone.py | 4 ++-- win32/Lib/win32verstamp.py | 2 +- win32/scripts/VersionStamp/BrandProject.py | 2 +- win32/scripts/backupEventLog.py | 2 +- win32/scripts/regsetup.py | 4 ++-- win32/test/handles.py | 8 ++++---- win32/test/test_win32file.py | 10 +++++----- 50 files changed, 106 insertions(+), 107 deletions(-) diff --git a/AutoDuck/fixHelpCompression.py b/AutoDuck/fixHelpCompression.py index 02cd78454d..de4008e722 100644 --- a/AutoDuck/fixHelpCompression.py +++ b/AutoDuck/fixHelpCompression.py @@ -9,7 +9,7 @@ try: os.stat(fname) -except os.error: +except OSError: sys.stderr.write("The project file '%s' was not found\n" % (fname)) sys.exit(1) diff --git a/Pythonwin/Scintilla/src/LexGen.py b/Pythonwin/Scintilla/src/LexGen.py index c030921ce9..7c1d9eb0b7 100644 --- a/Pythonwin/Scintilla/src/LexGen.py +++ b/Pythonwin/Scintilla/src/LexGen.py @@ -107,7 +107,7 @@ def UpdateFile(filename, updated): it as modified.""" try: infile = open(filename, "rb") - except IOError: # File is not there yet + except OSError: # File is not there yet out = open(filename, "wb") out.write(updated) out.close() @@ -136,7 +136,7 @@ def Generate(inpath, outpath, commentPrefix, eolType, *lists): # % (inpath, outpath, commentPrefix, eolType) try: infile = open(inpath, "r") - except IOError: + except OSError: print("Can not open", inpath) return original = infile.read() diff --git a/Pythonwin/pywin/Demos/hiertest.py b/Pythonwin/pywin/Demos/hiertest.py index 287b71dafa..3762946112 100644 --- a/Pythonwin/pywin/Demos/hiertest.py +++ b/Pythonwin/pywin/Demos/hiertest.py @@ -105,7 +105,7 @@ def GetText(self): os.path.basename(self.filename), os.stat(self.filename)[6], ) - except os.error as details: + except OSError as details: return "%-20s - %s" % (self.filename, details[1]) def IsExpandable(self): diff --git a/Pythonwin/pywin/framework/app.py b/Pythonwin/pywin/framework/app.py index 298a79b4fb..409a10c3e9 100644 --- a/Pythonwin/pywin/framework/app.py +++ b/Pythonwin/pywin/framework/app.py @@ -379,7 +379,7 @@ def OnInitDialog(self): open(os.path.join(site_packages, "pywin32.version.txt")).read().strip() ) ver = "pywin32 build %s" % build_no - except EnvironmentError: + except OSError: ver = None if ver is None: # See if we are Part of Active Python diff --git a/Pythonwin/pywin/framework/bitmap.py b/Pythonwin/pywin/framework/bitmap.py index 1501f72d89..1ec4d50f48 100644 --- a/Pythonwin/pywin/framework/bitmap.py +++ b/Pythonwin/pywin/framework/bitmap.py @@ -28,7 +28,7 @@ def OnOpenDocument(self, filename): try: try: self.bitmap.LoadBitmapFile(f) - except IOError: + except OSError: win32ui.MessageBox("Could not load the bitmap from %s" % filename) return 0 finally: diff --git a/Pythonwin/pywin/framework/editor/document.py b/Pythonwin/pywin/framework/editor/document.py index e66947b81c..1e74e86a2b 100644 --- a/Pythonwin/pywin/framework/editor/document.py +++ b/Pythonwin/pywin/framework/editor/document.py @@ -66,23 +66,23 @@ def OnSaveDocument(self, fileName): tempPath = os.path.join(win32api.GetTempPath(), "bak") try: os.mkdir(tempPath, 0) - except os.error: + except OSError: pass bakFileName = os.path.join(tempPath, basename) try: os.unlink(bakFileName) # raise NameError if no bakups wanted. - except (os.error, NameError): + except (OSError, NameError): pass try: # Do a copy as it might be on different volumes, # and the file may be a hard-link, causing the link # to follow the backup. shutil.copy2(fileName, bakFileName) - except (os.error, NameError, IOError): + except (OSError, NameError): pass try: self.SaveFile(fileName) - except IOError as details: + except OSError as details: win32ui.MessageBox("Error - could not save file\r\n\r\n%s" % details) return 0 except (UnicodeEncodeError, LookupError) as details: @@ -99,7 +99,7 @@ def OnSaveDocument(self, fileName): if rc == win32con.IDYES: try: self.SaveFile(fileName, encoding="latin-1") - except IOError as details: + except OSError as details: win32ui.MessageBox( "Error - could not save file\r\n\r\n%s" % details ) @@ -155,7 +155,7 @@ def CheckExternalDocumentUpdated(self): return try: newstat = os.stat(self.GetPathName()) - except os.error as exc: + except OSError as exc: if not self.bReportedFileNotFound: print( "The file '%s' is open for editing, but\nchecking it for changes caused the error: %s" @@ -207,7 +207,7 @@ def _DocumentStateChanged(self): if self.GetPathName(): try: self.fileStat = os.stat(self.GetPathName()) - except os.error: + except OSError: self.fileStat = None else: self.fileStat = None diff --git a/Pythonwin/pywin/framework/editor/editor.py b/Pythonwin/pywin/framework/editor/editor.py index 2a61ea6c55..63df9cfcdb 100644 --- a/Pythonwin/pywin/framework/editor/editor.py +++ b/Pythonwin/pywin/framework/editor/editor.py @@ -101,7 +101,7 @@ def OnOpenDocument(self, filename): win32ui.SetStatusText("Loading file...", 1) try: f = open(filename, "rb") - except IOError: + except OSError: win32ui.MessageBox( filename + "\nCan not find this file\nPlease verify that the correct path and file name are given" diff --git a/Pythonwin/pywin/framework/scriptutils.py b/Pythonwin/pywin/framework/scriptutils.py index 5bb8544d34..c6e8e32440 100644 --- a/Pythonwin/pywin/framework/scriptutils.py +++ b/Pythonwin/pywin/framework/scriptutils.py @@ -288,7 +288,7 @@ def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None): try: os.stat(fnameonly) # See if it is OK as is... script = fnameonly - except os.error: + except OSError: fullScript = LocatePythonFile(script) if fullScript is None: win32ui.MessageBox("The file '%s' can not be located" % script) @@ -308,7 +308,7 @@ def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None): # So: do the binary thing and manually normalize \r\n. try: f = open(script, "rb") - except IOError as exc: + except OSError as exc: win32ui.MessageBox( "The file could not be opened - %s (%d)" % (exc.strerror, exc.errno) ) @@ -505,7 +505,7 @@ def CheckFile(): win32ui.DoWaitCursor(1) try: f = open(pathName) - except IOError as details: + except OSError as details: print("Cant open file '%s' - %s" % (pathName, details)) return try: @@ -640,7 +640,7 @@ def FindTabNanny(): fname = os.path.join(path, "Tools\\Scripts\\%s" % filename) try: os.stat(fname) - except os.error: + except OSError: print( "WARNING - The file '%s' can not be located in path '%s'" % (filename, path) ) diff --git a/Pythonwin/pywin/framework/winout.py b/Pythonwin/pywin/framework/winout.py index 645dbca816..7badd38415 100644 --- a/Pythonwin/pywin/framework/winout.py +++ b/Pythonwin/pywin/framework/winout.py @@ -60,7 +60,7 @@ def OnSaveDocument(self, fileName): win32ui.SetStatusText("Saving file...", 1) try: self.SaveFile(fileName) - except IOError as details: + except OSError as details: win32ui.MessageBox("Error - could not save file\r\n\r\n%s" % details) return 0 win32ui.SetStatusText("Ready") diff --git a/Pythonwin/pywin/scintilla/config.py b/Pythonwin/pywin/scintilla/config.py index 6f169eed37..1dc4b38034 100644 --- a/Pythonwin/pywin/scintilla/config.py +++ b/Pythonwin/pywin/scintilla/config.py @@ -91,7 +91,7 @@ def __init__(self, f): try: f = find_config_file(f) src_stat = os.stat(f) - except os.error: + except OSError: self.report_error("Config file '%s' not found" % f) return self.filename = f @@ -119,7 +119,7 @@ def __init__(self, f): return # We are ready to roll! finally: cf.close() - except (os.error, IOError, EOFError): + except (OSError, EOFError): pass fp = open(f) b_close = True @@ -167,7 +167,7 @@ def __init__(self, f): marshal.dump(src_stat[stat.ST_MTIME], cf) marshal.dump(self.cache, cf) cf.close() - except (IOError, EOFError): + except (OSError, EOFError): pass # Ignore errors - may be read only. def configure(self, editor, subsections=None): diff --git a/Pythonwin/pywin/scintilla/document.py b/Pythonwin/pywin/scintilla/document.py index 7fb5e264a5..f7f542d6c0 100644 --- a/Pythonwin/pywin/scintilla/document.py +++ b/Pythonwin/pywin/scintilla/document.py @@ -47,7 +47,7 @@ def OnOpenDocument(self, filename): self._LoadTextFromFile(f) finally: f.close() - except IOError: + except OSError: rc = win32ui.MessageBox( "Could not load the file from %s\n\nDo you want to create a new file?" % filename, @@ -63,7 +63,7 @@ def OnOpenDocument(self, filename): self._LoadTextFromFile(f) finally: f.close() - except IOError as e: + except OSError as e: rc = win32ui.MessageBox("Cannot create the file %s" % filename) return 1 diff --git a/com/win32com/client/gencache.py b/com/win32com/client/gencache.py index 99e9c6cbd1..1d9ca3300d 100644 --- a/com/win32com/client/gencache.py +++ b/com/win32com/client/gencache.py @@ -61,7 +61,7 @@ def __init__(): # Initialize the module. Called once explicitly at module import below. try: _LoadDicts() - except IOError: + except OSError: Rebuild() @@ -100,7 +100,7 @@ def _LoadDicts(): except AttributeError: # The __loader__ has no get_data method. See below. return - except IOError: + except OSError: # Our gencache is in a .zip file (and almost certainly readonly) # but no dicts file. That actually needn't be fatal for a frozen # application. Assuming they call "EnsureModule" with the same @@ -115,7 +115,7 @@ def _LoadDicts(): return f = io.BytesIO(data) else: - # NOTE: IOError on file open must be caught by caller. + # NOTE: OSError on file open must be caught by caller. f = open(os.path.join(win32com.__gen_path__, "dicts.dat"), "rb") try: p = pickle.Unpickler(f) @@ -147,12 +147,12 @@ def GetGeneratePath(): try: os.makedirs(win32com.__gen_path__) # os.mkdir(win32com.__gen_path__) - except os.error: + except OSError: pass try: fname = os.path.join(win32com.__gen_path__, "__init__.py") os.stat(fname) - except os.error: + except OSError: f = open(fname, "w") f.write( "# Generated file - this directory may be deleted to reset the COM cache...\n" @@ -528,11 +528,11 @@ def EnsureModule( # try to erase the bad file from the cache try: os.unlink(filePath) - except os.error: + except OSError: pass try: os.unlink(filePathPyc) - except os.error: + except OSError: pass if os.path.isdir(filePathPrefix): import shutil @@ -554,13 +554,13 @@ def EnsureModule( try: pyModTime = os.stat(filePath)[8] fModTimeSet = 1 - except os.error as e: + except OSError as e: # If .py file fails, try .pyc file # print "Trying pyc stat", filePathPyc try: pyModTime = os.stat(filePathPyc)[8] fModTimeSet = 1 - except os.error as e: + except OSError as e: pass # print "Trying stat typelib", pyModTime # print str(typLibPath) @@ -568,7 +568,7 @@ def EnsureModule( if fModTimeSet and (typLibModTime > pyModTime): bReloadNeeded = 1 module = None - except (ImportError, os.error): + except (ImportError, OSError): module = None if module is None: # We need to build an item. If we are in a read-only cache, we diff --git a/com/win32com/client/genpy.py b/com/win32com/client/genpy.py index c00a77e190..96997d3a29 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -1042,13 +1042,13 @@ def finish_writer(self, filename, f, worked): f.close() try: os.unlink(filename) - except os.error: + except OSError: pass temp_filename = self.get_temp_filename(filename) if worked: try: os.rename(temp_filename, filename) - except os.error: + except OSError: # If we are really unlucky, another process may have written the # file in between our calls to os.unlink and os.rename. So try # again, but only once. @@ -1064,7 +1064,7 @@ def finish_writer(self, filename, f, worked): # as well. try: os.unlink(filename) - except os.error: + except OSError: pass os.rename(temp_filename, filename) else: diff --git a/com/win32com/client/makepy.py b/com/win32com/client/makepy.py index 18974305b4..bb1bf4e07a 100644 --- a/com/win32com/client/makepy.py +++ b/com/win32com/client/makepy.py @@ -300,15 +300,15 @@ def GenerateFromTypeLibSpec( if bForDemand: try: os.unlink(full_name + ".py") - except os.error: + except OSError: pass try: os.unlink(full_name + ".pyc") - except os.error: + except OSError: pass try: os.unlink(full_name + ".pyo") - except os.error: + except OSError: pass if not os.path.isdir(full_name): os.mkdir(full_name) diff --git a/com/win32com/demos/excelAddin.py b/com/win32com/demos/excelAddin.py index 96f6cff8ab..8229477a8c 100644 --- a/com/win32com/demos/excelAddin.py +++ b/com/win32com/demos/excelAddin.py @@ -156,7 +156,7 @@ def UnregisterAddin(klass): winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Excel\\Addins\\" + klass._reg_progid_, ) - except WindowsError: + except OSError: pass diff --git a/com/win32com/demos/iebutton.py b/com/win32com/demos/iebutton.py index 0feb0e4883..6ded24c9f0 100644 --- a/com/win32com/demos/iebutton.py +++ b/com/win32com/demos/iebutton.py @@ -157,7 +157,7 @@ def register(classobj): winreg.SetValueEx(hKey, "ToolTip", 0, winreg.REG_SZ, classobj._tool_tip_) winreg.SetValueEx(hKey, "Icon", 0, winreg.REG_SZ, classobj._icon_) winreg.SetValueEx(hKey, "HotIcon", 0, winreg.REG_SZ, classobj._hot_icon_) - except WindowsError: + except OSError: print("Couldn't set standard toolbar reg keys.") else: print("Set standard toolbar reg keys.") @@ -180,7 +180,7 @@ def unregister(classobj): winreg.DeleteValue(hKey, "Icon") winreg.DeleteValue(hKey, "HotIcon") winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, subKeyCLSID) - except WindowsError: + except OSError: print("Couldn't delete Standard toolbar regkey.") else: print("Deleted Standard toolbar regkey.") diff --git a/com/win32com/demos/ietoolbar.py b/com/win32com/demos/ietoolbar.py index b259c406df..b520dcdad8 100644 --- a/com/win32com/demos/ietoolbar.py +++ b/com/win32com/demos/ietoolbar.py @@ -328,7 +328,7 @@ def DllRegisterServer(): subKey = winreg.SetValueEx( hkey, comclass._reg_clsid_, 0, winreg.REG_BINARY, "\0" ) - except WindowsError: + except OSError: print( "Couldn't set registry value.\nhkey: %d\tCLSID: %s\n" % (hkey, comclass._reg_clsid_) @@ -351,7 +351,7 @@ def DllUnregisterServer(): winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Internet Explorer\\Toolbar" ) winreg.DeleteValue(hkey, comclass._reg_clsid_) - except WindowsError: + except OSError: print( "Couldn't delete registry value.\nhkey: %d\tCLSID: %s\n" % (hkey, comclass._reg_clsid_) diff --git a/com/win32com/demos/outlookAddin.py b/com/win32com/demos/outlookAddin.py index 9433596d60..58f2f69878 100644 --- a/com/win32com/demos/outlookAddin.py +++ b/com/win32com/demos/outlookAddin.py @@ -124,7 +124,7 @@ def UnregisterAddin(klass): winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Outlook\\Addins\\" + klass._reg_progid_, ) - except WindowsError: + except OSError: pass diff --git a/com/win32com/server/register.py b/com/win32com/server/register.py index 6c8922e5ac..250c20d5ca 100644 --- a/com/win32com/server/register.py +++ b/com/win32com/server/register.py @@ -134,7 +134,7 @@ def _find_localserver_module(): pyfile = os.path.join(path, baseName + ".py") try: os.stat(pyfile) - except os.error: + except OSError: # See if we have a compiled extension if __debug__: ext = ".pyc" @@ -143,7 +143,7 @@ def _find_localserver_module(): pyfile = os.path.join(path, baseName + ext) try: os.stat(pyfile) - except os.error: + except OSError: raise RuntimeError( "Can not locate the Python module 'win32com.server.%s'" % baseName ) @@ -623,7 +623,7 @@ def ReExecuteElevated(flags): for f in (outfile, batfile): try: os.unlink(f) - except os.error as exc: + except OSError as exc: print("Failed to remove tempfile '%s': %s" % (f, exc)) diff --git a/com/win32com/test/GenTestScripts.py b/com/win32com/test/GenTestScripts.py index 4e5cf4a492..08b19d5905 100644 --- a/com/win32com/test/GenTestScripts.py +++ b/com/win32com/test/GenTestScripts.py @@ -27,7 +27,7 @@ def GenerateFromRegistered(fname, *loadArgs): genPath = GetGenPath() try: os.stat(genPath) - except os.error: + except OSError: os.mkdir(genPath) # Ensure an __init__ exists. open(os.path.join(genPath, "__init__.py"), "w").close() @@ -67,13 +67,13 @@ def CleanAll(): try: name = args[0] + ".py" os.unlink(os.path.join(genPath, name)) - except os.error as details: + except OSError as details: if isinstance(details, tuple) and details[0] != 2: print("Could not deleted generated", name, details) try: name = args[0] + ".pyc" os.unlink(os.path.join(genPath, name)) - except os.error as details: + except OSError as details: if isinstance(details, tuple) and details[0] != 2: print("Could not deleted generated", name, details) try: @@ -86,7 +86,7 @@ def CleanAll(): pass try: os.rmdir(genPath) - except os.error as details: + except OSError as details: print("Could not delete test directory -", details) diff --git a/com/win32com/test/testAccess.py b/com/win32com/test/testAccess.py index 161da9b5bf..1d41eb6fc5 100644 --- a/com/win32com/test/testAccess.py +++ b/com/win32com/test/testAccess.py @@ -26,7 +26,7 @@ def CreateTestAccessDatabase(dbname=None): try: os.unlink(dbname) - except os.error: + except OSError: print( "WARNING - Unable to delete old test database - expect a COM exception RSN!" ) diff --git a/com/win32com/test/testShell.py b/com/win32com/test/testShell.py index 3d1b51b892..23b996b0e4 100644 --- a/com/win32com/test/testShell.py +++ b/com/win32com/test/testShell.py @@ -221,7 +221,7 @@ def setUp(self): f.close() try: os.unlink(self.dest_name) - except os.error: + except OSError: pass def tearDown(self): diff --git a/com/win32com/test/testxslt.py b/com/win32com/test/testxslt.py index caaa2ec51f..62780ff429 100644 --- a/com/win32com/test/testxslt.py +++ b/com/win32com/test/testxslt.py @@ -26,7 +26,7 @@ def testAll(self): finally: try: os.unlink(output_name) - except os.error: + except OSError: pass diff --git a/com/win32com/test/util.py b/com/win32com/test/util.py index d36a0da917..1704f63267 100644 --- a/com/win32com/test/util.py +++ b/com/win32com/test/util.py @@ -45,7 +45,7 @@ def RegisterPythonServer(filename, progids=None, verbose=0): HKCR = winreg.HKEY_CLASSES_ROOT hk = winreg.OpenKey(HKCR, "CLSID\\%s" % clsid) dll = winreg.QueryValue(hk, "InprocServer32") - except WindowsError: + except OSError: # no CLSID or InProcServer32 - not registered break ok_files = [ diff --git a/com/win32comext/axdebug/Test/host.py b/com/win32comext/axdebug/Test/host.py index 7704f4fb17..da99b1b2fe 100644 --- a/com/win32comext/axdebug/Test/host.py +++ b/com/win32comext/axdebug/Test/host.py @@ -58,7 +58,7 @@ def _GetCodeContainer(self): if self.codeContainer is None: try: codeText = open(self.module.__file__, "rt").read() - except IOError as details: + except OSError as details: codeText = "# Exception opening file\n# %s" % (details) self.codeContainer = codecontainer.SourceCodeContainer( diff --git a/com/win32comext/axdebug/codecontainer.py b/com/win32comext/axdebug/codecontainer.py index 44c5f0e797..be20a2d394 100644 --- a/com/win32comext/axdebug/codecontainer.py +++ b/com/win32comext/axdebug/codecontainer.py @@ -225,7 +225,7 @@ def GetText(self): if fname: try: self.text = open(fname, "r").read() - except IOError as details: + except OSError as details: self.text = "# Exception opening file\n# %s" % (repr(details)) else: self.text = "# No file available for module '%s'" % (self.module) diff --git a/com/win32comext/ifilter/demo/filterDemo.py b/com/win32comext/ifilter/demo/filterDemo.py index 1eb7a01c0e..91b3c7c17b 100644 --- a/com/win32comext/ifilter/demo/filterDemo.py +++ b/com/win32comext/ifilter/demo/filterDemo.py @@ -220,7 +220,7 @@ def _trace(self, *args): ret = " ".join([str(arg) for arg in args]) try: print(ret) - except IOError: + except OSError: pass diff --git a/com/win32comext/shell/demos/servers/column_provider.py b/com/win32comext/shell/demos/servers/column_provider.py index 6c8625a448..ca0a2a10ae 100644 --- a/com/win32comext/shell/demos/servers/column_provider.py +++ b/com/win32comext/shell/demos/servers/column_provider.py @@ -108,7 +108,7 @@ def DllUnregisterServer(): winreg.HKEY_CLASSES_ROOT, "Folder\\ShellEx\\ColumnHandlers\\" + str(ColumnProvider._reg_clsid_), ) - except WindowsError as details: + except OSError as details: import errno if details.errno != errno.ENOENT: diff --git a/com/win32comext/shell/demos/servers/context_menu.py b/com/win32comext/shell/demos/servers/context_menu.py index b92109d738..3db4ee8ca4 100644 --- a/com/win32comext/shell/demos/servers/context_menu.py +++ b/com/win32comext/shell/demos/servers/context_menu.py @@ -104,7 +104,7 @@ def DllUnregisterServer(): winreg.HKEY_CLASSES_ROOT, "Python.File\\shellex\\ContextMenuHandlers\\PythonSample", ) - except WindowsError as details: + except OSError as details: import errno if details.errno != errno.ENOENT: diff --git a/com/win32comext/shell/demos/servers/copy_hook.py b/com/win32comext/shell/demos/servers/copy_hook.py index e5871fd80a..0b403b7fbc 100644 --- a/com/win32comext/shell/demos/servers/copy_hook.py +++ b/com/win32comext/shell/demos/servers/copy_hook.py @@ -55,7 +55,7 @@ def DllUnregisterServer(): winreg.HKEY_CLASSES_ROOT, "directory\\shellex\\CopyHookHandlers\\" + ShellExtension._reg_desc_, ) - except WindowsError as details: + except OSError as details: import errno if details.errno != errno.ENOENT: @@ -65,7 +65,7 @@ def DllUnregisterServer(): winreg.HKEY_CLASSES_ROOT, "*\\shellex\\CopyHookHandlers\\" + ShellExtension._reg_desc_, ) - except WindowsError as details: + except OSError as details: import errno if details.errno != errno.ENOENT: diff --git a/com/win32comext/shell/demos/servers/empty_volume_cache.py b/com/win32comext/shell/demos/servers/empty_volume_cache.py index a10d150e9f..6a0fb6a193 100644 --- a/com/win32comext/shell/demos/servers/empty_volume_cache.py +++ b/com/win32comext/shell/demos/servers/empty_volume_cache.py @@ -170,7 +170,7 @@ def DllUnregisterServer(): ) try: key = winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, kn) - except WindowsError as details: + except OSError as details: import errno if details.errno != errno.ENOENT: diff --git a/com/win32comext/shell/demos/servers/folder_view.py b/com/win32comext/shell/demos/servers/folder_view.py index 383270dff3..6e25c34d45 100644 --- a/com/win32comext/shell/demos/servers/folder_view.py +++ b/com/win32comext/shell/demos/servers/folder_view.py @@ -840,7 +840,7 @@ def DllUnregisterServer(): for path in paths: try: winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, path) - except WindowsError as details: + except OSError as details: import errno if details.errno != errno.ENOENT: diff --git a/com/win32comext/shell/demos/servers/icon_handler.py b/com/win32comext/shell/demos/servers/icon_handler.py index 57aa36110b..605dbeed09 100644 --- a/com/win32comext/shell/demos/servers/icon_handler.py +++ b/com/win32comext/shell/demos/servers/icon_handler.py @@ -64,7 +64,7 @@ def DllUnregisterServer(): key = winreg.DeleteKey( winreg.HKEY_CLASSES_ROOT, "Python.File\\shellex\\IconHandler" ) - except WindowsError as details: + except OSError as details: import errno if details.errno != errno.ENOENT: diff --git a/com/win32comext/shell/demos/servers/shell_view.py b/com/win32comext/shell/demos/servers/shell_view.py index 29b66ac573..2a1320b362 100644 --- a/com/win32comext/shell/demos/servers/shell_view.py +++ b/com/win32comext/shell/demos/servers/shell_view.py @@ -953,7 +953,7 @@ def DllUnregisterServer(): "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\" "Explorer\\Desktop\\Namespace\\" + ShellFolderRoot._reg_clsid_, ) - except WindowsError as details: + except OSError as details: import errno if details.errno != errno.ENOENT: diff --git a/isapi/__init__.py b/isapi/__init__.py index 71823616ae..0fa7dcace7 100644 --- a/isapi/__init__.py +++ b/isapi/__init__.py @@ -4,7 +4,7 @@ # Exceptions thrown by the DLL framework. class ISAPIError(Exception): def __init__(self, errno, strerror=None, funcname=None): - # named attributes match IOError etc. + # named attributes match OSError etc. self.errno = errno self.strerror = strerror self.funcname = funcname diff --git a/isapi/install.py b/isapi/install.py index 154f82aff3..7c9e63bf98 100644 --- a/isapi/install.py +++ b/isapi/install.py @@ -516,7 +516,7 @@ def CheckLoaderModule(dll_name): src_stat = os.stat(template) try: dest_stat = os.stat(dll_name) - except os.error: + except OSError: same = 0 else: same = ( diff --git a/pywin32_postinstall.py b/pywin32_postinstall.py index 5b6a6da749..1c0b396ad5 100644 --- a/pywin32_postinstall.py +++ b/pywin32_postinstall.py @@ -27,7 +27,7 @@ def write(self, what): if self.f is not None: try: self.f.write(what.replace("\n", "\r\n")) - except IOError: + except OSError: pass tee_f.write(what) @@ -35,7 +35,7 @@ def flush(self): if self.f is not None: try: self.f.flush() - except IOError: + except OSError: pass tee_f.flush() @@ -399,7 +399,7 @@ def fixup_dbi(): os.rename(this_pyd, this_dest) print("renamed '%s'->'%s.old'" % (this_pyd, this_pyd)) file_created(this_pyd + ".old") - except os.error as exc: + except OSError as exc: print("FAILED to rename '%s': %s" % (this_pyd, exc)) @@ -423,11 +423,11 @@ def install(lib_dir): for root in winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER: try: winreg.DeleteKey(root, keyname + "\\Debug") - except WindowsError: + except OSError: pass try: winreg.DeleteKey(root, keyname) - except WindowsError: + except OSError: pass LoadSystemModule(lib_dir, "pywintypes") LoadSystemModule(lib_dir, "pythoncom") @@ -635,11 +635,11 @@ def uninstall(lib_dir): # The dbi.pyd.old files we may have created. try: os.remove(os.path.join(lib_dir, "win32", "dbi.pyd.old")) - except os.error: + except OSError: pass try: os.remove(os.path.join(lib_dir, "win32", "dbi_d.pyd.old")) - except os.error: + except OSError: pass except Exception as why: @@ -764,7 +764,7 @@ def main(): if args.wait is not None: try: os.waitpid(args.wait, 0) - except os.error: + except OSError: # child already dead pass diff --git a/setup.py b/setup.py index ecaa7a692b..7309fc1199 100644 --- a/setup.py +++ b/setup.py @@ -306,7 +306,7 @@ def __init__(self, name, **kw): if type_id == winreg.REG_SZ: sdk_install_dir = value break - except WindowsError: + except OSError: pass if sdk_install_dir is not None: d = os.path.join(sdk_install_dir, "SDK", "Include") @@ -368,7 +368,7 @@ def run(self): f = open(ver_fname, "w") f.write("%s\n" % build_id) f.close() - except EnvironmentError as why: + except OSError as why: print("Failed to open '%s': %s" % (ver_fname, why)) diff --git a/win32/Demos/winprocess.py b/win32/Demos/winprocess.py index 48f6fe7194..d3af02f5fa 100644 --- a/win32/Demos/winprocess.py +++ b/win32/Demos/winprocess.py @@ -179,7 +179,7 @@ def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw): child = Process(cmd, **kw) if child.wait(mSec) != win32event.WAIT_OBJECT_0: child.kill() - raise WindowsError("process timeout exceeded") + raise OSError("process timeout exceeded") return child.exitCode() @@ -226,5 +226,5 @@ def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw): for n in (cmd_name, out_name): try: os.unlink(cmd_name) - except os.error: + except OSError: pass diff --git a/win32/Lib/regcheck.py b/win32/Lib/regcheck.py index c07b77b7a6..4bb2419aae 100644 --- a/win32/Lib/regcheck.py +++ b/win32/Lib/regcheck.py @@ -23,8 +23,7 @@ def CheckRegisteredExe(exename): regutil.GetRootKey(), regutil.GetAppPathsKey() + "\\" + exename ) ) - # except SystemError: - except (os.error, win32api.error): + except (OSError, win32api.error): print("Registration of %s - Not registered correctly" % exename) @@ -115,7 +114,7 @@ def CheckHelpFiles(verbose): os.stat(helpFile) if verbose: print(helpFile) - except os.error: + except OSError: print("** Help file %s does not exist" % helpFile) keyNo = keyNo + 1 except win32api.error as exc: diff --git a/win32/Lib/regutil.py b/win32/Lib/regutil.py index db6d849af2..9837637327 100644 --- a/win32/Lib/regutil.py +++ b/win32/Lib/regutil.py @@ -151,7 +151,7 @@ def RegisterModule(modName, modPath): import os os.stat(modPath) - except os.error: + except OSError: print("Warning: Registering non-existant module %s" % modPath) win32api.RegSetValue( GetRootKey(), @@ -209,7 +209,7 @@ def RegisterHelpFile(helpFile, helpPath, helpDesc=None, bCheckFile=1): try: if bCheckFile: os.stat(fullHelpFile) - except os.error: + except OSError: raise ValueError("Help file does not exist") # Now register with Python itself. win32api.RegSetValue( @@ -269,7 +269,7 @@ def RegisterCoreDLL(coredllName=None): else: try: os.stat(coredllName) - except os.error: + except OSError: print("Warning: Registering non-existant core DLL %s" % coredllName) hKey = win32api.RegCreateKey(GetRootKey(), BuildDefaultPythonKey()) diff --git a/win32/Lib/win32rcparser.py b/win32/Lib/win32rcparser.py index 1d90bfd717..627cea1baf 100644 --- a/win32/Lib/win32rcparser.py +++ b/win32/Lib/win32rcparser.py @@ -590,12 +590,12 @@ def Parse(rc_name, h_name=None): h_name = rc_name[:-2] + "h" try: h_file = open(h_name, "r") - except IOError: + except OSError: # See if MSVC default of 'resource.h' in the same dir. h_name = os.path.join(os.path.dirname(rc_name), "resource.h") try: h_file = open(h_name, "r") - except IOError: + except OSError: # .h files are optional anyway h_file = None rc_file = open(rc_name, "r") diff --git a/win32/Lib/win32serviceutil.py b/win32/Lib/win32serviceutil.py index 82e0a49431..4778c630c9 100644 --- a/win32/Lib/win32serviceutil.py +++ b/win32/Lib/win32serviceutil.py @@ -1027,7 +1027,7 @@ def SvcInterrogate(self): def SvcOther(self, control): try: print("Unknown control status - %d" % control) - except IOError: + except OSError: # services may not have a valid stdout! pass diff --git a/win32/Lib/win32timezone.py b/win32/Lib/win32timezone.py index 5a5445a0fd..ef853264a1 100644 --- a/win32/Lib/win32timezone.py +++ b/win32/Lib/win32timezone.py @@ -568,7 +568,7 @@ def _LoadDynamicInfoFromKey(self, key): """ try: info = key.subkey("Dynamic DST") - except WindowsError: + except OSError: return del info["FirstEntry"] del info["LastEntry"] @@ -824,7 +824,7 @@ def _enumerate_reg(key, func): try: for index in count(): yield func(key, index) - except WindowsError: + except OSError: pass diff --git a/win32/Lib/win32verstamp.py b/win32/Lib/win32verstamp.py index 074eccb6e8..64038cd233 100644 --- a/win32/Lib/win32verstamp.py +++ b/win32/Lib/win32verstamp.py @@ -126,7 +126,7 @@ def stamp(pathname, options): try: f = open(pathname, "a+b") f.close() - except IOError as why: + except OSError as why: print("WARNING: File %s could not be opened - %s" % (pathname, why)) ver = options.version diff --git a/win32/scripts/VersionStamp/BrandProject.py b/win32/scripts/VersionStamp/BrandProject.py index cc78d8d91f..6a0cf1716f 100644 --- a/win32/scripts/VersionStamp/BrandProject.py +++ b/win32/scripts/VersionStamp/BrandProject.py @@ -90,7 +90,7 @@ def usage(msg): path = args[2] try: os.stat(descFile) - except IOError: + except OSError: usage("The description file '%s' can not be found" % (descFile)) if not os.path.isdir(path): usage("The path to the files to stamp '%s' does not exist" % (path)) diff --git a/win32/scripts/backupEventLog.py b/win32/scripts/backupEventLog.py index bc7d53fec5..6dd37bb227 100644 --- a/win32/scripts/backupEventLog.py +++ b/win32/scripts/backupEventLog.py @@ -21,7 +21,7 @@ def BackupClearLog(logType): "%s%s-%s" % (datePrefix, index, logType) + ".evt", ) os.stat(fname) - except os.error: + except OSError: fileExists = 0 retry = retry + 1 # OK - have unique file name. diff --git a/win32/scripts/regsetup.py b/win32/scripts/regsetup.py index cf8c5e980e..20a4f84719 100644 --- a/win32/scripts/regsetup.py +++ b/win32/scripts/regsetup.py @@ -15,7 +15,7 @@ def FileExists(fname): try: os.stat(fname) return 1 - except os.error as details: + except OSError as details: return 0 @@ -192,7 +192,7 @@ def LocateFileName(fileNamesString, searchPaths): retPath = os.path.join(path, fileName) os.stat(retPath) break - except os.error: + except OSError: retPath = None if retPath: break diff --git a/win32/test/handles.py b/win32/test/handles.py index b1f2240ba3..e8c297499c 100644 --- a/win32/test/handles.py +++ b/win32/test/handles.py @@ -27,16 +27,16 @@ def f1(invalidate): # this case def f2(invalidate): - """This function should throw an IOError.""" + """This function should throw an OSError.""" try: f1(invalidate) except ZeroDivisionError as exc: - raise IOError("raise 2") + raise OSError("raise 2") - self.assertRaises(IOError, f2, False) + self.assertRaises(OSError, f2, False) # Now do it again, but so the auto object destruction # actually fails. - self.assertRaises(IOError, f2, True) + self.assertRaises(OSError, f2, True) def testCleanup2(self): # Cause an exception during object destruction. diff --git a/win32/test/test_win32file.py b/win32/test/test_win32file.py index c57e94ad5b..9c0b37488f 100644 --- a/win32/test/test_win32file.py +++ b/win32/test/test_win32file.py @@ -65,7 +65,7 @@ def testSimpleFiles(self): handle.Close() try: os.unlink(filename) - except os.error: + except OSError: pass # A simple test using normal read/write operations. @@ -573,7 +573,7 @@ def testEmptyDir(self): # reference count leaks, that function showed leaks! os.rmdir # doesn't have that problem. os.rmdir(test_path) - except os.error: + except OSError: pass os.mkdir(test_path) try: @@ -863,7 +863,7 @@ def runner(): try: s1.bind(self.addr) break - except os.error as exc: + except OSError as exc: if exc.winerror != 10013: raise print("Failed to use port", self.addr, "trying another random one") @@ -1013,7 +1013,7 @@ def test_functional(self): while sent < 16 * 1024 * 1024: try: sent += client.send(data) - except socket.error as e: + except OSError as e: if e.args[0] == win32file.WSAEINTR: continue elif e.args[0] in (win32file.WSAEWOULDBLOCK, win32file.WSAENOBUFS): @@ -1035,7 +1035,7 @@ def test_functional(self): while received < sent: try: received += len(server.recv(16 * 1024)) - except socket.error as e: + except OSError as e: if e.args[0] in [win32file.WSAEINTR, win32file.WSAEWOULDBLOCK]: continue else: From 56ecf8cecbe10ffce67c9f5c5793e290c6a7c594 Mon Sep 17 00:00:00 2001 From: Avasam Date: Thu, 21 Sep 2023 10:59:42 -0400 Subject: [PATCH 06/22] Update collections literals and comprehensions (#2108) --- com/win32com/test/testShell.py | 86 +++++++++---------- com/win32comext/axdebug/expressions.py | 2 +- com/win32comext/bits/test/show_all_jobs.py | 24 +++--- com/win32comext/bits/test/test_bits.py | 12 ++- .../shell/demos/IFileOperationProgressSink.py | 4 +- .../shell/demos/ITransferAdviseSink.py | 4 +- .../shell/demos/servers/folder_view.py | 10 ++- win32/Lib/win32timezone.py | 6 +- win32/test/handles.py | 4 +- win32/test/test_pywintypes.py | 2 +- win32/test/test_security.py | 2 +- win32/test/test_win32guistruct.py | 74 ++++++++-------- win32/test/test_win32inet.py | 2 +- 13 files changed, 116 insertions(+), 116 deletions(-) diff --git a/com/win32com/test/testShell.py b/com/win32com/test/testShell.py index 23b996b0e4..fdc4babaa8 100644 --- a/com/win32com/test/testShell.py +++ b/com/win32com/test/testShell.py @@ -137,8 +137,8 @@ def _testSimple(self, make_unicode): fgd = shell.FILEGROUPDESCRIPTORAsString([], make_unicode) header = struct.pack("i", 0) self.assertEqual(header, fgd[: len(header)]) - self._testRT(dict()) - d = dict() + self._testRT({}) + d = {} fgd = shell.FILEGROUPDESCRIPTORAsString([d], make_unicode) header = struct.pack("i", 1) self.assertEqual(header, fgd[: len(header)]) @@ -153,53 +153,53 @@ def testSimpleUnicode(self): def testComplex(self): clsid = pythoncom.MakeIID("{CD637886-DB8B-4b04-98B5-25731E1495BE}") ctime, atime, wtime = self._getTestTimes() - d = dict( - cFileName="foo.txt", - clsid=clsid, - sizel=(1, 2), - pointl=(3, 4), - dwFileAttributes=win32con.FILE_ATTRIBUTE_NORMAL, - ftCreationTime=ctime, - ftLastAccessTime=atime, - ftLastWriteTime=wtime, - nFileSize=sys.maxsize + 1, - ) + d = { + "cFileName": "foo.txt", + "clsid": clsid, + "sizel": (1, 2), + "pointl": (3, 4), + "dwFileAttributes": win32con.FILE_ATTRIBUTE_NORMAL, + "ftCreationTime": ctime, + "ftLastAccessTime": atime, + "ftLastWriteTime": wtime, + "nFileSize": sys.maxsize + 1, + } self._testRT(d) def testUnicode(self): # exercise a bug fixed in build 210 - multiple unicode objects failed. ctime, atime, wtime = self._getTestTimes() d = [ - dict( - cFileName="foo.txt", - sizel=(1, 2), - pointl=(3, 4), - dwFileAttributes=win32con.FILE_ATTRIBUTE_NORMAL, - ftCreationTime=ctime, - ftLastAccessTime=atime, - ftLastWriteTime=wtime, - nFileSize=sys.maxsize + 1, - ), - dict( - cFileName="foo2.txt", - sizel=(1, 2), - pointl=(3, 4), - dwFileAttributes=win32con.FILE_ATTRIBUTE_NORMAL, - ftCreationTime=ctime, - ftLastAccessTime=atime, - ftLastWriteTime=wtime, - nFileSize=sys.maxsize + 1, - ), - dict( - cFileName="foo\xa9.txt", - sizel=(1, 2), - pointl=(3, 4), - dwFileAttributes=win32con.FILE_ATTRIBUTE_NORMAL, - ftCreationTime=ctime, - ftLastAccessTime=atime, - ftLastWriteTime=wtime, - nFileSize=sys.maxsize + 1, - ), + { + "cFileName": "foo.txt", + "sizel": (1, 2), + "pointl": (3, 4), + "dwFileAttributes": win32con.FILE_ATTRIBUTE_NORMAL, + "ftCreationTime": ctime, + "ftLastAccessTime": atime, + "ftLastWriteTime": wtime, + "nFileSize": sys.maxsize + 1, + }, + { + "cFileName": "foo2.txt", + "sizel": (1, 2), + "pointl": (3, 4), + "dwFileAttributes": win32con.FILE_ATTRIBUTE_NORMAL, + "ftCreationTime": ctime, + "ftLastAccessTime": atime, + "ftLastWriteTime": wtime, + "nFileSize": sys.maxsize + 1, + }, + { + "cFileName": "foo\xa9.txt", + "sizel": (1, 2), + "pointl": (3, 4), + "dwFileAttributes": win32con.FILE_ATTRIBUTE_NORMAL, + "ftCreationTime": ctime, + "ftLastAccessTime": atime, + "ftLastWriteTime": wtime, + "nFileSize": sys.maxsize + 1, + }, ] s = shell.FILEGROUPDESCRIPTORAsString(d, 1) d2 = shell.StringAsFILEGROUPDESCRIPTOR(s) diff --git a/com/win32comext/axdebug/expressions.py b/com/win32comext/axdebug/expressions.py index 28c7b90457..e573eb514e 100644 --- a/com/win32comext/axdebug/expressions.py +++ b/com/win32comext/axdebug/expressions.py @@ -65,7 +65,7 @@ def Start(self, callback): sys.exc_info()[0], sys.exc_info()[1] ) # l is a list of strings with trailing "\n" - self.result = string.join(map(lambda s: s[:-1], l), "\n") + self.result = string.join((s[:-1] for s in l), "\n") self.hresult = winerror.E_FAIL finally: self.isComplete = 1 diff --git a/com/win32comext/bits/test/show_all_jobs.py b/com/win32comext/bits/test/show_all_jobs.py index 8ce230ce0c..904e127d3e 100644 --- a/com/win32comext/bits/test/show_all_jobs.py +++ b/com/win32comext/bits/test/show_all_jobs.py @@ -2,21 +2,17 @@ import pythoncom from win32com.bits import bits -states = dict( - [ - (val, (name[13:])) - for name, val in vars(bits).items() - if name.startswith("BG_JOB_STATE_") - ] -) +states = { + val: name[13:] + for name, val in vars(bits).items() + if name.startswith("BG_JOB_STATE_") +} -job_types = dict( - [ - (val, (name[12:])) - for name, val in vars(bits).items() - if name.startswith("BG_JOB_TYPE_") - ] -) +job_types = { + val: name[12:] + for name, val in vars(bits).items() + if name.startswith("BG_JOB_TYPE_") +} bcm = pythoncom.CoCreateInstance( bits.CLSID_BackgroundCopyManager, diff --git a/com/win32comext/bits/test/test_bits.py b/com/win32comext/bits/test/test_bits.py index 94bcbe4be5..6ff7005fb6 100755 --- a/com/win32comext/bits/test/test_bits.py +++ b/com/win32comext/bits/test/test_bits.py @@ -11,13 +11,11 @@ StopEvent = win32event.CreateEvent(None, 0, 0, None) job_name = "bits-pywin32-test" -states = dict( - [ - (val, (name[13:])) - for name, val in vars(bits).items() - if name.startswith("BG_JOB_STATE_") - ] -) +states = { + val: (name[13:]) + for name, val in vars(bits).items() + if name.startswith("BG_JOB_STATE_") +} bcm = pythoncom.CoCreateInstance( bits.CLSID_BackgroundCopyManager, diff --git a/com/win32comext/shell/demos/IFileOperationProgressSink.py b/com/win32comext/shell/demos/IFileOperationProgressSink.py index de117ad0f0..e9108bbd0b 100644 --- a/com/win32comext/shell/demos/IFileOperationProgressSink.py +++ b/com/win32comext/shell/demos/IFileOperationProgressSink.py @@ -5,9 +5,7 @@ from win32com.server.policy import DesignatedWrapPolicy from win32com.shell import shell, shellcon -tsf_flags = list( - (k, v) for k, v in list(shellcon.__dict__.items()) if k.startswith("TSF_") -) +tsf_flags = [(k, v) for k, v in list(shellcon.__dict__.items()) if k.startswith("TSF_")] def decode_flags(flags): diff --git a/com/win32comext/shell/demos/ITransferAdviseSink.py b/com/win32comext/shell/demos/ITransferAdviseSink.py index fc766fb0b2..dfd25eb513 100644 --- a/com/win32comext/shell/demos/ITransferAdviseSink.py +++ b/com/win32comext/shell/demos/ITransferAdviseSink.py @@ -4,9 +4,7 @@ from win32com.server.policy import DesignatedWrapPolicy from win32com.shell import shell, shellcon -tsf_flags = list( - (k, v) for k, v in list(shellcon.__dict__.items()) if k.startswith("TSF_") -) +tsf_flags = [(k, v) for k, v in list(shellcon.__dict__.items()) if k.startswith("TSF_")] TRANSFER_ADVISE_STATES = {} for k, v in list(shellcon.__dict__.items()): diff --git a/com/win32comext/shell/demos/servers/folder_view.py b/com/win32comext/shell/demos/servers/folder_view.py index 6e25c34d45..08ca34731c 100644 --- a/com/win32comext/shell/demos/servers/folder_view.py +++ b/com/win32comext/shell/demos/servers/folder_view.py @@ -150,9 +150,13 @@ def make_item_enum(level, flags): else: skip = not (flags & shellcon.SHCONTF_NONFOLDERS) if not skip: - data = dict( - name=name, size=size, sides=sides, level=level, is_folder=is_folder - ) + data = { + "name": name, + "size": size, + "sides": sides, + "level": level, + "is_folder": is_folder, + } pidls.append([pickle.dumps(data)]) return NewEnum(pidls, shell.IID_IEnumIDList) diff --git a/win32/Lib/win32timezone.py b/win32/Lib/win32timezone.py index ef853264a1..42aef980bc 100644 --- a/win32/Lib/win32timezone.py +++ b/win32/Lib/win32timezone.py @@ -578,7 +578,7 @@ def _LoadDynamicInfoFromKey(self, key): # if the target year is greater or equal. self.dynamicInfo = RangeMap( zip(years, values), - sort_params=dict(reverse=True), + sort_params={"reverse": True}, key_match_comparator=operator.ge, ) @@ -967,7 +967,7 @@ def __init__(self, source, sort_params={}, key_match_comparator=operator.le): self.match = key_match_comparator def __getitem__(self, item): - sorted_keys = sorted(list(self.keys()), **self.sort_params) + sorted_keys = sorted(self.keys(), **self.sort_params) if isinstance(item, RangeMap.Item): result = self.__getitem__(sorted_keys[item]) else: @@ -998,7 +998,7 @@ def is_match(k): raise KeyError(item) def bounds(self): - sorted_keys = sorted(list(self.keys()), **self.sort_params) + sorted_keys = sorted(self.keys(), **self.sort_params) return ( sorted_keys[RangeMap.first_item], sorted_keys[RangeMap.last_item], diff --git a/win32/test/handles.py b/win32/test/handles.py index e8c297499c..eb71524952 100644 --- a/win32/test/handles.py +++ b/win32/test/handles.py @@ -100,12 +100,12 @@ def testOtherHandle(self): def testHandleInDict(self): h = pywintypes.HANDLE(1) - d = dict(foo=h) + d = {"foo": h} self.assertEqual(d["foo"], h) def testHandleInDictThenInt(self): h = pywintypes.HANDLE(1) - d = dict(foo=h) + d = {"foo": h} self.assertEqual(d["foo"], 1) def testHandleCompareNone(self): diff --git a/win32/test/test_pywintypes.py b/win32/test/test_pywintypes.py index 0a932fcd33..313171c63e 100644 --- a/win32/test/test_pywintypes.py +++ b/win32/test/test_pywintypes.py @@ -103,7 +103,7 @@ def testGUIDRichCmp(self): def testGUIDInDict(self): s = "{00020400-0000-0000-C000-000000000046}" iid = pywintypes.IID(s) - d = dict(item=iid) + d = {"item": iid} self.assertEqual(d["item"], iid) diff --git a/win32/test/test_security.py b/win32/test/test_security.py index 52be9f328c..11e9780de2 100644 --- a/win32/test/test_security.py +++ b/win32/test/test_security.py @@ -46,7 +46,7 @@ def testNEOther(self): self.assertNotEqual(None, self.pwr_sid) def testSIDInDict(self): - d = dict(foo=self.pwr_sid) + d = {"foo": self.pwr_sid} self.assertEqual(d["foo"], self.pwr_sid) def testBuffer(self): diff --git a/win32/test/test_win32guistruct.py b/win32/test/test_win32guistruct.py index 063cea3a7f..0c1d1d1c09 100644 --- a/win32/test/test_win32guistruct.py +++ b/win32/test/test_win32guistruct.py @@ -9,7 +9,7 @@ class TestBase(unittest.TestCase): def assertDictEquals(self, d, **kw): - checked = dict() + checked = {} for n, v in kw.items(): self.assertEqual(v, d[n], "'%s' doesn't match: %r != %r" % (n, v, d[n])) checked[n] = True @@ -22,17 +22,17 @@ def assertDictEquals(self, d, **kw): class TestMenuItemInfo(TestBase): def _testPackUnpack(self, text): - vals = dict( - fType=win32con.MFT_MENUBARBREAK, - fState=win32con.MFS_CHECKED, - wID=123, - hSubMenu=1234, - hbmpChecked=12345, - hbmpUnchecked=123456, - dwItemData=1234567, - text=text, - hbmpItem=321, - ) + vals = { + "fType": win32con.MFT_MENUBARBREAK, + "fState": win32con.MFS_CHECKED, + "wID": 123, + "hSubMenu": 1234, + "hbmpChecked": 12345, + "hbmpUnchecked": 123456, + "dwItemData": 1234567, + "text": text, + "hbmpItem": 321, + } mii, extras = win32gui_struct.PackMENUITEMINFO(**vals) ( fType, @@ -94,7 +94,13 @@ def testEmptyMenuItemInfo(self): class TestMenuInfo(TestBase): def testPackUnpack(self): - vals = dict(dwStyle=1, cyMax=2, hbrBack=3, dwContextHelpID=4, dwMenuData=5) + vals = { + "dwStyle": 1, + "cyMax": 2, + "hbrBack": 3, + "dwContextHelpID": 4, + "dwMenuData": 5, + } mi = win32gui_struct.PackMENUINFO(**vals) ( @@ -132,16 +138,16 @@ def testEmptyMenuItemInfo(self): class TestTreeViewItem(TestBase): def _testPackUnpack(self, text): - vals = dict( - hitem=1, - state=2, - stateMask=3, - text=text, - image=4, - selimage=5, - citems=6, - param=7, - ) + vals = { + "hitem": 1, + "state": 2, + "stateMask": 3, + "text": text, + "image": 4, + "selimage": 5, + "citems": 6, + "param": 7, + } ti, extra = win32gui_struct.PackTVITEM(**vals) ( @@ -197,16 +203,16 @@ def testEmpty(self): class TestListViewItem(TestBase): def _testPackUnpack(self, text): - vals = dict( - item=None, - subItem=None, - state=1, - stateMask=2, - text=text, - image=3, - param=4, - indent=5, - ) + vals = { + "item": None, + "subItem": None, + "state": 1, + "stateMask": 2, + "text": text, + "image": 3, + "param": 4, + "indent": 5, + } ti, extra = win32gui_struct.PackLVITEM(**vals) ( @@ -265,7 +271,7 @@ def testEmpty(self): class TestLVColumn(TestBase): def _testPackUnpack(self, text): - vals = dict(fmt=1, cx=2, text=text, subItem=3, image=4, order=5) + vals = {"fmt": 1, "cx": 2, "text": text, "subItem": 3, "image": 4, "order": 5} ti, extra = win32gui_struct.PackLVCOLUMN(**vals) fmt, cx, text, subItem, image, order = win32gui_struct.UnpackLVCOLUMN(ti) diff --git a/win32/test/test_win32inet.py b/win32/test/test_win32inet.py index d2d30c5252..bf4a9af3cc 100644 --- a/win32/test/test_win32inet.py +++ b/win32/test/test_win32inet.py @@ -12,7 +12,7 @@ def testCookies(self): InternetSetCookie("http://www.python.org", None, data) got = InternetGetCookie("http://www.python.org", None) # handle that there might already be cookies for the domain. - bits = map(lambda x: x.strip(), got.split(";")) + bits = (x.strip() for x in got.split(";")) self.assertTrue(data in bits) def testCookiesEmpty(self): From ea314af45d9002917c9f09172cad164245560407 Mon Sep 17 00:00:00 2001 From: Avasam Date: Thu, 21 Sep 2023 11:00:51 -0400 Subject: [PATCH 07/22] Remove extraneous parenthesis found by Ruff/pyupgrade (#2110) --- Pythonwin/pywin/framework/stdin.py | 2 +- Pythonwin/pywin/scintilla/formatter.py | 4 +-- com/win32com/olectl.py | 2 +- com/win32com/test/testConversionErrors.py | 2 +- com/win32comext/adsi/adsicon.py | 36 +++++++++++------------ win32/Lib/winnt.py | 2 +- win32/test/test_exceptions.py | 4 +-- 7 files changed, 26 insertions(+), 26 deletions(-) diff --git a/Pythonwin/pywin/framework/stdin.py b/Pythonwin/pywin/framework/stdin.py index a9b56e9f15..93f5c02df2 100644 --- a/Pythonwin/pywin/framework/stdin.py +++ b/Pythonwin/pywin/framework/stdin.py @@ -151,7 +151,7 @@ def fake_input(prompt=None): result = test_input[:end_of_line_pos] test_input = test_input[end_of_line_pos + 1 :] if len(result) == 0 or result[0] == "~": - raise EOFError() + raise EOFError return result get_input_line = fake_input diff --git a/Pythonwin/pywin/scintilla/formatter.py b/Pythonwin/pywin/scintilla/formatter.py index 3687d64e00..0df8015366 100644 --- a/Pythonwin/pywin/scintilla/formatter.py +++ b/Pythonwin/pywin/scintilla/formatter.py @@ -92,7 +92,7 @@ def __init__(self, scintilla): self.SetStyles() def HookFormatter(self, parent=None): - raise NotImplementedError() + raise NotImplementedError # Used by the IDLE extensions to quickly determine if a character is a string. def GetStringStyle(self, pos): @@ -114,7 +114,7 @@ def RegisterStyle(self, style, stylenum): self.styles_by_id[stylenum] = style def SetStyles(self): - raise NotImplementedError() + raise NotImplementedError def GetSampleText(self): return "Sample Text for the Format Dialog" diff --git a/com/win32com/olectl.py b/com/win32com/olectl.py index 50ec6f746b..f6be98bda2 100644 --- a/com/win32com/olectl.py +++ b/com/win32com/olectl.py @@ -9,7 +9,7 @@ def MAKE_SCODE(sev, fac, code): - return int((int(-sev) << 31) | ((fac) << 16) | ((code))) + return int((int(-sev) << 31) | ((fac) << 16) | (code)) def STD_CTL_SCODE(n): diff --git a/com/win32com/test/testConversionErrors.py b/com/win32com/test/testConversionErrors.py index a4b755e688..773b9b80f3 100644 --- a/com/win32com/test/testConversionErrors.py +++ b/com/win32com/test/testConversionErrors.py @@ -23,7 +23,7 @@ class TestException(Exception): # The object we try and pass - pywin32 will call __float__ as a last resort. class BadConversions: def __float__(self): - raise TestException() + raise TestException class TestCase(win32com.test.util.TestCase): diff --git a/com/win32comext/adsi/adsicon.py b/com/win32comext/adsi/adsicon.py index 9944aefaf9..73080790b8 100644 --- a/com/win32comext/adsi/adsicon.py +++ b/com/win32comext/adsi/adsicon.py @@ -226,27 +226,27 @@ def _HRESULT_TYPEDEF_(_sc): return _sc -E_ADS_BAD_PATHNAME = _HRESULT_TYPEDEF_((-2147463168)) -E_ADS_INVALID_DOMAIN_OBJECT = _HRESULT_TYPEDEF_((-2147463167)) -E_ADS_INVALID_USER_OBJECT = _HRESULT_TYPEDEF_((-2147463166)) -E_ADS_INVALID_COMPUTER_OBJECT = _HRESULT_TYPEDEF_((-2147463165)) -E_ADS_UNKNOWN_OBJECT = _HRESULT_TYPEDEF_((-2147463164)) -E_ADS_PROPERTY_NOT_SET = _HRESULT_TYPEDEF_((-2147463163)) -E_ADS_PROPERTY_NOT_SUPPORTED = _HRESULT_TYPEDEF_((-2147463162)) -E_ADS_PROPERTY_INVALID = _HRESULT_TYPEDEF_((-2147463161)) -E_ADS_BAD_PARAMETER = _HRESULT_TYPEDEF_((-2147463160)) -E_ADS_OBJECT_UNBOUND = _HRESULT_TYPEDEF_((-2147463159)) -E_ADS_PROPERTY_NOT_MODIFIED = _HRESULT_TYPEDEF_((-2147463158)) -E_ADS_PROPERTY_MODIFIED = _HRESULT_TYPEDEF_((-2147463157)) -E_ADS_CANT_CONVERT_DATATYPE = _HRESULT_TYPEDEF_((-2147463156)) -E_ADS_PROPERTY_NOT_FOUND = _HRESULT_TYPEDEF_((-2147463155)) -E_ADS_OBJECT_EXISTS = _HRESULT_TYPEDEF_((-2147463154)) -E_ADS_SCHEMA_VIOLATION = _HRESULT_TYPEDEF_((-2147463153)) -E_ADS_COLUMN_NOT_SET = _HRESULT_TYPEDEF_((-2147463152)) +E_ADS_BAD_PATHNAME = _HRESULT_TYPEDEF_(-2147463168) +E_ADS_INVALID_DOMAIN_OBJECT = _HRESULT_TYPEDEF_(-2147463167) +E_ADS_INVALID_USER_OBJECT = _HRESULT_TYPEDEF_(-2147463166) +E_ADS_INVALID_COMPUTER_OBJECT = _HRESULT_TYPEDEF_(-2147463165) +E_ADS_UNKNOWN_OBJECT = _HRESULT_TYPEDEF_(-2147463164) +E_ADS_PROPERTY_NOT_SET = _HRESULT_TYPEDEF_(-2147463163) +E_ADS_PROPERTY_NOT_SUPPORTED = _HRESULT_TYPEDEF_(-2147463162) +E_ADS_PROPERTY_INVALID = _HRESULT_TYPEDEF_(-2147463161) +E_ADS_BAD_PARAMETER = _HRESULT_TYPEDEF_(-2147463160) +E_ADS_OBJECT_UNBOUND = _HRESULT_TYPEDEF_(-2147463159) +E_ADS_PROPERTY_NOT_MODIFIED = _HRESULT_TYPEDEF_(-2147463158) +E_ADS_PROPERTY_MODIFIED = _HRESULT_TYPEDEF_(-2147463157) +E_ADS_CANT_CONVERT_DATATYPE = _HRESULT_TYPEDEF_(-2147463156) +E_ADS_PROPERTY_NOT_FOUND = _HRESULT_TYPEDEF_(-2147463155) +E_ADS_OBJECT_EXISTS = _HRESULT_TYPEDEF_(-2147463154) +E_ADS_SCHEMA_VIOLATION = _HRESULT_TYPEDEF_(-2147463153) +E_ADS_COLUMN_NOT_SET = _HRESULT_TYPEDEF_(-2147463152) S_ADS_ERRORSOCCURRED = _HRESULT_TYPEDEF_(0x00005011) S_ADS_NOMORE_ROWS = _HRESULT_TYPEDEF_(0x00005012) S_ADS_NOMORE_COLUMNS = _HRESULT_TYPEDEF_(0x00005013) -E_ADS_INVALID_FILTER = _HRESULT_TYPEDEF_((-2147463148)) +E_ADS_INVALID_FILTER = _HRESULT_TYPEDEF_(-2147463148) # ADS_DEREFENUM enum ADS_DEREF_NEVER = 0 diff --git a/win32/Lib/winnt.py b/win32/Lib/winnt.py index a88627e0fd..80fe348e71 100644 --- a/win32/Lib/winnt.py +++ b/win32/Lib/winnt.py @@ -176,7 +176,7 @@ def LANGIDFROMLCID(lcid): def SORTIDFROMLCID(lcid): - return (((lcid)) & NLS_VALID_LOCALE_MASK) >> 16 + return ((lcid) & NLS_VALID_LOCALE_MASK) >> 16 MAXIMUM_WAIT_OBJECTS = 64 diff --git a/win32/test/test_exceptions.py b/win32/test/test_exceptions.py index 2944da364c..ad956abf66 100644 --- a/win32/test/test_exceptions.py +++ b/win32/test/test_exceptions.py @@ -86,7 +86,7 @@ def testAttributes(self): # some tests for 'insane' args. def testStrangeArgsNone(self): try: - raise pywintypes.error() + raise pywintypes.error self.fail("Expected exception") except pywintypes.error as exc: self.assertEqual(exc.args, ()) @@ -176,7 +176,7 @@ def testAttributes(self): def testStrangeArgsNone(self): try: - raise pywintypes.com_error() + raise pywintypes.com_error self.fail("Expected exception") except pywintypes.com_error as exc: self.assertEqual(exc.args, ()) From 4445881a23be2ecc2ae13a37a14109e2d3971c18 Mon Sep 17 00:00:00 2001 From: Avasam Date: Thu, 21 Sep 2023 11:01:25 -0400 Subject: [PATCH 08/22] Update unicode strings in comments (#2111) --- com/win32com/test/testStorage.py | 2 +- win32/Demos/security/sspi/simple_auth.py | 2 +- win32/Lib/win32timezone.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/com/win32com/test/testStorage.py b/com/win32com/test/testStorage.py index 5b7e25de93..3bbe776ce2 100644 --- a/com/win32com/test/testStorage.py +++ b/com/win32com/test/testStorage.py @@ -14,7 +14,7 @@ def testit(self): pss = pythoncom.StgOpenStorageEx( fname, m, storagecon.STGFMT_FILE, 0, pythoncom.IID_IPropertySetStorage ) - ### {"Version":2,"reserved":0,"SectorSize":512,"TemplateFile":u'somefilename'}) + ### {"Version":2,"reserved":0,"SectorSize":512,"TemplateFile":'somefilename'}) ## FMTID_SummaryInformation FMTID_DocSummaryInformation FMTID_UserDefinedProperties psuser = pss.Create( diff --git a/win32/Demos/security/sspi/simple_auth.py b/win32/Demos/security/sspi/simple_auth.py index cc0ce5cf92..2721ca780d 100644 --- a/win32/Demos/security/sspi/simple_auth.py +++ b/win32/Demos/security/sspi/simple_auth.py @@ -18,7 +18,7 @@ def lookup_ret_code(err): pkg_name='Kerberos' sspiclient=SSPIClient(pkg_name, win32api.GetUserName(), ## target spn is ourself None, None, ## use none for client name and authentication information for current context - ## u'username', (u'username',u'domain.com',u'passwd'), + ## 'username', ('username','domain.com','passwd'), sspicon.ISC_REQ_INTEGRITY|sspicon.ISC_REQ_SEQUENCE_DETECT|sspicon.ISC_REQ_REPLAY_DETECT| \ sspicon.ISC_REQ_DELEGATE|sspicon.ISC_REQ_CONFIDENTIALITY|sspicon.ISC_REQ_USE_SESSION_KEY) sspiserver=SSPIServer(pkg_name, None, diff --git a/win32/Lib/win32timezone.py b/win32/Lib/win32timezone.py index 42aef980bc..442cb1f6d2 100644 --- a/win32/Lib/win32timezone.py +++ b/win32/Lib/win32timezone.py @@ -144,7 +144,7 @@ True This test helps ensure language support for unicode characters ->>> x = TIME_ZONE_INFORMATION(0, u'français') +>>> x = TIME_ZONE_INFORMATION(0, 'français') Test conversion from one time zone to another at a DST boundary From 03a8bb1d7d1f77b3b5c15915a22fe578036a3a1d Mon Sep 17 00:00:00 2001 From: Avasam Date: Thu, 21 Sep 2023 11:05:28 -0400 Subject: [PATCH 09/22] Replace usages of the `imp` module (#2113) --- com/win32comext/axscript/client/pyscript.py | 4 ++-- isapi/install.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/com/win32comext/axscript/client/pyscript.py b/com/win32comext/axscript/client/pyscript.py index 4da7db0b5b..b359791051 100644 --- a/com/win32comext/axscript/client/pyscript.py +++ b/com/win32comext/axscript/client/pyscript.py @@ -8,6 +8,7 @@ """ import re +import types import pythoncom import win32api @@ -210,10 +211,9 @@ def __init__(self): def InitNew(self): framework.COMScript.InitNew(self) - import imp self.scriptDispatch = None - self.globalNameSpaceModule = imp.new_module("__ax_main__") + self.globalNameSpaceModule = types.ModuleType("__ax_main__") self.globalNameSpaceModule.__dict__["ax"] = AXScriptAttribute(self) self.codeBlocks = [] diff --git a/isapi/install.py b/isapi/install.py index 7c9e63bf98..12416fd645 100644 --- a/isapi/install.py +++ b/isapi/install.py @@ -2,7 +2,7 @@ # this code adapted from "Tomcat JK2 ISAPI redirector", part of Apache # Created July 2004, Mark Hammond. -import imp +import importlib.machinery import os import shutil import stat @@ -39,7 +39,7 @@ _DEFAULT_ENABLE_DIR_BROWSING = False _DEFAULT_ENABLE_DEFAULT_DOC = False -_extensions = [ext for ext, _, _ in imp.get_suffixes()] +_extensions = [ext for ext, _, _ in importlib.machinery.EXTENSION_SUFFIXES] is_debug_build = "_d.pyd" in _extensions this_dir = os.path.abspath(os.path.dirname(__file__)) From 22efab538eb31e6232f63b814077cae59c81c03d Mon Sep 17 00:00:00 2001 From: Avasam Date: Fri, 22 Sep 2023 10:24:33 -0400 Subject: [PATCH 10/22] Update Python2 string module usage (#2127) --- Pythonwin/pywin/framework/bitmap.py | 6 +++--- Pythonwin/pywin/idle/PyParse.py | 2 -- com/help/active_directory.html | 4 ++-- com/help/adsi.html | 6 +++--- com/win32com/makegw/makegwenum.py | 3 +-- com/win32com/test/testDCOM.py | 5 ++--- com/win32comext/adsi/demos/test.py | 9 ++++----- com/win32comext/axdebug/debugger.py | 7 +++---- com/win32comext/axdebug/expressions.py | 5 ++--- .../axscript/demos/client/ie/calc.htm | 4 ++-- com/win32comext/axscript/server/axsite.py | 2 +- win32/help/event.d | 18 ++++++++---------- win32/help/security_directories.html | 11 +++++------ win32/scripts/VersionStamp/BrandProject.py | 3 +-- win32/scripts/VersionStamp/vssutil.py | 9 ++++----- win32/scripts/ce/pysynch.py | 10 ++++------ 16 files changed, 45 insertions(+), 59 deletions(-) diff --git a/Pythonwin/pywin/framework/bitmap.py b/Pythonwin/pywin/framework/bitmap.py index 1ec4d50f48..0099fbe590 100644 --- a/Pythonwin/pywin/framework/bitmap.py +++ b/Pythonwin/pywin/framework/bitmap.py @@ -144,9 +144,9 @@ def MatchDocType(self, fileName, fileType): # magic=file.readline() # if magic <> "P6\n": # raise TypeError, "The file is not a PPM format file" -# rowcollist=string.split(file.readline()) -# cols=string.atoi(rowcollist[0]) -# rows=string.atoi(rowcollist[1]) +# rowcollist=file.readline().split() +# cols=int(rowcollist[0]) +# rows=int(rowcollist[1]) # file.readline() # whats this one? # self.bitmap.LoadPPMFile(file,(cols,rows)) diff --git a/Pythonwin/pywin/idle/PyParse.py b/Pythonwin/pywin/idle/PyParse.py index b11b4744e9..fa34ff5896 100644 --- a/Pythonwin/pywin/idle/PyParse.py +++ b/Pythonwin/pywin/idle/PyParse.py @@ -1,5 +1,4 @@ import re -import string import sys # Reason last stmt is continued (or C_NONE if it's not). @@ -362,7 +361,6 @@ def get_continuation_type(self): # if continuation is C_BRACKET, index of last open bracket def _study2(self): - _ws = string.whitespace if self.study_level >= 2: return self._study1() diff --git a/com/help/active_directory.html b/com/help/active_directory.html index a7309642a9..d7764002ba 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',string.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:',string.join(ex_stores,"',") + print '\tExchange stores:',"',".join(ex_stores)

Making the object

diff --git a/com/help/adsi.html b/com/help/adsi.html index 77415bc1d9..6fd2ab119e 100644 --- a/com/help/adsi.html +++ b/com/help/adsi.html @@ -228,11 +228,11 @@

Recursively listing all unique members of a distribution dsobj = ldap.OpenDSObject(path,logon_ex,password,0) dsobj.Getinfo() if dsobj.Class=='organizationalPerson': - user_dict[string.capitalize(dsobj.cn)]=dsobj.uid + user_dict[dsobj.cn.capitalize()]=dsobj.uid elif dsobj.Class=='groupOfNames': for i in dsobj.Members(): if i.Class=='organizationalPerson': - user_dict[string.capitalize(i.cn)]=i.uid + user_dict[i.cn.capitalize()]=i.uid elif type(i.member)==types.TupleType: for j in i.member: newpath='LDAP://'+server+'/'+j @@ -241,7 +241,7 @@

Recursively listing all unique members of a distribution newpath='LDAP://'+server+'/'+i.member getmembers(newpath) elif dsobj.Class=='Remote-Address': - User_dict[string.capitalize(dsobj.cn)]=dsobj.uid + User_dict[dsobj.cn.capitalize()]=dsobj.uid elif dsobj.Class=='Public-Folder': pass else: diff --git a/com/win32com/makegw/makegwenum.py b/com/win32com/makegw/makegwenum.py index 39c9b2d190..90acc613a2 100644 --- a/com/win32com/makegw/makegwenum.py +++ b/com/win32com/makegw/makegwenum.py @@ -11,11 +11,10 @@ # INTERNAL FUNCTIONS # # -import string def is_interface_enum(enumtype): - return not (enumtype[0] in string.uppercase and enumtype[2] in string.uppercase) + return not (enumtype[0].isupper() and enumtype[2].isupper()) def _write_enumifc_cpp(f, interface): diff --git a/com/win32com/test/testDCOM.py b/com/win32com/test/testDCOM.py index 9f5a334e14..9dedf5d101 100644 --- a/com/win32com/test/testDCOM.py +++ b/com/win32com/test/testDCOM.py @@ -12,7 +12,6 @@ The Python.Interpreter object must be installed on the local machine, but no special DCOM configuration should be necessary. """ -import string import sys # NOTE: If you configured the object locally using dcomcnfg, you could @@ -23,7 +22,7 @@ def test(serverName): - if string.lower(serverName) == string.lower(win32api.GetComputerName()): + if serverName.lower() == win32api.GetComputerName().lower(): print("You must specify a remote server name, not the local machine!") return @@ -34,7 +33,7 @@ def test(serverName): ob = win32com.client.DispatchEx("Python.Interpreter", serverName, clsctx=clsctx) ob.Exec("import win32api") actualName = ob.Eval("win32api.GetComputerName()") - if string.lower(serverName) != string.lower(actualName): + if serverName.lower() != actualName.lower(): print( "Error: The object created on server '%s' reported its name as '%s'" % (serverName, actualName) diff --git a/com/win32comext/adsi/demos/test.py b/com/win32comext/adsi/demos/test.py index d5b8fde98e..b0e15f5c64 100644 --- a/com/win32comext/adsi/demos/test.py +++ b/com/win32comext/adsi/demos/test.py @@ -1,4 +1,3 @@ -import string import sys import pythoncom @@ -31,12 +30,12 @@ def DumpRoot(): # Reading attributeSchema and classSchema Objects def _DumpClass(child): attrs = "Abstract lDAPDisplayName schemaIDGUID schemaNamingContext attributeSyntax oMSyntax" - _DumpTheseAttributes(child, string.split(attrs)) + _DumpTheseAttributes(child, attrs.split()) def _DumpAttribute(child): attrs = "lDAPDisplayName schemaIDGUID adminDescription adminDisplayName rDNAttID defaultHidingValue defaultObjectCategory systemOnly defaultSecurityDescriptor" - _DumpTheseAttributes(child, string.split(attrs)) + _DumpTheseAttributes(child, attrs.split()) def _DumpTheseAttributes(child, attrs): @@ -144,7 +143,7 @@ def DumpSchema2(): schema = ADsGetObject(path, IID_IADsContainer) nclass = nprop = nsyntax = 0 for item in schema: - item_class = string.lower(item.Class) + item_class = item.Class.lower() if item_class == "class": items = [] if item.Abstract: @@ -152,7 +151,7 @@ def DumpSchema2(): if item.Auxiliary: items.append("Auxiliary") # if item.Structural: items.append("Structural") - desc = string.join(items, ", ") + desc = ", ".join(items) import win32com.util iid_name = win32com.util.IIDToInterfaceName(item.PrimaryInterface) diff --git a/com/win32comext/axdebug/debugger.py b/com/win32comext/axdebug/debugger.py index 3157586bce..2630e9188d 100644 --- a/com/win32comext/axdebug/debugger.py +++ b/com/win32comext/axdebug/debugger.py @@ -1,5 +1,4 @@ import os -import string import sys import pythoncom @@ -46,7 +45,7 @@ def BuildModule(module, built_nodes, rootNode, create_node_fn, create_node_args) keep = module.__name__ keep = keep and (built_nodes.get(module) is None) if keep and hasattr(module, "__file__"): - keep = string.lower(os.path.splitext(module.__file__)[1]) not in [ + keep = os.path.splitext(module.__file__)[1].lower() not in [ ".pyd", ".dll", ] @@ -59,10 +58,10 @@ def BuildModule(module, built_nodes, rootNode, create_node_fn, create_node_args) node.realNode = realNode # Split into parent nodes. - parts = string.split(module.__name__, ".") + parts = module.__name__.split(".") if parts[-1][:8] == "__init__": parts = parts[:-1] - parent = string.join(parts[:-1], ".") + parent = ".".join(parts[:-1]) parentNode = rootNode if parent: parentModule = sys.modules[parent] diff --git a/com/win32comext/axdebug/expressions.py b/com/win32comext/axdebug/expressions.py index e573eb514e..67bf148e77 100644 --- a/com/win32comext/axdebug/expressions.py +++ b/com/win32comext/axdebug/expressions.py @@ -1,5 +1,4 @@ import io -import string import sys import traceback from pprint import pprint @@ -15,7 +14,7 @@ def MakeNiceString(ob): stream = io.StringIO() pprint(ob, stream) - return string.strip(stream.getvalue()) + return stream.getvalue().strip() class ProvideExpressionContexts(gateways.ProvideExpressionContexts): @@ -65,7 +64,7 @@ def Start(self, callback): sys.exc_info()[0], sys.exc_info()[1] ) # l is a list of strings with trailing "\n" - self.result = string.join((s[:-1] for s in l), "\n") + self.result = "\n".join(s[:-1] for s in l) self.hresult = winerror.E_FAIL finally: self.isComplete = 1 diff --git a/com/win32comext/axscript/demos/client/ie/calc.htm b/com/win32comext/axscript/demos/client/ie/calc.htm index 7c7fb48d40..46ef9a41fe 100644 --- a/com/win32comext/axscript/demos/client/ie/calc.htm +++ b/com/win32comext/axscript/demos/client/ie/calc.htm @@ -48,7 +48,7 @@ PendingOp = NullOp else: FlagNewNum = 1 - Accum = PendingOp( Accum, string.atof(ReadOut) ) + Accum = PendingOp( Accum, float(ReadOut) ) ax.document.Keypad.ReadOut.Value = str(Accum) PendingOp = fn @@ -65,7 +65,7 @@ ClearEntry_OnClick() def Neg_OnClick(): - ax.document.Keypad.ReadOut.Value = str(-string.atof(ax.document.Keypad.ReadOut.Value)) + ax.document.Keypad.ReadOut.Value = str(-float(ax.document.Keypad.ReadOut.Value)) diff --git a/com/win32comext/axscript/server/axsite.py b/com/win32comext/axscript/server/axsite.py index 8f0dd33b17..29fa0ebe93 100644 --- a/com/win32comext/axscript/server/axsite.py +++ b/com/win32comext/axscript/server/axsite.py @@ -76,7 +76,7 @@ def __init__(self, objModel={}, engine=None, lcid=0): self.lcid = lcid self.objModel = {} for name, object in objModel.items(): - # Gregs code did string.lower this - I think that is callers job if he wants! + # Gregs code did str.lower this - I think that is callers job if he wants! self.objModel[name] = object self.engine = None diff --git a/win32/help/event.d b/win32/help/event.d index 1110bb5271..baf4c349af 100644 --- a/win32/help/event.d +++ b/win32/help/event.d @@ -64,8 +64,8 @@ def date2sec(self,evt_date): reg_result=regexp.search(evt_date) date=reg_result.group(1) the_time=reg_result.group(2) - (mon,day,yr)=map(lambda x: string.atoi(x),string.split(date,'/')) - (hr,min,sec)=map(lambda x: string.atoi(x),string.split(the_time,':')) + (mon,day,yr)=map(lambda x: int(x),date.split('/')) + (hr,min,sec)=map(lambda x: int(x),the_time.split(':')) tup=[yr,mon,day,hr,min,sec,0,0,0] sec=time.mktime(tup) return sec @@ -86,7 +86,6 @@ import win32con import winerror import time import re -import string import sys import traceback @@ -99,8 +98,8 @@ def date2sec(evt_date): reg_result=regexp.search(evt_date) date=reg_result.group(1) the_time=reg_result.group(2) - (mon,day,yr)=map(lambda x: string.atoi(x),string.split(date,'/')) - (hr,min,sec)=map(lambda x: string.atoi(x),string.split(the_time,':')) + (mon,day,yr)=map(lambda x: int(x),date.split('/')) + (hr,min,sec)=map(lambda x: int(x),the_time.split(':')) tup=[yr,mon,day,hr,min,sec,0,0,0] sec=time.mktime(tup) @@ -146,7 +145,7 @@ try: evt_id=str(winerror.HRESULT_CODE(ev_obj.EventID)) evt_type=str(evt_dict[ev_obj.EventType]) msg = str(win32evtlogutil.SafeFormatMessage(ev_obj, logtype)) - print string.join((the_time,computer,src,cat,record,evt_id,evt_type,msg[0:15]),':') + print(':'.join((the_time,computer,src,cat,record,evt_id,evt_type,msg[0:15]))) if seconds < begin_sec-28800: break #get out of while loop as well win32evtlog.CloseEventLog(hand) @@ -275,7 +274,6 @@ import win32con import winerror import time import re -import string import sys import threading import traceback @@ -323,7 +321,7 @@ class thread_it ( threading.Thread ) : evt_id=str(winerror.HRESULT_CODE(ev_obj.EventID)) evt_type=str(evt_dict[ev_obj.EventType]) msg = str(win32evtlogutil.SafeFormatMessage(ev_obj, logtype)) - results=string.join((now_time,the_time,computer,src,cat,record,evt_id,evt_type,msg[0:15]),':') + results=':'.join((now_time,the_time,computer,src,cat,record,evt_id,evt_type,msg[0:15])) self.data.append(results) if seconds < begin_sec-28800: break win32evtlog.CloseEventLog(hand) @@ -340,8 +338,8 @@ class thread_it ( threading.Thread ) : date=reg_result.group(1) the_time=reg_result.group(2) - (mon,day,yr)=map(lambda x: string.atoi(x),string.split(date,'/')) - (hr,min,sec)=map(lambda x: string.atoi(x),string.split(the_time,':')) + (mon,day,yr)=map(lambda x: int(x),date.split('/')) + (hr,min,sec)=map(lambda x: int(x),the_time.split(':')) tup=[yr,mon,day,hr,min,sec,0,0,0] sec=time.mktime(tup) diff --git a/win32/help/security_directories.html b/win32/help/security_directories.html index 194698e7e3..dcdfa95167 100644 --- a/win32/help/security_directories.html +++ b/win32/help/security_directories.html @@ -323,7 +323,6 @@

Python code

import os import sys import win32net -import string import time import copy import getopt @@ -383,7 +382,7 @@

Python code

#get the server for the domain -- it has to be a primary dc group=0 resume=0 - sys_id=string.strip(sys_id) + sys_id=sys_id.strip() if D_group.has_key(sys_id): group=1 elif D_except.has_key(sys_id): @@ -405,7 +404,7 @@

Python code

def get_perm_base(file): all_perms=fileperm.get_perms(file) for (domain_id,mask) in all_perms.items(): - (domain,sys_id)=string.split(domain_id,'\\',1) + (domain,sys_id)=domain_id.split('\\',1) mask_name=get_mask(mask) Results.append(file+','+sys_id+','+mask_name) @@ -414,7 +413,7 @@

Python code

perm_list.append(file) all_perms=fileperm.get_perms(file) for (domain_id,mask) in all_perms.items(): - (domain,sys_id)=string.split(domain_id,'\\',1) + (domain,sys_id)=domain_id.split('\\',1) print domain,sys_id sys_id=str(sys_id) mask_name=get_mask(mask) @@ -435,8 +434,8 @@

Python code

continue all_perms=fileperm.get_perms(file) for (domain_id,mask) in all_perms.items(): - if string.find(domain_id,'\\')!=-1: - (domain,sys_id)=string.split(domain_id,'\\',1) + if domain_id.find('\\')!=-1: + (domain,sys_id)=domain_id.split('\\',1) else: sys_id=domain_id mask_name=get_mask(mask) diff --git a/win32/scripts/VersionStamp/BrandProject.py b/win32/scripts/VersionStamp/BrandProject.py index 6a0cf1716f..cfa9ca0c99 100644 --- a/win32/scripts/VersionStamp/BrandProject.py +++ b/win32/scripts/VersionStamp/BrandProject.py @@ -4,7 +4,6 @@ # stamp DLL/EXE files with version information. import os -import string import sys import bulkstamp @@ -77,7 +76,7 @@ def usage(msg): if opt == "-a": bAuto = 1 if opt == "-f": - infile, outfile = string.split(val, "=", 2) + infile, outfile = val.split("=", 2) stampFiles.append((infile, outfile)) if opt == "-d": desc = val diff --git a/win32/scripts/VersionStamp/vssutil.py b/win32/scripts/VersionStamp/vssutil.py index 6679ebc930..23be6278d4 100644 --- a/win32/scripts/VersionStamp/vssutil.py +++ b/win32/scripts/VersionStamp/vssutil.py @@ -1,4 +1,3 @@ -import string import time import traceback @@ -37,7 +36,7 @@ def test(projectName): def SubstituteInString(inString, evalEnv): substChar = "$" - fields = string.split(inString, substChar) + fields = inString.split(substChar) newFields = [] for i in range(len(fields)): didSubst = 0 @@ -52,7 +51,7 @@ def SubstituteInString(inString, evalEnv): print("Could not substitute", strVal) if not didSubst: newFields.append(strVal) - return string.join(map(str, newFields), "") + return "".join(map(str, newFields)) def SubstituteInFile(inName, outName, evalEnv): @@ -102,7 +101,7 @@ def VssLog(project, linePrefix="", noLabels=5, maxItems=150): ) if labelNum > noLabels: break - return string.join(lines, "\n") + return "\n".join(lines) def SubstituteVSSInFile(projectName, inName, outName): @@ -171,7 +170,7 @@ def MakeNewBuildNo(project, buildDesc=None, auto=0, bRebrand=0): oldBuild = "" else: try: - buildNo = string.atoi(buildNo) + buildNo = int(buildNo) if not bRebrand: buildNo = buildNo + 1 buildNo = str(buildNo) diff --git a/win32/scripts/ce/pysynch.py b/win32/scripts/ce/pysynch.py index c3054f0e2e..3244ae45dc 100644 --- a/win32/scripts/ce/pysynch.py +++ b/win32/scripts/ce/pysynch.py @@ -3,7 +3,6 @@ import fnmatch import getopt import os -import string import sys import win32api @@ -62,7 +61,6 @@ def CopyFileToCe(src_name, dest_name, progress=None): if progress is not None: progress(bytes) finally: - pass dh.Close() finally: sh.Close() @@ -144,9 +142,9 @@ def copy(args): src = args[:-1] dest = args[-1] # See if WCE: leading anywhere indicates a direction. - if string.find(src[0], "WCE:") == 0: + if src[0].find("WCE:") == 0: bToDevice = 0 - elif string.find(dest, "WCE:") == 0: + elif dest.find("WCE:") == 0: bToDevice = 1 else: # Assume copy to device. @@ -224,7 +222,7 @@ def run(args): prog_args.append('"' + arg + '"') else: prog_args.append(arg) - prog_args = string.join(prog_args, " ") + prog_args = " ".join(prog_args) wincerapi.CeCreateProcess(prog_args, "", None, None, 0, 0, None, "", None) @@ -247,7 +245,7 @@ def DumpCommands(): if isinstance(item, Callable): doc = getattr(item, "__doc__", "") if doc: - lines = string.split(doc, "\n") + lines = doc.split("\n") print("%-10s - %s" % (name, lines[0])) for line in lines[1:]: if line: From 378fcb738563e8b67522a809c98882528420e6bd Mon Sep 17 00:00:00 2001 From: Avasam Date: Wed, 1 Nov 2023 10:41:27 -0400 Subject: [PATCH 11/22] Replace `distutils.FileList` with `pathlib` (#2138) --- setup.py | 35 ++++++++++++++++------------------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/setup.py b/setup.py index 7309fc1199..89faf52458 100644 --- a/setup.py +++ b/setup.py @@ -43,7 +43,10 @@ from distutils.command.install_data import install_data from distutils.command.install_lib import install_lib from distutils.core import Extension +from pathlib import Path from tempfile import gettempdir +from typing import Iterable, List, Tuple, Union + # some modules need a static CRT to avoid problems caused by them having a # manifest. @@ -52,7 +55,6 @@ import distutils.util from distutils.dep_util import newer_group -from distutils.filelist import FileList build_id_patch = build_id if not "." in build_id_patch: @@ -2122,12 +2124,9 @@ def finalize_options(self): swig_include_files = "mapilib adsilib".split() -# Helper to allow our script specifications to include wildcards. -def expand_modules(module_dir): - flist = FileList() - flist.findall(module_dir) - flist.include_pattern("*.py", anchor=0) - return [os.path.splitext(name)[0] for name in flist.files] +def expand_modules(module_dir: Union[str, os.PathLike]): + """Helper to allow our script specifications to include wildcards.""" + return [str(path.with_suffix("")) for path in Path(module_dir).rglob("*.py")] # NOTE: somewhat counter-intuitively, a result list a-la: @@ -2135,28 +2134,26 @@ def expand_modules(module_dir): # will 'do the right thing' in terms of installing licence.txt into # 'Lib/site-packages/pythonwin/licence.txt'. We exploit this to # get 'com/win32com/whatever' installed to 'win32com/whatever' -def convert_data_files(files): - ret = [] +def convert_data_files(files: Iterable[str]): + ret: List[Tuple[str, Tuple[str]]] = [] for file in files: file = os.path.normpath(file) if file.find("*") >= 0: - flist = FileList() - flist.findall(os.path.dirname(file)) - flist.include_pattern(os.path.basename(file), anchor=0) - # We never want CVS - flist.exclude_pattern(re.compile(r".*\\CVS\\"), is_regex=1, anchor=0) - flist.exclude_pattern("*.pyc", anchor=0) - flist.exclude_pattern("*.pyo", anchor=0) - if not flist.files: + files_use = ( + str(path) + for path in Path(file).parent.rglob(os.path.basename(file)) + # We never want CVS + if not ("\\CVS\\" in file or path.suffix in {".pyc", ".pyo"}) + ) + if not files_use: raise RuntimeError("No files match '%s'" % file) - files_use = flist.files else: if not os.path.isfile(file): raise RuntimeError("No file '%s'" % file) files_use = (file,) for fname in files_use: path_use = os.path.dirname(fname) - if path_use.startswith("com/") or path_use.startswith("com\\"): + if path_use.startswith("com\\"): path_use = path_use[4:] ret.append((path_use, (fname,))) return ret From d1317324e52466192905128f26ffa5c40e4c36e4 Mon Sep 17 00:00:00 2001 From: Avasam Date: Wed, 1 Nov 2023 13:12:55 -0400 Subject: [PATCH 12/22] Prefer f-strings and non-printf-style format (#2122) --- .github/workflows/download-arm64-libs.py | 6 +- AutoDuck/BuildHHP.py | 8 +- AutoDuck/Dump2HHC.py | 85 +- AutoDuck/InsertExternalOverviews.py | 6 +- AutoDuck/TOCToHHK.py | 9 +- AutoDuck/document_object.py | 2 +- AutoDuck/makedfromi.py | 11 +- AutoDuck/py2d.py | 28 +- Pythonwin/pywin/Demos/app/basictimerapp.py | 2 +- Pythonwin/pywin/Demos/guidemo.py | 10 +- Pythonwin/pywin/Demos/ocx/webbrowser.py | 2 +- Pythonwin/pywin/debugger/dbgpyapp.py | 2 +- Pythonwin/pywin/debugger/debugger.py | 2 +- Pythonwin/pywin/framework/app.py | 11 +- .../pywin/framework/editor/ModuleBrowser.py | 4 +- Pythonwin/pywin/framework/editor/document.py | 10 +- Pythonwin/pywin/framework/editor/vss.py | 4 +- Pythonwin/pywin/framework/interact.py | 7 +- Pythonwin/pywin/framework/intpyapp.py | 17 +- Pythonwin/pywin/framework/mdi_pychecker.py | 4 +- Pythonwin/pywin/framework/scriptutils.py | 12 +- Pythonwin/pywin/framework/sgrepmdi.py | 2 +- Pythonwin/pywin/idle/CallTips.py | 3 +- Pythonwin/pywin/idle/PyParse.py | 2 +- Pythonwin/pywin/scintilla/IDLEenvironment.py | 17 +- Pythonwin/pywin/scintilla/bindings.py | 2 +- Pythonwin/pywin/scintilla/config.py | 8 +- Pythonwin/pywin/scintilla/control.py | 5 +- Pythonwin/pywin/scintilla/keycodes.py | 2 +- Pythonwin/pywin/scintilla/view.py | 12 +- Pythonwin/pywin/test/test_exe.py | 10 +- Pythonwin/pywin/test/test_pywin.py | 2 +- Pythonwin/pywin/tools/browseProjects.py | 4 +- Pythonwin/pywin/tools/browser.py | 2 +- Pythonwin/pywin/tools/hierlist.py | 7 +- Pythonwin/pywin/tools/regedit.py | 4 +- com/win32com/client/__init__.py | 30 +- com/win32com/client/build.py | 24 +- com/win32com/client/combrowse.py | 6 +- com/win32com/client/dynamic.py | 29 +- com/win32com/client/gencache.py | 18 +- com/win32com/client/genpy.py | 70 +- com/win32com/client/makepy.py | 12 +- com/win32com/client/selecttlb.py | 4 +- com/win32com/client/tlbrowse.py | 2 +- com/win32com/demos/connect.py | 2 +- com/win32com/makegw/makegw.py | 206 ++--- com/win32com/makegw/makegwenum.py | 260 +++--- com/win32com/makegw/makegwparse.py | 158 ++-- com/win32com/server/dispatcher.py | 10 +- com/win32com/server/exception.py | 2 +- com/win32com/server/policy.py | 9 +- com/win32com/server/register.py | 13 +- com/win32com/test/GenTestScripts.py | 2 +- com/win32com/test/daodump.py | 7 +- com/win32com/test/errorSemantics.py | 4 +- com/win32com/test/pippo_server.py | 6 +- com/win32com/test/testAXScript.py | 2 +- com/win32com/test/testCollections.py | 23 +- com/win32com/test/testDCOM.py | 5 +- com/win32com/test/testDictionary.py | 5 +- com/win32com/test/testDynamic.py | 5 +- com/win32com/test/testExchange.py | 2 +- com/win32com/test/testGatewayAddresses.py | 2 +- com/win32com/test/testPyComTest.py | 23 +- com/win32com/test/testStorage.py | 2 +- com/win32com/test/testall.py | 8 +- com/win32com/test/testmakepy.py | 2 +- com/win32com/test/testvb.py | 55 +- com/win32com/test/testxslt.py | 4 +- com/win32com/test/util.py | 14 +- com/win32com/universal.py | 11 +- com/win32comext/adsi/demos/scp.py | 4 +- com/win32comext/adsi/demos/search.py | 4 +- com/win32comext/adsi/demos/test.py | 37 +- com/win32comext/axdebug/Test/host.py | 5 +- com/win32comext/axdebug/adb.py | 5 +- com/win32comext/axdebug/dump.py | 4 +- com/win32comext/axdebug/util.py | 4 +- com/win32comext/axscript/client/error.py | 4 +- com/win32comext/axscript/client/framework.py | 5 +- com/win32comext/axscript/client/pyscript.py | 2 +- com/win32comext/axscript/test/testHost.py | 11 +- com/win32comext/axscript/test/testHost4Dbg.py | 2 +- com/win32comext/bits/test/test_bits.py | 2 +- com/win32comext/ifilter/demo/filterDemo.py | 6 +- com/win32comext/mapi/mapiutil.py | 5 +- .../shell/demos/ITransferAdviseSink.py | 6 +- .../shell/demos/servers/empty_volume_cache.py | 4 +- .../shell/demos/servers/folder_view.py | 9 +- isapi/install.py | 48 +- isapi/samples/advanced.py | 2 +- isapi/samples/redirector.py | 2 +- isapi/samples/redirector_asynch.py | 2 +- isapi/samples/redirector_with_filter.py | 8 +- isapi/test/extension_simple.py | 4 +- isapi/threaded_extension.py | 5 +- pywin32_postinstall.py | 48 +- pywin32_testall.py | 2 +- setup.py | 751 +++++++++--------- win32/Demos/EvtFormatMessage.py | 10 +- win32/Demos/SystemParametersInfo.py | 2 +- win32/Demos/cerapi.py | 15 +- win32/Demos/dde/ddeclient.py | 2 +- win32/Demos/eventLogDemo.py | 9 +- win32/Demos/getfilever.py | 2 +- win32/Demos/rastest.py | 2 +- win32/Demos/security/localized_names.py | 4 +- win32/Demos/security/sspi/fetch_url.py | 12 +- .../Demos/security/sspi/validate_password.py | 2 +- win32/Demos/service/serviceEvents.py | 6 +- win32/Demos/win32clipboardDemo.py | 26 +- win32/Demos/win32comport_demo.py | 2 +- win32/Demos/win32gui_dialog.py | 2 +- win32/Demos/win32netdemo.py | 12 +- win32/Demos/win32rcparser_demo.py | 2 +- win32/Demos/win32wnet/testwnet.py | 10 +- win32/Lib/netbios.py | 2 +- win32/Lib/pywin32_testutil.py | 2 +- win32/Lib/pywintypes.py | 6 +- win32/Lib/sspi.py | 4 +- win32/Lib/win32evtlogutil.py | 8 +- win32/Lib/win32rcparser.py | 17 +- win32/Lib/win32serviceutil.py | 6 +- win32/Lib/win32timezone.py | 2 +- win32/Lib/win32verstamp.py | 2 +- win32/scripts/VersionStamp/BrandProject.py | 7 +- win32/scripts/VersionStamp/vssutil.py | 11 +- win32/scripts/backupEventLog.py | 4 +- win32/scripts/killProcName.py | 2 +- win32/scripts/regsetup.py | 8 +- win32/scripts/setup_d.py | 25 +- win32/test/test_odbc.py | 11 +- win32/test/test_pywintypes.py | 2 +- win32/test/test_sspi.py | 2 +- win32/test/test_win32api.py | 14 +- win32/test/test_win32file.py | 4 +- win32/test/test_win32guistruct.py | 2 +- win32/test/test_win32pipe.py | 2 +- win32/test/test_win32trace.py | 5 +- win32/test/test_win32wnet.py | 6 +- win32/test/testall.py | 4 +- 142 files changed, 1305 insertions(+), 1325 deletions(-) diff --git a/.github/workflows/download-arm64-libs.py b/.github/workflows/download-arm64-libs.py index 63e48971ab..21b23cc79a 100644 --- a/.github/workflows/download-arm64-libs.py +++ b/.github/workflows/download-arm64-libs.py @@ -21,11 +21,11 @@ VERSION = "{}.{}.{}".format(*sys.version_info[:3]) if sys.version_info.releaselevel == "alpha": - VERSION += "-a{}".format(sys.version_info.serial) + VERSION += f"-a{sys.version_info.serial}" if sys.version_info.releaselevel == "beta": - VERSION += "-b{}".format(sys.version_info.serial) + VERSION += f"-b{sys.version_info.serial}" if sys.version_info.releaselevel == "candidate": - VERSION += "-rc{}".format(sys.version_info.serial) + VERSION += f"-rc{sys.version_info.serial}" URL = f"https://www.nuget.org/api/v2/package/pythonarm64/{VERSION}" PATH = dest / f"pythonarm64.{VERSION}.zip" diff --git a/AutoDuck/BuildHHP.py b/AutoDuck/BuildHHP.py index aa1f4119f0..52662d8f4a 100644 --- a/AutoDuck/BuildHHP.py +++ b/AutoDuck/BuildHHP.py @@ -40,7 +40,7 @@ def handle_globs(lGlobs): for g in lGlobs: new = glob.glob(g) if len(new) == 0: - print("The pattern '%s' yielded no files!" % (g,)) + print(f"The pattern '{g}' yielded no files!") lFiles = lFiles + new # lFiles is now the list of origin files. # Normalize all of the paths: @@ -111,12 +111,12 @@ def main(): shutil.copyfile(lSrcFiles[i], file) for file in lDestFiles: - html_files = html_files + "%s\\%s\n" % (html_dir, file) + html_files = html_files + f"{html_dir}\\{file}\n" for cat in doc: - html_files = html_files + "%s\\%s.html\n" % (output_dir, cat.id) + html_files = html_files + f"{output_dir}\\{cat.id}.html\n" for suffix in "_overview _modules _objects _constants".split(): - html_files = html_files + "%s\\%s%s.html\n" % (output_dir, cat.id, suffix) + html_files = html_files + f"{output_dir}\\{cat.id}{suffix}.html\n" f.write(sHHPFormat % {"output": output, "target": target, "html_files": html_files}) f.close() diff --git a/AutoDuck/Dump2HHC.py b/AutoDuck/Dump2HHC.py index d6071d31b4..42790a9d81 100644 --- a/AutoDuck/Dump2HHC.py +++ b/AutoDuck/Dump2HHC.py @@ -153,19 +153,16 @@ def parseTopics(cat, input): elif top.type == "const": d = cat.constants else: - raise RuntimeError("What is '%s'" % (top.type,)) + raise RuntimeError(f"What is '{top.type}'") if top.name in d: - print("Duplicate named %s detected: %s" % (top.type, top.name)) + print(f"Duplicate named {top.type} detected: {top.name}") # Skip the property fields line for module/object line = input.readline() line = line[:-1] fields = line.split("\t") - assert len(fields[0]) == 0 and len(fields[1]) == 0, "%s, %s" % ( - fields, - top.name, - ) + assert len(fields[0]) == 0 and len(fields[1]) == 0, f"{fields}, {top.name}" if line == "": raise ValueError("incomplete topic!") @@ -197,16 +194,10 @@ def parseTopics(cat, input): assert len(fields[0]) == 0 and len(fields[1]) == 0, fields if top2.type == "pymeth": top2.name = fields[2] - top2.context = "%s__%s_meth.html" % ( - _urlescape(top.name), - top2.name, - ) + top2.context = f"{_urlescape(top.name)}__{top2.name}_meth.html" elif top2.type == "prop": top2.name = fields[3] - top2.context = "%s__%s_prop.html" % ( - _urlescape(top.name), - top2.name, - ) + top2.context = f"{_urlescape(top.name)}__{top2.name}_prop.html" else: # and loop.... line = input.readline() @@ -244,7 +235,7 @@ def _genCategoryHTMLFromDict(dict, output): keys.sort() for key in keys: topic = dict[key] - output.write('
  • %s\n' % (topic.context, topic.name)) + output.write(f'
  • {topic.name}\n') def _genOneCategoryHTML(output_dir, cat, title, suffix, *dicts): @@ -271,7 +262,7 @@ def _genCategoryTopic(output_dir, cat, title): ("Modules", "_modules"), ("Objects", "_objects"), ): - output.write('
  • %s\n' % (cat.id, suffix, subtitle)) + output.write(f'
  • {subtitle}\n') output.write("\n") output.close() @@ -302,12 +293,13 @@ def _genItemsFromDict(dict, cat, output, target, do_children=1): output.write( """
  • - + - + - """ - % locals() + """.format( + **locals() + ) ) if not do_children: continue @@ -317,13 +309,12 @@ def _genItemsFromDict(dict, cat, output, target, do_children=1): containees.sort(key=TopicKey) for m in containees: output.write( - """ + f"""
  • - + - + """ - % (m.name, CHM, m.context) ) if len(dict[k].contains) > 0: output.write( @@ -347,13 +338,14 @@ def genTOC(cats, output, title, target):
    • - + - +
        -""" - % locals() +""".format( + **locals() + ) ) for cat in cats: @@ -362,13 +354,14 @@ def genTOC(cats, output, title, target): output.write( """\
      • - + - +
          - """ - % locals() + """.format( + **locals() + ) ) # Next write the overviews for this category output.write( @@ -376,11 +369,12 @@ def genTOC(cats, output, title, target):
        • - +
            - """ - % locals() + """.format( + **locals() + ) ) _genItemsFromDict(cat.overviewTopics, cat, output, target) _genItemsFromDict(cat.extOverviewTopics, cat, output, target) @@ -394,11 +388,12 @@ def genTOC(cats, output, title, target):
          • - +
              -""" - % locals() +""".format( + **locals() + ) ) _genItemsFromDict(cat.modules, cat, output, target) output.write( @@ -411,10 +406,11 @@ def genTOC(cats, output, title, target):
            • - + -
                """ - % locals() +
                  """.format( + **locals() + ) ) # Dont show 'children' for objects - params etc don't need their own child nodes! _genItemsFromDict(cat.objects, cat, output, target, do_children=0) @@ -428,11 +424,12 @@ def genTOC(cats, output, title, target):
                • - +
                    -""" - % locals() +""".format( + **locals() + ) ) _genItemsFromDict(cat.constants, cat, output, target) output.write( diff --git a/AutoDuck/InsertExternalOverviews.py b/AutoDuck/InsertExternalOverviews.py index c94ddef443..ea7c2c7228 100644 --- a/AutoDuck/InsertExternalOverviews.py +++ b/AutoDuck/InsertExternalOverviews.py @@ -25,21 +25,21 @@ def processFile(input, out, extLinksHTML, extTopicHTML, importantHTML): def genHTML(doc): s = "" for cat in doc: - s = s + "

                    %s

                    \n" % (cat.label,) + s = s + f"

                    {cat.label}

                    \n" dict = {} for item in cat.overviewItems.items: dict[item.name] = item.href keys = list(dict.keys()) keys.sort() for k in keys: - s = s + '
                  • %s\n' % (dict[k], k) + s = s + f'
                  • {k}\n' return s def genLinksHTML(links): s = "" for link in links: - s = s + '
                  • %s\n' % (link.href, link.name) + s = s + f'
                  • {link.name}\n' return s diff --git a/AutoDuck/TOCToHHK.py b/AutoDuck/TOCToHHK.py index 235b786772..edeb8457e3 100644 --- a/AutoDuck/TOCToHHK.py +++ b/AutoDuck/TOCToHHK.py @@ -37,13 +37,12 @@ def main(): if " " in context: context = context.replace(" ", "_") out.write( - """
                  • - - - + f"""
                  • + + + """ - % (keyword, fields[1], context) ) line = input.readline() out.write( diff --git a/AutoDuck/document_object.py b/AutoDuck/document_object.py index e610a788eb..3755fdf46f 100644 --- a/AutoDuck/document_object.py +++ b/AutoDuck/document_object.py @@ -15,7 +15,7 @@ def startElement(self, name, attrs): category = self.document.categories[-1] assert ( category.overviewItems is None - ), "category %r already has overviews" % (category,) + ), f"category {category!r} already has overviews" category.overviewItems = OverviewItems(attrs) elif name == "item": item = Item(attrs) diff --git a/AutoDuck/makedfromi.py b/AutoDuck/makedfromi.py index 678a422e87..b83c51e201 100644 --- a/AutoDuck/makedfromi.py +++ b/AutoDuck/makedfromi.py @@ -117,19 +117,18 @@ def make_doc_summary(inFile, outFile): print("**Error - %s does not have enough fields" % meth) else: outFile.write( - "// @pymethod %s|%s|%s|%s\n" - % (fields[0], thisModName, fields[1], fields[2]) + f"// @pymethod {fields[0]}|{thisModName}|{fields[1]}|{fields[2]}\n" ) for extra in extras: outFile.write(extra) if g_com_parent: - outFile.write("\n// @object %s|%s" % (thisModName, modDoc)) + outFile.write(f"\n// @object {thisModName}|{modDoc}") outFile.write("\n// Derived from \n" % (g_com_parent)) else: - outFile.write("\n// @module %s|%s\n" % (thisModName, modDoc)) + outFile.write(f"\n// @module {thisModName}|{modDoc}\n") for meth, extras in these_methods: fields = meth.split("|") - outFile.write("// @pymeth %s|%s\n" % (fields[1], fields[2])) + outFile.write(f"// @pymeth {fields[1]}|{fields[2]}\n") chunk_number += 1 method_num += max_methods @@ -137,7 +136,7 @@ def make_doc_summary(inFile, outFile): for extra in extra_tags: outFile.write("%s\n" % (extra)) for cname, doc in constants: - outFile.write("// @const %s|%s|%s\n" % (modName, cname, doc)) + outFile.write(f"// @const {modName}|{cname}|{doc}\n") def doit(): diff --git a/AutoDuck/py2d.py b/AutoDuck/py2d.py index 7dda5d8d25..6a0452bf72 100644 --- a/AutoDuck/py2d.py +++ b/AutoDuck/py2d.py @@ -112,32 +112,30 @@ def build_module(fp, mod_name): elif name.upper() == name and isinstance(ob, (int, str)): constants.append((name, ob)) info = BuildInfo(mod_name, mod) - Print("// @module %s|%s" % (mod_name, format_desc(info.desc)), file=fp) + Print(f"// @module {mod_name}|{format_desc(info.desc)}", file=fp) functions = [f for f in functions if should_build_function(f)] for ob in functions: - Print("// @pymeth %s|%s" % (ob.name, ob.short_desc), file=fp) + Print(f"// @pymeth {ob.name}|{ob.short_desc}", file=fp) for ob in classes: # only classes with docstrings get printed. if not ob.ob.__doc__: continue ob_name = mod_name + "." + ob.name - Print("// @pyclass %s|%s" % (ob.name, ob.short_desc), file=fp) + Print(f"// @pyclass {ob.name}|{ob.short_desc}", file=fp) for ob in functions: Print( - "// @pymethod |%s|%s|%s" % (mod_name, ob.name, format_desc(ob.desc)), + f"// @pymethod |{mod_name}|{ob.name}|{format_desc(ob.desc)}", file=fp, ) for ai in BuildArgInfos(ob.ob): - Print( - "// @pyparm |%s|%s|%s" % (ai.name, ai.default, ai.short_desc), file=fp - ) + Print(f"// @pyparm |{ai.name}|{ai.default}|{ai.short_desc}", file=fp) for ob in classes: # only classes with docstrings get printed. if not ob.ob.__doc__: continue ob_name = mod_name + "." + ob.name - Print("// @object %s|%s" % (ob_name, format_desc(ob.desc)), file=fp) + Print(f"// @object {ob_name}|{format_desc(ob.desc)}", file=fp) func_infos = [] # We need to iter the keys then to a getattr() so the funky descriptor # things work. @@ -148,29 +146,29 @@ def build_module(fp, mod_name): if should_build_function(info): func_infos.append(info) for fi in func_infos: - Print("// @pymeth %s|%s" % (fi.name, fi.short_desc), file=fp) + Print(f"// @pymeth {fi.name}|{fi.short_desc}", file=fp) for fi in func_infos: Print( - "// @pymethod |%s|%s|%s" % (ob_name, fi.name, format_desc(fi.desc)), + f"// @pymethod |{ob_name}|{fi.name}|{format_desc(fi.desc)}", file=fp, ) if hasattr(fi.ob, "im_self") and fi.ob.im_self is ob.ob: Print("// @comm This is a @classmethod.", file=fp) Print( - "// @pymethod |%s|%s|%s" % (ob_name, fi.name, format_desc(fi.desc)), + f"// @pymethod |{ob_name}|{fi.name}|{format_desc(fi.desc)}", file=fp, ) for ai in BuildArgInfos(fi.ob): Print( - "// @pyparm |%s|%s|%s" % (ai.name, ai.default, ai.short_desc), + f"// @pyparm |{ai.name}|{ai.default}|{ai.short_desc}", file=fp, ) for name, val in constants: - desc = "%s = %r" % (name, val) + desc = f"{name} = {val!r}" if isinstance(val, int): - desc += " (0x%x)" % (val,) - Print("// @const %s|%s|%s" % (mod_name, name, desc), file=fp) + desc += f" (0x{val:x})" + Print(f"// @const {mod_name}|{name}|{desc}", file=fp) def main(fp, args): diff --git a/Pythonwin/pywin/Demos/app/basictimerapp.py b/Pythonwin/pywin/Demos/app/basictimerapp.py index afc9e8dc73..af2f95490b 100644 --- a/Pythonwin/pywin/Demos/app/basictimerapp.py +++ b/Pythonwin/pywin/Demos/app/basictimerapp.py @@ -129,7 +129,7 @@ def OnTimer(self, id, timeVal): print("The last operation completed successfully.") except: t, v, tb = sys.exc_info() - str = "Failed: %s: %s" % (t, repr(v)) + str = f"Failed: {t}: {repr(v)}" print(str) self.oldErr.write(str) tb = None # Prevent cycle diff --git a/Pythonwin/pywin/Demos/guidemo.py b/Pythonwin/pywin/Demos/guidemo.py index b4d88159a0..95b1dbbc91 100644 --- a/Pythonwin/pywin/Demos/guidemo.py +++ b/Pythonwin/pywin/Demos/guidemo.py @@ -56,10 +56,7 @@ def demo(): try: exec(cmd) except: - print( - "Demo of %s failed - %s:%s" - % (cmd, sys.exc_info()[0], sys.exc_info()[1]) - ) + print(f"Demo of {cmd} failed - {sys.exc_info()[0]}:{sys.exc_info()[1]}") return # Otherwise allow the user to select the demo to run @@ -73,10 +70,7 @@ def demo(): try: exec(cmd) except: - print( - "Demo of %s failed - %s:%s" - % (title, sys.exc_info()[0], sys.exc_info()[1]) - ) + print(f"Demo of {title} failed - {sys.exc_info()[0]}:{sys.exc_info()[1]}") if __name__ == __main__.__name__: diff --git a/Pythonwin/pywin/Demos/ocx/webbrowser.py b/Pythonwin/pywin/Demos/ocx/webbrowser.py index cc17445e9a..914b84a555 100644 --- a/Pythonwin/pywin/Demos/ocx/webbrowser.py +++ b/Pythonwin/pywin/Demos/ocx/webbrowser.py @@ -57,7 +57,7 @@ def OnSize(self, params): self.ocx.SetWindowPos(0, rect, 0) def OnNavigate(self, url): - title = "Web Browser - %s" % (url,) + title = f"Web Browser - {url}" self.SetWindowText(title) diff --git a/Pythonwin/pywin/debugger/dbgpyapp.py b/Pythonwin/pywin/debugger/dbgpyapp.py index 207f404938..284460e87e 100644 --- a/Pythonwin/pywin/debugger/dbgpyapp.py +++ b/Pythonwin/pywin/debugger/dbgpyapp.py @@ -25,7 +25,7 @@ def LoadMainFrame(self): def InitInstance(self): # Use a registry path of "Python\Pythonwin Debugger win32ui.SetAppName(win32ui.LoadString(win32ui.IDR_DEBUGGER)) - win32ui.SetRegistryKey("Python %s" % (sys.winver,)) + win32ui.SetRegistryKey(f"Python {sys.winver}") # We _need_ the Scintilla color editor. # (and we _always_ get it now :-) diff --git a/Pythonwin/pywin/debugger/debugger.py b/Pythonwin/pywin/debugger/debugger.py index 320e34ddf5..d063f06d57 100644 --- a/Pythonwin/pywin/debugger/debugger.py +++ b/Pythonwin/pywin/debugger/debugger.py @@ -411,7 +411,7 @@ def RespondDebuggerData(self): cond = bp.cond item = index + 1, 0, 0, 0, str(cond), 0, id(bp) index = l.InsertItem(item) - l.SetItemText(index, 1, "%s: %s" % (baseName, bp.line)) + l.SetItemText(index, 1, f"{baseName}: {bp.line}") class DebuggerWatchWindow(DebuggerListViewWindow): diff --git a/Pythonwin/pywin/framework/app.py b/Pythonwin/pywin/framework/app.py index 409a10c3e9..9793aa1307 100644 --- a/Pythonwin/pywin/framework/app.py +++ b/Pythonwin/pywin/framework/app.py @@ -234,9 +234,7 @@ def OnHelp(self, id, code): help.OpenHelpFile(helpFile, helpCmd) except: t, v, tb = sys.exc_info() - win32ui.MessageBox( - "Internal error in help file processing\r\n%s: %s" % (t, v) - ) + win32ui.MessageBox(f"Internal error in help file processing\r\n{t}: {v}") tb = None # Prevent a cycle def DoLoadModules(self, modules): @@ -364,9 +362,8 @@ def __init__(self, idd=win32ui.IDD_ABOUTBOX): dialog.Dialog.__init__(self, idd) def OnInitDialog(self): - text = ( - "Pythonwin - Python IDE and GUI Framework for Windows.\n\n%s\n\nPython is %s\n\n%s\n\n%s\n\n%s" - % (win32ui.copyright, sys.copyright, scintilla, idle, contributors) + text = "Pythonwin - Python IDE and GUI Framework for Windows.\n\n{}\n\nPython is {}\n\n{}\n\n{}\n\n{}".format( + win32ui.copyright, sys.copyright, scintilla, idle, contributors ) self.SetDlgItemText(win32ui.IDC_EDIT1, text) # Get the build number - written by installers. @@ -387,7 +384,7 @@ def OnInitDialog(self): "SOFTWARE\\ActiveState\\ActivePython", "CurrentVersion" ) if ver is not None: - ver = "ActivePython build %s" % (ver,) + ver = f"ActivePython build {ver}" if ver is None: ver = "" self.SetDlgItemText(win32ui.IDC_ABOUT_VERSION, ver) diff --git a/Pythonwin/pywin/framework/editor/ModuleBrowser.py b/Pythonwin/pywin/framework/editor/ModuleBrowser.py index 7fd965327d..d1437e6a40 100644 --- a/Pythonwin/pywin/framework/editor/ModuleBrowser.py +++ b/Pythonwin/pywin/framework/editor/ModuleBrowser.py @@ -61,7 +61,7 @@ def TakeDefaultAction(self): def PerformItemSelected(self): if self.file is None: - msg = "%s - source can not be located." % (self.name,) + msg = f"{self.name} - source can not be located." else: msg = "%s defined at line %d of %s" % (self.name, self.lineno, self.file) win32ui.SetStatusText(msg) @@ -170,7 +170,7 @@ def _MakeRoot(self): pass else: what = "Building" - win32ui.SetStatusText("%s class list - please wait..." % (what,), 1) + win32ui.SetStatusText(f"{what} class list - please wait...", 1) win32ui.DoWaitCursor(1) try: reader = pyclbr.readmodule_ex # new version post 1.5.2 diff --git a/Pythonwin/pywin/framework/editor/document.py b/Pythonwin/pywin/framework/editor/document.py index 1e74e86a2b..ec27bccc66 100644 --- a/Pythonwin/pywin/framework/editor/document.py +++ b/Pythonwin/pywin/framework/editor/document.py @@ -158,15 +158,17 @@ def CheckExternalDocumentUpdated(self): except OSError as exc: if not self.bReportedFileNotFound: print( - "The file '%s' is open for editing, but\nchecking it for changes caused the error: %s" - % (self.GetPathName(), exc.strerror) + "The file '{}' is open for editing, but\nchecking it for changes caused the error: {}".format( + self.GetPathName(), exc.strerror + ) ) self.bReportedFileNotFound = 1 return if self.bReportedFileNotFound: print( - "The file '%s' has re-appeared - continuing to watch for changes..." - % (self.GetPathName(),) + "The file '{}' has re-appeared - continuing to watch for changes...".format( + self.GetPathName() + ) ) self.bReportedFileNotFound = ( 0 # Once found again we want to start complaining. diff --git a/Pythonwin/pywin/framework/editor/vss.py b/Pythonwin/pywin/framework/editor/vss.py index 718f83eea4..4a772acef2 100644 --- a/Pythonwin/pywin/framework/editor/vss.py +++ b/Pythonwin/pywin/framework/editor/vss.py @@ -91,7 +91,7 @@ def CheckoutFile(fileName): if not database: database = pythoncom.Missing g_sourceSafe.Open(database, pythoncom.Missing, pythoncom.Missing) - item = g_sourceSafe.VSSItem("$/%s/%s" % (project, vssFname)) + item = g_sourceSafe.VSSItem(f"$/{project}/{vssFname}") item.Checkout(None, fileName) ok = 1 except pythoncom.com_error as exc: @@ -99,6 +99,6 @@ def CheckoutFile(fileName): except: typ, val, tb = sys.exc_info() traceback.print_exc() - win32ui.MessageBox("%s - %s" % (str(typ), str(val)), "Error checking out file") + win32ui.MessageBox(f"{str(typ)} - {str(val)}", "Error checking out file") tb = None # Cleanup a cycle return ok diff --git a/Pythonwin/pywin/framework/interact.py b/Pythonwin/pywin/framework/interact.py index ed3a7e0820..7c5d07a60e 100644 --- a/Pythonwin/pywin/framework/interact.py +++ b/Pythonwin/pywin/framework/interact.py @@ -325,11 +325,12 @@ def Init(self): if win32ui.debug: suffix = ", debug build" sys.stderr.write( - "PythonWin %s on %s%s.\n" % (sys.version, sys.platform, suffix) + f"PythonWin {sys.version} on {sys.platform}{suffix}.\n" ) sys.stderr.write( - "Portions %s - see 'Help/About PythonWin' for further copyright information.\n" - % (win32ui.copyright,) + "Portions {} - see 'Help/About PythonWin' for further copyright information.\n".format( + win32ui.copyright + ) ) else: sys.stderr.write(banner) diff --git a/Pythonwin/pywin/framework/intpyapp.py b/Pythonwin/pywin/framework/intpyapp.py index 48461dbab0..e70e7c09f0 100644 --- a/Pythonwin/pywin/framework/intpyapp.py +++ b/Pythonwin/pywin/framework/intpyapp.py @@ -205,7 +205,7 @@ def InitInstance(self): self.ddeServer = None win32ui.SetRegistryKey( - "Python %s" % (sys.winver,) + f"Python {sys.winver}" ) # MFC automatically puts the main frame caption on! app.CApp.InitInstance(self) @@ -317,8 +317,9 @@ def ProcessArgs(self, args, dde=None): # pywin.scintilla.document.CScintillaDocument.OnOpenDocument) # segfaults Pythonwin on recent PY3 builds (b228) win32ui.MessageBox( - "No such file: %s\n\nCommand Line: %s" - % (fname, win32api.GetCommandLine()), + "No such file: {}\n\nCommand Line: {}".format( + fname, win32api.GetCommandLine() + ), "Open file for edit", win32con.MB_ICONERROR, ) @@ -330,8 +331,9 @@ def ProcessArgs(self, args, dde=None): elif argType == "/rundlg": if dde: dde.Exec( - "from pywin.framework import scriptutils;scriptutils.RunScript(%r, %r, 1)" - % (par, " ".join(args[i + 1 :])) + "from pywin.framework import scriptutils;scriptutils.RunScript({!r}, {!r}, 1)".format( + par, " ".join(args[i + 1 :]) + ) ) else: from . import scriptutils @@ -341,8 +343,9 @@ def ProcessArgs(self, args, dde=None): elif argType == "/run": if dde: dde.Exec( - "from pywin.framework import scriptutils;scriptutils.RunScript(%r, %r, 0)" - % (par, " ".join(args[i + 1 :])) + "from pywin.framework import scriptutils;scriptutils.RunScript({!r}, {!r}, 0)".format( + par, " ".join(args[i + 1 :]) + ) ) else: from . import scriptutils diff --git a/Pythonwin/pywin/framework/mdi_pychecker.py b/Pythonwin/pywin/framework/mdi_pychecker.py index 06fbcc82b0..de43f349bc 100644 --- a/Pythonwin/pywin/framework/mdi_pychecker.py +++ b/Pythonwin/pywin/framework/mdi_pychecker.py @@ -284,7 +284,7 @@ def OnNewDocument(self): def doSearch(self): self.dp = dirpath(self.dirpattern, self.recurse) self.SetTitle( - "Pychecker Run '%s' (options: %s)" % (self.filpattern, self.greppattern) + f"Pychecker Run '{self.filpattern}' (options: {self.greppattern})" ) # self.text = [] self.GetFirstView().Append( @@ -367,7 +367,7 @@ def threadPycheckerRun(self): "(or run 'setup.py install' if you have the source version)\n" ) else: - cmd = '%s "%s" %s %s 2>&1' % (py, pychecker, options, files) + cmd = f'{py} "{pychecker}" {options} {files} 2>&1' ##fin,fout,ferr=os.popen3(cmd) ##result=ferr.read()+fout.read() result = os.popen(cmd).read() diff --git a/Pythonwin/pywin/framework/scriptutils.py b/Pythonwin/pywin/framework/scriptutils.py index c6e8e32440..5fb6702f16 100644 --- a/Pythonwin/pywin/framework/scriptutils.py +++ b/Pythonwin/pywin/framework/scriptutils.py @@ -93,9 +93,7 @@ def IsOnPythonPath(path): if syspath and win32ui.FullPath(syspath) == path: return 1 except win32ui.error as details: - print( - "Warning: The sys.path entry '%s' is invalid\n%s" % (syspath, details) - ) + print(f"Warning: The sys.path entry '{syspath}' is invalid\n{details}") return 0 @@ -398,7 +396,7 @@ def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None): sys.path[0] = oldPath0 f.close() if bWorked: - win32ui.SetStatusText("Script '%s' returned exit code %s" % (script, exitCode)) + win32ui.SetStatusText(f"Script '{script}' returned exit code {exitCode}") else: win32ui.SetStatusText("Exception raised while running script %s" % base) try: @@ -506,7 +504,7 @@ def CheckFile(): try: f = open(pathName) except OSError as details: - print("Cant open file '%s' - %s" % (pathName, details)) + print(f"Cant open file '{pathName}' - {details}") return try: code = f.read() + "\n" @@ -641,9 +639,7 @@ def FindTabNanny(): try: os.stat(fname) except OSError: - print( - "WARNING - The file '%s' can not be located in path '%s'" % (filename, path) - ) + print(f"WARNING - The file '{filename}' can not be located in path '{path}'") return None tabnannyhome, tabnannybase = os.path.split(fname) diff --git a/Pythonwin/pywin/framework/sgrepmdi.py b/Pythonwin/pywin/framework/sgrepmdi.py index 16bff7fa8a..1c0d6339c4 100644 --- a/Pythonwin/pywin/framework/sgrepmdi.py +++ b/Pythonwin/pywin/framework/sgrepmdi.py @@ -264,7 +264,7 @@ def OnNewDocument(self): def doSearch(self): self.dp = dirpath(self.dirpattern, self.recurse) - self.SetTitle("Grep for %s in %s" % (self.greppattern, self.filpattern)) + self.SetTitle(f"Grep for {self.greppattern} in {self.filpattern}") # self.text = [] self.GetFirstView().Append("#Search " + self.dirpattern + "\n") if self.verbose: diff --git a/Pythonwin/pywin/idle/CallTips.py b/Pythonwin/pywin/idle/CallTips.py index cecc760a14..810d8c8818 100644 --- a/Pythonwin/pywin/idle/CallTips.py +++ b/Pythonwin/pywin/idle/CallTips.py @@ -208,8 +208,7 @@ def test(tests): if get_arg_text(t) != expected: failed.append(t) print( - "%s - expected %s, but got %s" - % (t, repr(expected), repr(get_arg_text(t))) + f"{t} - expected {repr(expected)}, but got {repr(get_arg_text(t))}" ) print("%d of %d tests failed" % (len(failed), len(tests))) diff --git a/Pythonwin/pywin/idle/PyParse.py b/Pythonwin/pywin/idle/PyParse.py index fa34ff5896..8a994254e4 100644 --- a/Pythonwin/pywin/idle/PyParse.py +++ b/Pythonwin/pywin/idle/PyParse.py @@ -130,7 +130,7 @@ def __init__(self, indentwidth, tabwidth): self.tabwidth = tabwidth def set_str(self, str): - assert len(str) == 0 or str[-1] == "\n", "Oops - have str %r" % (str,) + assert len(str) == 0 or str[-1] == "\n", f"Oops - have str {str!r}" self.str = str self.study_level = 0 diff --git a/Pythonwin/pywin/scintilla/IDLEenvironment.py b/Pythonwin/pywin/scintilla/IDLEenvironment.py index b1db509316..f60f19de36 100644 --- a/Pythonwin/pywin/scintilla/IDLEenvironment.py +++ b/Pythonwin/pywin/scintilla/IDLEenvironment.py @@ -28,9 +28,9 @@ def GetIDLEModule(module): __import__(modname) except ImportError as details: msg = ( - "The IDLE extension '%s' can not be located.\r\n\r\n" + f"The IDLE extension '{module}' can not be located.\r\n\r\n" "Please correct the installation and restart the" - " application.\r\n\r\n%s" % (module, details) + f" application.\r\n\r\n{details}" ) win32ui.MessageBox(msg) return None @@ -99,7 +99,7 @@ def IDLEExtension(self, extension): # Find and bind all the events defined in the extension. events = [item for item in dir(klass) if item[-6:] == "_event"] for event in events: - name = "<<%s>>" % (event[:-6].replace("_", "-"),) + name = "<<{}>>".format(event[:-6].replace("_", "-")) self.edit.bindings.bind(name, getattr(ext, event)) return ext @@ -133,11 +133,9 @@ def askinteger( except ValueError: err = "Please enter an integer" if not err and minvalue is not None and rc < minvalue: - err = "Please enter an integer greater then or equal to %s" % ( - minvalue, - ) + err = f"Please enter an integer greater then or equal to {minvalue}" if not err and maxvalue is not None and rc > maxvalue: - err = "Please enter an integer less then or equal to %s" % (maxvalue,) + err = f"Please enter an integer less then or equal to {maxvalue}" if err: win32ui.MessageBox(err, caption, win32con.MB_OK) continue @@ -519,8 +517,9 @@ def TestGet(fr, to, t, expected): got = t.get(fr, to) if got != expected: print( - "ERROR: get(%s, %s) expected %s, but got %s" - % (repr(fr), repr(to), repr(expected), repr(got)) + "ERROR: get({}, {}) expected {}, but got {}".format( + repr(fr), repr(to), repr(expected), repr(got) + ) ) diff --git a/Pythonwin/pywin/scintilla/bindings.py b/Pythonwin/pywin/scintilla/bindings.py index 785bd42a13..44644bdfc8 100644 --- a/Pythonwin/pywin/scintilla/bindings.py +++ b/Pythonwin/pywin/scintilla/bindings.py @@ -106,7 +106,7 @@ def _get_IDLE_handler(self, ext, handler): name = handler.replace("-", "_") + "_event" return getattr(instance, name) except (ImportError, AttributeError): - msg = "Can not find event '%s' in IDLE extension '%s'" % (handler, ext) + msg = f"Can not find event '{handler}' in IDLE extension '{ext}'" self.report_error(msg) return None diff --git a/Pythonwin/pywin/scintilla/config.py b/Pythonwin/pywin/scintilla/config.py index 1dc4b38034..f6916a7331 100644 --- a/Pythonwin/pywin/scintilla/config.py +++ b/Pythonwin/pywin/scintilla/config.py @@ -148,7 +148,7 @@ def __init__(self, f): line, lineno = self._load_general(subsection, fp, lineno) else: self.report_error( - "Unrecognised section header '%s:%s'" % (section, subsection) + f"Unrecognised section header '{section}:{subsection}'" ) line = fp.readline() lineno = lineno + 1 @@ -243,10 +243,10 @@ def get_key_binding(self, event, subsections=None): def report_error(self, msg): self.last_error = msg - print("Error in %s: %s" % (self.filename, msg)) + print(f"Error in {self.filename}: {msg}") def report_warning(self, msg): - print("Warning in %s: %s" % (self.filename, msg)) + print(f"Warning in {self.filename}: {msg}") def _readline(self, fp, lineno, bStripComments=1): line = fp.readline() @@ -358,7 +358,7 @@ def test(): cm = ConfigManager(f) map = cm.get_data("keys") took = time.clock() - start - print("Loaded %s items in %.4f secs" % (len(map), took)) + print(f"Loaded {len(map)} items in {took:.4f} secs") if __name__ == "__main__": diff --git a/Pythonwin/pywin/scintilla/control.py b/Pythonwin/pywin/scintilla/control.py index 9923489b8a..5430e65d35 100644 --- a/Pythonwin/pywin/scintilla/control.py +++ b/Pythonwin/pywin/scintilla/control.py @@ -455,10 +455,7 @@ def LineFromChar(self, charPos=-1): charPos = self.GetSel()[0] assert ( charPos >= 0 and charPos <= self.GetTextLength() - ), "The charPos postion (%s) is invalid (max=%s)" % ( - charPos, - self.GetTextLength(), - ) + ), f"The charPos postion ({charPos}) is invalid (max={self.GetTextLength()})" # return self.SendScintilla(EM_EXLINEFROMCHAR, charPos) # EM_EXLINEFROMCHAR puts charPos in lParam, not wParam return self.SendScintilla(EM_EXLINEFROMCHAR, 0, charPos) diff --git a/Pythonwin/pywin/scintilla/keycodes.py b/Pythonwin/pywin/scintilla/keycodes.py index badcef3e70..fa896991a2 100644 --- a/Pythonwin/pywin/scintilla/keycodes.py +++ b/Pythonwin/pywin/scintilla/keycodes.py @@ -156,7 +156,7 @@ def test1(): def _pkn(n): vk, flags = parse_key_name(n) - print("%s -> %s,%s -> %s" % (n, vk, flags, make_key_name(vk, flags))) + print(f"{n} -> {vk},{flags} -> {make_key_name(vk, flags)}") def test2(): diff --git a/Pythonwin/pywin/scintilla/view.py b/Pythonwin/pywin/scintilla/view.py index 910161bad4..305c9904d3 100644 --- a/Pythonwin/pywin/scintilla/view.py +++ b/Pythonwin/pywin/scintilla/view.py @@ -332,8 +332,9 @@ def AppendMenu(self, menu, text="", event=None, flags=None, checked=0): if cmdid is None: # No event of that name - no point displaying it. print( - 'View.AppendMenu(): Unknown event "%s" specified for menu text "%s" - ignored' - % (event, text) + 'View.AppendMenu(): Unknown event "{}" specified for menu text "{}" - ignored'.format( + event, text + ) ) return keyname = configManager.get_key_binding(event, self._GetSubConfigNames()) @@ -509,8 +510,9 @@ def list2dict(l): pass except: win32ui.SetStatusText( - "Error attempting to get object attributes - %s" - % (repr(sys.exc_info()[0]),) + "Error attempting to get object attributes - {}".format( + repr(sys.exc_info()[0]) + ) ) # ensure all keys are strings. @@ -811,7 +813,7 @@ def LoadConfiguration(): configManager = ConfigManager(configName) if configManager.last_error: bTryDefault = 0 - msg = "Error loading configuration '%s'\n\n%s" % ( + msg = "Error loading configuration '{}'\n\n{}".format( configName, configManager.last_error, ) diff --git a/Pythonwin/pywin/test/test_exe.py b/Pythonwin/pywin/test/test_exe.py index 0d77ea3327..6e59bc3967 100644 --- a/Pythonwin/pywin/test/test_exe.py +++ b/Pythonwin/pywin/test/test_exe.py @@ -41,17 +41,17 @@ def setUp(self): # XXX Pythonwin.exe / win32uihostglue.h could be improved to search # the Python DLL itself via registry when local / relative search fails. - pydll = "Python%s%s.dll" % sys.version_info[:2] # same for 32bit + pydll = "Python{}{}.dll".format(*sys.version_info[:2]) # same for 32bit src = os.path.dirname(sys.executable) + os.sep + pydll dst = os.path.dirname(pythonwinexe_path) + os.sep + pydll if not os.path.isfile(dst): try: assert os.path.isfile(src) - print("-- symlink %r -> %r" % (dst, src), file=sys.stderr) + print(f"-- symlink {dst!r} -> {src!r}", file=sys.stderr) os.symlink(src, dst) except (OSError, AssertionError) as e: - print("-- cannot make symlink %r: %r" % (dst, e), file=sys.stderr) - print("-- Starting: %r in %r" % (cmd, wd), file=sys.stderr) + print(f"-- cannot make symlink {dst!r}: {e!r}", file=sys.stderr) + print(f"-- Starting: {cmd!r} in {wd!r}", file=sys.stderr) self.p = subprocess.Popen(cmd, cwd=wd) def test_exe(self): @@ -62,7 +62,7 @@ def test_exe(self): rc = "TIMEOUT" with open(self.tfn) as f: outs = f.read() - assert rc == 0, "rc is %r, outs=%r" % (rc, outs) + assert rc == 0, f"rc is {rc!r}, outs={outs!r}" assert "Success!" in outs, outs print("-- test_exe Ok! --", file=sys.stderr) diff --git a/Pythonwin/pywin/test/test_pywin.py b/Pythonwin/pywin/test/test_pywin.py index 02cdcaca8e..14b4430e24 100644 --- a/Pythonwin/pywin/test/test_pywin.py +++ b/Pythonwin/pywin/test/test_pywin.py @@ -88,7 +88,7 @@ def test_1_pydocs_and_finddlg(self): scriptutils.JumpToDocument(__file__) if user_interaction: win32ui.MessageBox( - "Hello from test_pydocs() args=%s %s" % (sys.argv, os.getcwd()) + f"Hello from test_pydocs() args={sys.argv} {os.getcwd()}" ) v = scriptutils.GetActiveEditControl() assert file_abs == v.GetDocument().GetPathName() diff --git a/Pythonwin/pywin/tools/browseProjects.py b/Pythonwin/pywin/tools/browseProjects.py index e3255579a1..1a420b5f18 100644 --- a/Pythonwin/pywin/tools/browseProjects.py +++ b/Pythonwin/pywin/tools/browseProjects.py @@ -52,7 +52,7 @@ def TakeDefaultAction(self): def PerformItemSelected(self): if self.file is None: - msg = "%s - source can not be located." % (self.name,) + msg = f"{self.name} - source can not be located." else: msg = "%s defined at line %d of %s" % (self.name, self.lineno, self.file) win32ui.SetStatusText(msg) @@ -145,7 +145,7 @@ def GetSubList(self): ret.sort() return ret else: - return [HLIErrorItem("No Python classes%s in module." % (extra_msg,))] + return [HLIErrorItem(f"No Python classes{extra_msg} in module.")] finally: win32ui.DoWaitCursor(0) win32ui.SetStatusText(win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE)) diff --git a/Pythonwin/pywin/tools/browser.py b/Pythonwin/pywin/tools/browser.py index 6dfe3a24fa..5422b5fb65 100644 --- a/Pythonwin/pywin/tools/browser.py +++ b/Pythonwin/pywin/tools/browser.py @@ -356,7 +356,7 @@ def OnInitDialog(self): strval = str(self.object) except: t, v, tb = sys.exc_info() - strval = "Exception getting object value\n\n%s:%s" % (t, v) + strval = f"Exception getting object value\n\n{t}:{v}" tb = None strval = re.sub(r"\n", "\r\n", strval) self.edit.ReplaceSel(strval) diff --git a/Pythonwin/pywin/tools/hierlist.py b/Pythonwin/pywin/tools/hierlist.py index 4f27da9a91..a7dd4c72eb 100644 --- a/Pythonwin/pywin/tools/hierlist.py +++ b/Pythonwin/pywin/tools/hierlist.py @@ -97,9 +97,10 @@ def HierInit(self, parent, listControl=None): # Used when window first exists. else: self.listControl = listControl lbid = listControl.GetDlgCtrlID() - assert self.listBoxId is None or self.listBoxId == lbid, ( - "An invalid listbox control ID has been specified (specified as %s, but exists as %s)" - % (self.listBoxId, lbid) + assert ( + self.listBoxId is None or self.listBoxId == lbid + ), "An invalid listbox control ID has been specified (specified as {}, but exists as {})".format( + self.listBoxId, lbid ) self.listBoxId = lbid self.listControl.SetImageList(self.imageList, commctrl.LVSIL_NORMAL) diff --git a/Pythonwin/pywin/tools/regedit.py b/Pythonwin/pywin/tools/regedit.py index b94d3050fb..14e1e43c98 100644 --- a/Pythonwin/pywin/tools/regedit.py +++ b/Pythonwin/pywin/tools/regedit.py @@ -113,7 +113,7 @@ def OnItemRightClick(self, notify_data, extra): def OnDeleteKey(self, command, code): hitem = self.hierList.GetSelectedItem() item = self.hierList.ItemFromHandle(hitem) - msg = "Are you sure you wish to delete the key '%s'?" % (item.keyName,) + msg = f"Are you sure you wish to delete the key '{item.keyName}'?" id = win32ui.MessageBox(msg, None, win32con.MB_YESNO) if id != win32con.IDYES: return @@ -336,7 +336,7 @@ def __eq__(self, other): ) def __repr__(self): - return "<%s with root=%s, key=%s>" % ( + return "<{} with root={}, key={}>".format( self.__class__.__name__, self.keyRoot, self.keyName, diff --git a/com/win32com/client/__init__.py b/com/win32com/client/__init__.py index 6e23e70540..9a74a4defc 100644 --- a/com/win32com/client/__init__.py +++ b/com/win32com/client/__init__.py @@ -179,8 +179,8 @@ def CastTo(ob, target, typelib=None): ) if not hasattr(mod, target): raise ValueError( - "The interface name '%s' does not appear in the " - "specified library %r" % (target, typelib.ver_desc) + f"The interface name '{target}' does not appear in the " + f"specified library {typelib.ver_desc!r}" ) elif hasattr(target, "index"): # string like @@ -207,8 +207,8 @@ def CastTo(ob, target, typelib=None): target_clsid = mod.NamesToIIDMap.get(target) if target_clsid is None: raise ValueError( - "The interface name '%s' does not appear in the " - "same library as object '%r'" % (target, ob) + f"The interface name '{target}' does not appear in the " + f"same library as object '{ob!r}'" ) mod = gencache.GetModuleForCLSID(target_clsid) if mod is not None: @@ -489,9 +489,7 @@ def Record(name, object): try: struct_guid = package.RecordMap[name] except KeyError: - raise ValueError( - "The structure '%s' is not defined in module '%s'" % (name, package) - ) + raise ValueError(f"The structure '{name}' is not defined in module '{package}'") return pythoncom.GetRecordFromGuids( module.CLSID, module.MajorVersion, module.MinorVersion, module.LCID, struct_guid ) @@ -544,11 +542,7 @@ def __repr__(self): mod_name = sys.modules[self.__class__.__module__].__name__ except KeyError: mod_name = "win32com.gen_py.unknown" - return "<%s.%s instance at 0x%s>" % ( - mod_name, - self.__class__.__name__, - id(self), - ) + return f"<{mod_name}.{self.__class__.__name__} instance at 0x{id(self)}>" # Delegate comparison to the oleobjs, as they know how to do identity. def __eq__(self, other): @@ -569,9 +563,7 @@ def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *ar def __getattr__(self, attr): args = self._prop_map_get_.get(attr) if args is None: - raise AttributeError( - "'%s' object has no attribute '%s'" % (repr(self), attr) - ) + raise AttributeError(f"'{repr(self)}' object has no attribute '{attr}'") return self._ApplyTypes_(*args) def __setattr__(self, attr, value): @@ -581,9 +573,7 @@ def __setattr__(self, attr, value): try: args, defArgs = self._prop_map_put_[attr] except KeyError: - raise AttributeError( - "'%s' object has no attribute '%s'" % (repr(self), attr) - ) + raise AttributeError(f"'{repr(self)}' object has no attribute '{attr}'") self._oleobj_.Invoke(*(args + (value,) + defArgs)) def _get_good_single_object_(self, obj, obUserName=None, resultCLSID=None): @@ -629,7 +619,7 @@ def __init__(self, oobj=None): setattr(self, maybe, getattr(self, "__maybe" + maybe)) def __repr__(self): - return "" % (__doc__, self.__class__.__name__) + return f"" def __getattr__(self, attr): d = self.__dict__["_dispobj_"] @@ -701,4 +691,4 @@ def _del_value(self): value = property(_get_value, _set_value, _del_value) def __repr__(self): - return "win32com.client.VARIANT(%r, %r)" % (self.varianttype, self._value) + return f"win32com.client.VARIANT({self.varianttype!r}, {self._value!r})" diff --git a/com/win32com/client/build.py b/com/win32com/client/build.py index 84dacb566a..1035ecdff9 100644 --- a/com/win32com/client/build.py +++ b/com/win32com/client/build.py @@ -427,27 +427,31 @@ def MakeDispatchFuncMethod(self, entry, name, bMakeClass=1): repr(argsDesc), _BuildArgList(fdesc, names), ) - s = s + "%s\tif ret is not None:\n" % (linePrefix,) + s = s + f"{linePrefix}\tif ret is not None:\n" if rd == pythoncom.VT_UNKNOWN: - s = s + "%s\t\t# See if this IUnknown is really an IDispatch\n" % ( - linePrefix, + s = ( + s + + "{}\t\t# See if this IUnknown is really an IDispatch\n".format( + linePrefix, + ) ) - s = s + "%s\t\ttry:\n" % (linePrefix,) + s = s + f"{linePrefix}\t\ttry:\n" s = ( s - + "%s\t\t\tret = ret.QueryInterface(pythoncom.IID_IDispatch)\n" - % (linePrefix,) + + "{}\t\t\tret = ret.QueryInterface(pythoncom.IID_IDispatch)\n".format( + linePrefix + ) ) - s = s + "%s\t\texcept pythoncom.error:\n" % (linePrefix,) - s = s + "%s\t\t\treturn ret\n" % (linePrefix,) - s = s + "%s\t\tret = Dispatch(ret, %s, %s)\n" % ( + s = s + f"{linePrefix}\t\texcept pythoncom.error:\n" + s = s + f"{linePrefix}\t\t\treturn ret\n" + s = s + "{}\t\tret = Dispatch(ret, {}, {})\n".format( linePrefix, repr(name), resclsid, ) s = s + "%s\treturn ret" % (linePrefix) elif rd == pythoncom.VT_BSTR: - s = "%s\t# Result is a Unicode object\n" % (linePrefix,) + s = f"{linePrefix}\t# Result is a Unicode object\n" s = ( s + "%s\treturn self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s)" diff --git a/com/win32com/client/combrowse.py b/com/win32com/client/combrowse.py index 6e1e836240..18576251ee 100644 --- a/com/win32com/client/combrowse.py +++ b/com/win32com/client/combrowse.py @@ -194,7 +194,7 @@ def GetSubList(self): collected = [] helpPath = "" key = win32api.RegOpenKey( - win32con.HKEY_CLASSES_ROOT, "TypeLib\\%s\\%s" % (clsidstr, versionStr) + win32con.HKEY_CLASSES_ROOT, f"TypeLib\\{clsidstr}\\{versionStr}" ) win32ui.DoWaitCursor(1) try: @@ -453,7 +453,7 @@ def MakeReturnTypeName(self, typ): typname = "?Bad type?" for flag, desc in self.type_flags: if flag & typ: - typname = "%s(%s)" % (desc, typname) + typname = f"{desc}({typname})" return typname def MakeReturnType(self, returnTypeDesc): @@ -489,7 +489,7 @@ def GetSubList(self): if flags: val = "%s (Flags=%d)" % (val, flags) if default is not None: - val = "%s (Default=%s)" % (val, default) + val = f"{val} (Default={default})" ret.append(browser.MakeHLI(val, "Argument")) try: diff --git a/com/win32com/client/dynamic.py b/com/win32com/client/dynamic.py index 449ad928fd..dc938e8cbe 100644 --- a/com/win32com/client/dynamic.py +++ b/com/win32com/client/dynamic.py @@ -469,13 +469,13 @@ def _print_details_(self): print("\t", method) print("Props:") for prop, entry in self._olerepr_.propMap.items(): - print("\t%s = 0x%x - %s" % (prop, entry.dispid, repr(entry))) + print(f"\t{prop} = 0x{entry.dispid:x} - {repr(entry)}") print("Get Props:") for prop, entry in self._olerepr_.propMapGet.items(): - print("\t%s = 0x%x - %s" % (prop, entry.dispid, repr(entry))) + print(f"\t{prop} = 0x{entry.dispid:x} - {repr(entry)}") print("Put Props:") for prop, entry in self._olerepr_.propMapPut.items(): - print("\t%s = 0x%x - %s" % (prop, entry.dispid, repr(entry))) + print(f"\t{prop} = 0x{entry.dispid:x} - {repr(entry)}") except: traceback.print_exc() @@ -483,7 +483,7 @@ def __LazyMap__(self, attr): try: if self._LazyAddAttr_(attr): debug_attr_print( - "%s.__LazyMap__(%s) added something" % (self._username_, attr) + f"{self._username_}.__LazyMap__({attr}) added something" ) return 1 except AttributeError: @@ -543,8 +543,9 @@ def _FlagAsMethod(self, *methodNames): def __AttrToID__(self, attr): debug_attr_print( - "Calling GetIDsOfNames for property %s in Dispatch container %s" - % (attr, self._username_) + "Calling GetIDsOfNames for property {} in Dispatch container {}".format( + attr, self._username_ + ) ) return self._oleobj_.GetIDsOfNames(0, attr) @@ -635,7 +636,7 @@ def __call__(self): return self._get_good_object_(ret) # no where else to look. - raise AttributeError("%s.%s" % (self._username_, attr)) + raise AttributeError(f"{self._username_}.{attr}") def __setattr__(self, attr, value): if ( @@ -647,8 +648,9 @@ def __setattr__(self, attr, value): return # Allow property assignment. debug_attr_print( - "SetAttr called for %s.%s=%s on DispatchContainer" - % (self._username_, attr, repr(value)) + "SetAttr called for {}.{}={} on DispatchContainer".format( + self._username_, attr, repr(value) + ) ) if self._olerepr_: @@ -697,12 +699,11 @@ def __setattr__(self, attr, value): self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value) self._olerepr_.propMap[attr] = entry debug_attr_print( - "__setattr__ property %s (id=0x%x) in Dispatch container %s" - % (attr, entry.dispid, self._username_) + "__setattr__ property {} (id=0x{:x}) in Dispatch container {}".format( + attr, entry.dispid, self._username_ + ) ) return except pythoncom.com_error: pass - raise AttributeError( - "Property '%s.%s' can not be set." % (self._username_, attr) - ) + raise AttributeError(f"Property '{self._username_}.{attr}' can not be set.") diff --git a/com/win32com/client/gencache.py b/com/win32com/client/gencache.py index 1d9ca3300d..debe796213 100644 --- a/com/win32com/client/gencache.py +++ b/com/win32com/client/gencache.py @@ -131,7 +131,7 @@ def GetGeneratedFileName(clsid, lcid, major, minor): """Given the clsid, lcid, major and minor for a type lib, return the file name (no extension) providing this support. """ - return str(clsid).upper()[1:-1] + "x%sx%sx%s" % (lcid, major, minor) + return str(clsid).upper()[1:-1] + f"x{lcid}x{major}x{minor}" def SplitGeneratedFileName(fname): @@ -409,8 +409,9 @@ def ForgetAboutTypelibInterface(typelib_ob): except KeyError: # Not worth raising an exception - maybe they dont know we only remember for demand generated, etc. print( - "ForgetAboutTypelibInterface:: Warning - type library with info %s is not being remembered!" - % (info,) + "ForgetAboutTypelibInterface:: Warning - type library with info {} is not being remembered!".format( + info + ) ) # and drop any version redirects to it for key, val in list(versionRedirectMap.items()): @@ -506,7 +507,7 @@ def EnsureModule( bValidateFile = 0 if module is not None and bValidateFile: assert not is_readonly, "Can't validate in a read-only gencache" - filePathPrefix = "%s\\%s" % ( + filePathPrefix = "{}\\{}".format( GetGeneratePath(), GetGeneratedFileName(typelibCLSID, lcid, major, minor), ) @@ -543,7 +544,7 @@ def EnsureModule( bReloadNeeded = 1 else: minor = module.MinorVersion - filePathPrefix = "%s\\%s" % ( + filePathPrefix = "{}\\{}".format( GetGeneratePath(), GetGeneratedFileName(typelibCLSID, lcid, major, minor), ) @@ -741,8 +742,9 @@ def Rebuild(verbose=1): AddModuleToCache(iid, lcid, major, minor, verbose, 0) except: print( - "Could not add module %s - %s: %s" - % (info, sys.exc_info()[0], sys.exc_info()[1]) + "Could not add module {} - {}: {}".format( + info, sys.exc_info()[0], sys.exc_info()[1] + ) ) if verbose and len(infos): # Dont bother reporting this when directory is empty! print("Done.") @@ -757,7 +759,7 @@ def _Dump(): d[typelibCLSID, lcid, major, minor] = None for typelibCLSID, lcid, major, minor in d.keys(): mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor) - print("%s - %s" % (mod.__doc__, typelibCLSID)) + print(f"{mod.__doc__} - {typelibCLSID}") # Boot up diff --git a/com/win32com/client/genpy.py b/com/win32com/client/genpy.py index 96997d3a29..739f3ddd00 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -177,7 +177,7 @@ def WriteAliasItem(self, aliasDict, stream): if isinstance(ai, int): try: typeStr = mapVTToTypeString[ai] - print("# %s=%s" % (self.doc[0], typeStr), file=stream) + print(f"# {self.doc[0]}={typeStr}", file=stream) except KeyError: print( self.doc[0] + " = None # Can't convert alias info " + str(ai), @@ -262,7 +262,7 @@ def WriteVTableMap(self, generator): "%s_vtables_dispatch_ = %d" % (self.python_name, self.bIsDispatch), file=stream, ) - print("%s_vtables_ = [" % (self.python_name,), file=stream) + print(f"{self.python_name}_vtables_ = [", file=stream) for v in self.vtableFuncs: names, dispid, desc = v assert desc.desckind == pythoncom.DESCKIND_FUNCDESC @@ -507,8 +507,7 @@ def WriteClassBody(self, generator): resultName = entry.GetResultName() if resultName: print( - "\t\t# Property '%s' is an object of type '%s'" - % (key, resultName), + f"\t\t# Property '{key}' is an object of type '{resultName}'", file=stream, ) lkey = key.lower() @@ -544,7 +543,7 @@ def WriteClassBody(self, generator): continue print( - '\t\t"%s": %s,' % (build.MakePublicAttributeName(key), mapEntry), + f'\t\t"{build.MakePublicAttributeName(key)}": {mapEntry},', file=stream, ) names = list(self.propMapGet.keys()) @@ -554,8 +553,9 @@ def WriteClassBody(self, generator): if generator.bBuildHidden or not entry.hidden: if entry.GetResultName(): print( - "\t\t# Method '%s' returns object of type '%s'" - % (key, entry.GetResultName()), + "\t\t# Method '{}' returns object of type '{}'".format( + key, entry.GetResultName() + ), file=stream, ) details = entry.desc @@ -590,7 +590,7 @@ def WriteClassBody(self, generator): if details.memid == pythoncom.DISPID_NEWENUM: continue print( - '\t\t"%s": %s,' % (build.MakePublicAttributeName(key), mapEntry), + f'\t\t"{build.MakePublicAttributeName(key)}": {mapEntry},', file=stream, ) @@ -653,7 +653,7 @@ def WriteClassBody(self, generator): % propArgs ] print( - "\t# Default %s for this class is '%s'" % (typename, entry.names[0]), + f"\t# Default {typename} for this class is '{entry.names[0]}'", file=stream, ) for line in ret: @@ -772,12 +772,11 @@ def WriteClass(self, generator): print("import sys", file=stream) for ref in referenced_items: print( - "__import__('%s.%s')" % (generator.base_mod_name, ref.python_name), + f"__import__('{generator.base_mod_name}.{ref.python_name}')", file=stream, ) print( - "%s = sys.modules['%s.%s'].%s" - % ( + "{} = sys.modules['{}.{}'].{}".format( ref.python_name, generator.base_mod_name, ref.python_name, @@ -797,7 +796,7 @@ def WriteClass(self, generator): ) if doc and doc[1]: print("\t# " + doc[1], file=stream) - print("\tCLSID = %r" % (self.clsid,), file=stream) + print(f"\tCLSID = {self.clsid!r}", file=stream) print("\tcoclass_sources = [", file=stream) defItem = None for item, flag in self.sources: @@ -816,7 +815,7 @@ def WriteClass(self, generator): defName = defItem.python_name else: defName = repr(str(defItem.clsid)) # really the iid. - print("\tdefault_source = %s" % (defName,), file=stream) + print(f"\tdefault_source = {defName}", file=stream) print("\tcoclass_interfaces = [", file=stream) defItem = None for item, flag in self.interfaces: @@ -827,14 +826,14 @@ def WriteClass(self, generator): key = item.python_name else: key = repr(str(item.clsid)) # really the iid. - print("\t\t%s," % (key,), file=stream) + print(f"\t\t{key},", file=stream) print("\t]", file=stream) if defItem: if defItem.bWritten: defName = defItem.python_name else: defName = repr(str(defItem.clsid)) # really the iid. - print("\tdefault_interface = %s" % (defName,), file=stream) + print(f"\tdefault_interface = {defName}", file=stream) self.bWritten = 1 print(file=stream) @@ -1100,14 +1099,15 @@ def do_gen_file_header(self): assert self.file.encoding, self.file encoding = self.file.encoding # or "mbcs" - print("# -*- coding: %s -*-" % (encoding,), file=self.file) - print("# Created by makepy.py version %s" % (makepy_version,), file=self.file) + print(f"# -*- coding: {encoding} -*-", file=self.file) + print(f"# Created by makepy.py version {makepy_version}", file=self.file) print( - "# By python version %s" % (sys.version.replace("\n", "-"),), file=self.file + "# By python version {}".format(sys.version.replace("\n", "-")), + file=self.file, ) if self.sourceFilename: print( - "# From type library '%s'" % (os.path.split(self.sourceFilename)[1],), + f"# From type library '{os.path.split(self.sourceFilename)[1]}'", file=self.file, ) print("# On %s" % time.ctime(time.time()), file=self.file) @@ -1115,7 +1115,7 @@ def do_gen_file_header(self): print(build._makeDocString(docDesc), file=self.file) print("makepy_version =", repr(makepy_version), file=self.file) - print("python_version = 0x%x" % (sys.hexversion,), file=self.file) + print(f"python_version = 0x{sys.hexversion:x}", file=self.file) print(file=self.file) print( "import win32com.client.CLSIDToClass, pythoncom, pywintypes", file=self.file @@ -1192,13 +1192,14 @@ def do_generate(self): for record in recordItems.values(): if record.clsid == pythoncom.IID_NULL: print( - "\t###%s: %s, # Record disabled because it doesn't have a non-null GUID" - % (repr(record.doc[0]), repr(str(record.clsid))), + "\t###{}: {}, # Record disabled because it doesn't have a non-null GUID".format( + repr(record.doc[0]), repr(str(record.clsid)) + ), file=stream, ) else: print( - "\t%s: %s," % (repr(record.doc[0]), repr(str(record.clsid))), + f"\t{repr(record.doc[0])}: {repr(str(record.clsid))},", file=stream, ) print("}", file=stream) @@ -1210,7 +1211,7 @@ def do_generate(self): for item in oleItems.values(): if item is not None and item.bWritten: print( - "\t'%s' : %s," % (str(item.clsid), item.python_name), + f"\t'{str(item.clsid)}' : {item.python_name},", file=stream, ) print("}", file=stream) @@ -1222,7 +1223,7 @@ def do_generate(self): print("VTablesToPackageMap = {}", file=stream) print("VTablesToClassMap = {", file=stream) for item in vtableItems.values(): - print("\t'%s' : '%s'," % (item.clsid, item.python_name), file=stream) + print(f"\t'{item.clsid}' : '{item.python_name}',", file=stream) print("}", file=stream) print(file=stream) @@ -1232,14 +1233,14 @@ def do_generate(self): for item in oleItems.values(): if item is not None: print( - "\t'%s' : %s," % (str(item.clsid), repr(item.python_name)), + f"\t'{str(item.clsid)}' : {repr(item.python_name)},", file=stream, ) print("}", file=stream) print("VTablesToClassMap = {}", file=stream) print("VTablesToPackageMap = {", file=stream) for item in vtableItems.values(): - print("\t'%s' : '%s'," % (item.clsid, item.python_name), file=stream) + print(f"\t'{item.clsid}' : '{item.python_name}',", file=stream) print("}", file=stream) print(file=stream) @@ -1254,7 +1255,7 @@ def do_generate(self): print("NamesToIIDMap = {", file=stream) for name, iid in map.items(): - print("\t'%s' : '%s'," % (name, iid), file=stream) + print(f"\t'{name}' : '{iid}',", file=stream) print("}", file=stream) print(file=stream) @@ -1275,7 +1276,7 @@ def generate_child(self, child, dir): major = la[3] minor = la[4] self.base_mod_name = ( - "win32com.gen_py." + str(clsid)[1:-1] + "x%sx%sx%s" % (lcid, major, minor) + "win32com.gen_py." + str(clsid)[1:-1] + f"x{lcid}x{major}x{minor}" ) try: # Process the type library's CoClass objects, looking for the @@ -1327,9 +1328,7 @@ def generate_child(self, child, dir): assert ( found - ), "Cant find the '%s' interface in the CoClasses, or the interfaces" % ( - child, - ) + ), f"Cant find the '{child}' interface in the CoClasses, or the interfaces" # Make a map of iid: dispitem, vtableitem) items = {} for key, value in oleItems.items(): @@ -1375,8 +1374,9 @@ def do_gen_child_item(self, oleitem): oleitem.WriteClass(self) if oleitem.bWritten: print( - 'win32com.client.CLSIDToClass.RegisterCLSID( "%s", %s )' - % (oleitem.clsid, oleitem.python_name), + 'win32com.client.CLSIDToClass.RegisterCLSID( "{}", {} )'.format( + oleitem.clsid, oleitem.python_name + ), file=self.file, ) diff --git a/com/win32com/client/makepy.py b/com/win32com/client/makepy.py index bb1bf4e07a..5bcea6c830 100644 --- a/com/win32com/client/makepy.py +++ b/com/win32com/client/makepy.py @@ -105,14 +105,16 @@ def ShowInfo(spec): desc = tlb.GetDocumentation(-1)[0] print(desc) print( - " %s, lcid=%s, major=%s, minor=%s" - % (tlbSpec.clsid, tlbSpec.lcid, tlbSpec.major, tlbSpec.minor) + " {}, lcid={}, major={}, minor={}".format( + tlbSpec.clsid, tlbSpec.lcid, tlbSpec.major, tlbSpec.minor + ) ) print(" >>> # Use these commands in Python code to auto generate .py support") print(" >>> from win32com.client import gencache") print( - " >>> gencache.EnsureModule('%s', %s, %s, %s)" - % (tlbSpec.clsid, tlbSpec.lcid, tlbSpec.major, tlbSpec.minor) + " >>> gencache.EnsureModule('{}', {}, {}, {})".format( + tlbSpec.clsid, tlbSpec.lcid, tlbSpec.major, tlbSpec.minor + ) ) @@ -228,7 +230,7 @@ def GetTypeLibsForSpec(arg): return typelibs except pythoncom.com_error: t, v, tb = sys.exc_info() - sys.stderr.write("Unable to load type library from '%s' - %s\n" % (arg, v)) + sys.stderr.write(f"Unable to load type library from '{arg}' - {v}\n") tb = None # Storing tb in a local is a cycle! sys.exit(1) diff --git a/com/win32com/client/selecttlb.py b/com/win32com/client/selecttlb.py index 1337bc468b..56197128f5 100644 --- a/com/win32com/client/selecttlb.py +++ b/com/win32com/client/selecttlb.py @@ -132,10 +132,10 @@ def EnumTlbs(excludeFlags=0): continue # Check for both "{lcid}\win32" and "{lcid}\win64" keys. try: - key4 = win32api.RegOpenKey(key3, "%s\\win32" % (lcid,)) + key4 = win32api.RegOpenKey(key3, f"{lcid}\\win32") except win32api.error: try: - key4 = win32api.RegOpenKey(key3, "%s\\win64" % (lcid,)) + key4 = win32api.RegOpenKey(key3, f"{lcid}\\win64") except win32api.error: continue try: diff --git a/com/win32com/client/tlbrowse.py b/com/win32com/client/tlbrowse.py index acc0028167..11673d5aff 100644 --- a/com/win32com/client/tlbrowse.py +++ b/com/win32com/client/tlbrowse.py @@ -155,7 +155,7 @@ def _GetMainInfoTypes(self): typeFlags = attr[11] desc = doc[0] - desc = desc + ", Flags=0x%x, typeKind=0x%x, typeFlags=0x%x" % ( + desc = desc + ", Flags=0x{:x}, typeKind=0x{:x}, typeFlags=0x{:x}".format( flags, typeKind, typeFlags, diff --git a/com/win32com/demos/connect.py b/com/win32com/demos/connect.py index 3099214c94..197d7a6255 100644 --- a/com/win32com/demos/connect.py +++ b/com/win32com/demos/connect.py @@ -63,7 +63,7 @@ def CheckEvent(server, client, val, verbose): client.last_event_arg = None server.DoIt(val) if client.last_event_arg != val: - raise RuntimeError("Sent %r, but got back %r" % (val, client.last_event_arg)) + raise RuntimeError(f"Sent {val!r}, but got back {client.last_event_arg!r}") if verbose: print("Sent and received %r" % val) diff --git a/com/win32com/makegw/makegw.py b/com/win32com/makegw/makegw.py index 6074900d5f..196fce4276 100644 --- a/com/win32com/makegw/makegw.py +++ b/com/win32com/makegw/makegw.py @@ -89,13 +89,12 @@ def make_framework_support( fout = open("Py%s.cpp" % interface.name, "w") try: fout.write( - """\ -// This file implements the %s %s for Python. + f"""\ +// This file implements the {interface.name} {desc} for Python. // Generated by makegw.py #include "shell_pch.h" """ - % (interface.name, desc) ) # if bMakeGateway: # fout.write('#include "PythonCOMServer.h"\n') @@ -114,11 +113,10 @@ def make_framework_support( fout = open("Py%s.h" % interface.name, "w") try: fout.write( - """\ -// This file declares the %s %s for Python. + f"""\ +// This file declares the {interface.name} {desc} for Python. // Generated by makegw.py """ - % (interface.name, desc) ) if bMakeInterface: @@ -138,35 +136,33 @@ def make_framework_support( def _write_ifc_h(f, interface): f.write( - """\ + f"""\ // --------------------------------------------------- // // Interface Declaration -class Py%s : public Py%s -{ +class Py{interface.name} : public Py{interface.base} +{{ public: - MAKE_PYCOM_CTOR(Py%s); - static %s *GetI(PyObject *self); + MAKE_PYCOM_CTOR(Py{interface.name}); + static {interface.name} *GetI(PyObject *self); static PyComTypeObject type; // The Python methods """ - % (interface.name, interface.base, interface.name, interface.name) ) for method in interface.methods: f.write( "\tstatic PyObject *%s(PyObject *self, PyObject *args);\n" % method.name ) f.write( - """\ + f"""\ protected: - Py%s(IUnknown *pdisp); - ~Py%s(); -}; + Py{interface.name}(IUnknown *pdisp); + ~Py{interface.name}(); +}}; """ - % (interface.name, interface.name) ) @@ -178,23 +174,24 @@ def _write_ifc_cpp(f, interface): // // Interface Implementation -Py%(name)s::Py%(name)s(IUnknown *pdisp): - Py%(base)s(pdisp) -{ +Py{name}::Py{name}(IUnknown *pdisp): + Py{base}(pdisp) +{{ ob_type = &type; -} +}} -Py%(name)s::~Py%(name)s() -{ -} +Py{name}::~Py{name}() +{{ +}} -/* static */ %(name)s *Py%(name)s::GetI(PyObject *self) -{ - return (%(name)s *)Py%(base)s::GetI(self); -} +/* static */ {name} *Py{name}::GetI(PyObject *self) +{{ + return ({name} *)Py{base}::GetI(self); +}} -""" - % (interface.__dict__) +""".format( + **interface.__dict__ + ) ) ptr = re.sub(r"[a-z]", "", interface.name) @@ -203,14 +200,15 @@ def _write_ifc_cpp(f, interface): strdict["method"] = method.name f.write( """\ -// @pymethod |Py%(interfacename)s|%(method)s|Description of %(method)s. -PyObject *Py%(interfacename)s::%(method)s(PyObject *self, PyObject *args) -{ - %(interfacename)s *p%(ptr)s = GetI(self); - if ( p%(ptr)s == NULL ) +// @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; -""" - % strdict +""".format( + **strdict + ) ) argsParseTuple = ( argsCOM @@ -243,36 +241,38 @@ def _write_ifc_cpp(f, interface): argsCOM = argsCOM + ", " + comArgName except makegwparse.error_not_supported as why: f.write( - '// *** The input argument %s of type "%s" was not processed ***\n// Please check the conversion function is appropriate and exists!\n' - % (arg.name, arg.raw_type) + '// *** The input argument {} of type "{}" was not processed ***\n// Please check the conversion function is appropriate and exists!\n'.format( + arg.name, arg.raw_type + ) ) + f.write(f"\t{arg.type} {arg.name};\n\tPyObject *ob{arg.name};\n") f.write( - "\t%s %s;\n\tPyObject *ob%s;\n" % (arg.type, arg.name, arg.name) - ) - f.write( - "\t// @pyparm |%s||Description for %s\n" - % (arg.type, arg.name, arg.name) + "\t// @pyparm |{}||Description for {}\n".format( + arg.type, arg.name, arg.name + ) ) codePost = ( codePost - + "\tif (bPythonIsHappy && !PyObject_As%s( ob%s, &%s )) bPythonIsHappy = FALSE;\n" - % (arg.type, arg.name, arg.name) + + "\tif (bPythonIsHappy && !PyObject_As{}( ob{}, &{} )) bPythonIsHappy = FALSE;\n".format( + arg.type, arg.name, arg.name + ) ) formatChars = formatChars + "O" argsParseTuple = argsParseTuple + ", &ob%s" % (arg.name) argsCOM = argsCOM + ", " + arg.name - cleanup = cleanup + "\tPyObject_Free%s(%s);\n" % (arg.type, arg.name) + cleanup = cleanup + f"\tPyObject_Free{arg.type}({arg.name});\n" if needConversion: f.write("\tUSES_CONVERSION;\n") f.write(codePobjects) f.write(codeCobjects) f.write( - '\tif ( !PyArg_ParseTuple(args, "%s:%s"%s) )\n\t\treturn NULL;\n' - % (formatChars, method.name, argsParseTuple) + '\tif ( !PyArg_ParseTuple(args, "{}:{}"{}) )\n\t\treturn NULL;\n'.format( + formatChars, method.name, argsParseTuple + ) ) if codePost: f.write("\tBOOL bPythonIsHappy = TRUE;\n") @@ -284,14 +284,15 @@ def _write_ifc_cpp(f, interface): f.write( """ HRESULT hr; PY_INTERFACE_PRECALL; - hr = p%(ptr)s->%(method)s(%(argsCOM)s ); -%(cleanup)s + hr = p{ptr}->{method}({argsCOM} ); +{cleanup} PY_INTERFACE_POSTCALL; -%(cleanup_gil)s +{cleanup_gil} if ( FAILED(hr) ) - return PyCom_BuildPyException(hr, p%(ptr)s, IID_%(interfacename)s ); -""" - % strdict + return PyCom_BuildPyException(hr, p{ptr}, IID_{interfacename} ); +""".format( + **strdict + ) ) codePre = codePost = formatChars = codeVarsPass = codeDecl = "" for arg in method.args: @@ -308,14 +309,16 @@ def _write_ifc_cpp(f, interface): codeDecl = codeDecl + argCvt.DeclareParseArgTupleInputConverter() except makegwparse.error_not_supported as why: f.write( - '// *** The output argument %s of type "%s" was not processed ***\n// %s\n' - % (arg.name, arg.raw_type, why) + '// *** The output argument {} of type "{}" was not processed ***\n// {}\n'.format( + arg.name, arg.raw_type, why + ) ) continue if formatChars: f.write( - '%s\n%s\tPyObject *pyretval = Py_BuildValue("%s"%s);\n%s\treturn pyretval;' - % (codeDecl, codePre, formatChars, codeVarsPass, codePost) + '{}\n{}\tPyObject *pyretval = Py_BuildValue("{}"{});\n{}\treturn pyretval;'.format( + codeDecl, codePre, formatChars, codeVarsPass, codePost + ) ) else: f.write("\tPy_INCREF(Py_None);\n\treturn Py_None;\n") @@ -325,23 +328,25 @@ def _write_ifc_cpp(f, interface): f.write("static struct PyMethodDef Py%s_methods[] =\n{\n" % name) for method in interface.methods: f.write( - '\t{ "%s", Py%s::%s, 1 }, // @pymeth %s|Description of %s\n' - % (method.name, interface.name, method.name, method.name, method.name) + '\t{{ "{}", Py{}::{}, 1 }}, // @pymeth {}|Description of {}\n'.format( + method.name, interface.name, method.name, method.name, method.name + ) ) interfacebase = interface.base f.write( """\ - { NULL } -}; - -PyComTypeObject Py%(name)s::type("Py%(name)s", - &Py%(interfacebase)s::type, - sizeof(Py%(name)s), - Py%(name)s_methods, - GET_PYCOM_CTOR(Py%(name)s)); -""" - % locals() + {{ NULL }} +}}; + +PyComTypeObject Py{name}::type("Py{name}", + &Py{interfacebase}::type, + sizeof(Py{name}), + Py{name}_methods, + GET_PYCOM_CTOR(Py{name})); +""".format( + **locals() + ) ) @@ -359,24 +364,24 @@ def _write_gw_h(f, interface): else: base_name = "PyG" + interface.base f.write( - """\ + f"""\ // --------------------------------------------------- // // Gateway Declaration -class %s : public %s, public %s -{ +class {gname} : public {base_name}, public {name} +{{ protected: - %s(PyObject *instance) : %s(instance) { ; } - PYGATEWAY_MAKE_SUPPORT2(%s, %s, IID_%s, %s) + {gname}(PyObject *instance) : {base_name}(instance) {{ ; }} + PYGATEWAY_MAKE_SUPPORT2({gname}, {name}, IID_{name}, {base_name}) """ - % (gname, base_name, name, gname, base_name, gname, name, name, base_name) ) if interface.base != "IUnknown": f.write( - "\t// %s\n\t// *** Manually add %s method decls here\n\n" - % (interface.base, interface.base) + "\t// {}\n\t// *** Manually add {} method decls here\n\n".format( + interface.base, interface.base + ) ) else: f.write("\n\n") @@ -415,26 +420,26 @@ def _write_gw_cpp(f, interface): // --------------------------------------------------- // // Gateway Implementation -""" - % {"name": name, "gname": gname, "base_name": base_name} +""".format( + name=name, gname=gname, base_name=base_name + ) ) for method in interface.methods: f.write( - """\ -STDMETHODIMP %s::%s( + f"""\ +STDMETHODIMP {gname}::{method.name}( """ - % (gname, method.name) ) if method.args: for arg in method.args[:-1]: inoutstr = "][".join(arg.inout) - f.write("\t\t/* [%s] */ %s,\n" % (inoutstr, arg.GetRawDeclaration())) + f.write(f"\t\t/* [{inoutstr}] */ {arg.GetRawDeclaration()},\n") arg = method.args[-1] inoutstr = "][".join(arg.inout) - f.write("\t\t/* [%s] */ %s)\n" % (inoutstr, arg.GetRawDeclaration())) + f.write(f"\t\t/* [{inoutstr}] */ {arg.GetRawDeclaration()})\n") else: f.write("\t\tvoid)\n") @@ -467,16 +472,19 @@ def _write_gw_cpp(f, interface): codePost = codePost + argCvt.GetBuildForGatewayPostCode() except makegwparse.error_not_supported as why: f.write( - '// *** The input argument %s of type "%s" was not processed ***\n// - Please ensure this conversion function exists, and is appropriate\n// - %s\n' - % (arg.name, arg.raw_type, why) + '// *** The input argument {} of type "{}" was not processed ***\n// - Please ensure this conversion function exists, and is appropriate\n// - {}\n'.format( + arg.name, arg.raw_type, why + ) ) f.write( - "\tPyObject *ob%s = PyObject_From%s(%s);\n" - % (arg.name, arg.type, arg.name) + "\tPyObject *ob{} = PyObject_From{}({});\n".format( + arg.name, arg.type, arg.name + ) ) f.write( - '\tif (ob%s==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("%s");\n' - % (arg.name, method.name) + '\tif (ob{}==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("{}");\n'.format( + arg.name, method.name + ) ) codePost = codePost + "\tPy_DECREF(ob%s);\n" % arg.name formatChars = formatChars + "O" @@ -493,11 +501,11 @@ def _write_gw_cpp(f, interface): resStr = "NULL" if formatChars: - fullArgStr = '%s, "%s"%s' % (resStr, formatChars, argStr) + fullArgStr = f'{resStr}, "{formatChars}"{argStr}' else: fullArgStr = resStr - f.write('\tHRESULT hr=InvokeViaPolicy("%s", %s);\n' % (method.name, fullArgStr)) + f.write(f'\tHRESULT hr=InvokeViaPolicy("{method.name}", {fullArgStr});\n') f.write(codePost) if cout: f.write("\tif (FAILED(hr)) return hr;\n") @@ -526,8 +534,9 @@ def _write_gw_cpp(f, interface): needConversion = needConversion or argCvt.NeedUSES_CONVERSION() except makegwparse.error_not_supported as why: f.write( - '// *** The output argument %s of type "%s" was not processed ***\n// %s\n' - % (arg.name, arg.raw_type, why) + '// *** The output argument {} of type "{}" was not processed ***\n// {}\n'.format( + arg.name, arg.raw_type, why + ) ) if formatChars: # If I have any to actually process. @@ -538,8 +547,9 @@ def _write_gw_cpp(f, interface): if codePobjects: f.write(codePobjects) f.write( - '\tif (!%s(result, "%s" %s))\n\t\treturn MAKE_PYCOM_GATEWAY_FAILURE_CODE("%s");\n' - % (parseFn, formatChars, argsParseTuple, method.name) + '\tif (!{}(result, "{}" {}))\n\t\treturn MAKE_PYCOM_GATEWAY_FAILURE_CODE("{}");\n'.format( + parseFn, formatChars, argsParseTuple, method.name + ) ) if codePost: f.write("\tBOOL bPythonIsHappy = TRUE;\n") diff --git a/com/win32com/makegw/makegwenum.py b/com/win32com/makegw/makegwenum.py index 90acc613a2..d541307d12 100644 --- a/com/win32com/makegw/makegwenum.py +++ b/com/win32com/makegw/makegwenum.py @@ -22,19 +22,20 @@ def _write_enumifc_cpp(f, interface): if is_interface_enum(enumtype): # Assume an interface. enum_interface = "I" + enumtype[:-1] - converter = ( - "PyObject *ob = PyCom_PyObjectFromIUnknown(rgVar[i], IID_%(enum_interface)s, FALSE);" - % locals() + converter = "PyObject *ob = PyCom_PyObjectFromIUnknown(rgVar[i], IID_{enum_interface}, FALSE);".format( + **locals() ) arraydeclare = ( - "%(enum_interface)s **rgVar = new %(enum_interface)s *[celt];" % locals() + "{enum_interface} **rgVar = new {enum_interface} *[celt];".format( + **locals() + ) ) else: # Enum of a simple structure - converter = ( - "PyObject *ob = PyCom_PyObjectFrom%(enumtype)s(&rgVar[i]);" % locals() + converter = "PyObject *ob = PyCom_PyObjectFrom{enumtype}(&rgVar[i]);".format( + **locals() ) - arraydeclare = "%(enumtype)s *rgVar = new %(enumtype)s[celt];" % locals() + arraydeclare = "{enumtype} *rgVar = new {enumtype}[celt];".format(**locals()) f.write( """ @@ -42,38 +43,38 @@ def _write_enumifc_cpp(f, interface): // // Interface Implementation -PyIEnum%(enumtype)s::PyIEnum%(enumtype)s(IUnknown *pdisp): +PyIEnum{enumtype}::PyIEnum{enumtype}(IUnknown *pdisp): PyIUnknown(pdisp) -{ +{{ ob_type = &type; -} +}} -PyIEnum%(enumtype)s::~PyIEnum%(enumtype)s() -{ -} +PyIEnum{enumtype}::~PyIEnum{enumtype}() +{{ +}} -/* static */ IEnum%(enumtype)s *PyIEnum%(enumtype)s::GetI(PyObject *self) -{ - return (IEnum%(enumtype)s *)PyIUnknown::GetI(self); -} +/* static */ IEnum{enumtype} *PyIEnum{enumtype}::GetI(PyObject *self) +{{ + return (IEnum{enumtype} *)PyIUnknown::GetI(self); +}} -// @pymethod object|PyIEnum%(enumtype)s|Next|Retrieves a specified number of items in the enumeration sequence. -PyObject *PyIEnum%(enumtype)s::Next(PyObject *self, PyObject *args) -{ +// @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)s *pIE%(enumtype)s = GetI(self); - if ( pIE%(enumtype)s == NULL ) + IEnum{enumtype} *pIE{enumtype} = GetI(self); + if ( pIE{enumtype} == NULL ) return NULL; - %(arraydeclare)s - if ( rgVar == NULL ) { - PyErr_SetString(PyExc_MemoryError, "allocating result %(enumtype)ss"); + {arraydeclare} + if ( rgVar == NULL ) {{ + PyErr_SetString(PyExc_MemoryError, "allocating result {enumtype}s"); return NULL; - } + }} int i; /* for ( i = celt; i--; ) @@ -82,115 +83,116 @@ def _write_enumifc_cpp(f, interface): ULONG celtFetched = 0; PY_INTERFACE_PRECALL; - HRESULT hr = pIE%(enumtype)s->Next(celt, rgVar, &celtFetched); + 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)s, IID_IE%(enumtype)s); - } + return PyCom_BuildPyException(hr,pIE{enumtype}, IID_IE{enumtype}); + }} PyObject *result = PyTuple_New(celtFetched); if ( result != NULL ) - { + {{ for ( i = celtFetched; i--; ) - { - %(converter)s + {{ + {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; -} +}} -// @pymethod |PyIEnum%(enumtype)s|Skip|Skips over the next specified elementes. -PyObject *PyIEnum%(enumtype)s::Skip(PyObject *self, PyObject *args) -{ +// @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)s *pIE%(enumtype)s = GetI(self); - if ( pIE%(enumtype)s == NULL ) + IEnum{enumtype} *pIE{enumtype} = GetI(self); + if ( pIE{enumtype} == NULL ) return NULL; PY_INTERFACE_PRECALL; - HRESULT hr = pIE%(enumtype)s->Skip(celt); + HRESULT hr = pIE{enumtype}->Skip(celt); PY_INTERFACE_POSTCALL; if ( FAILED(hr) ) - return PyCom_BuildPyException(hr, pIE%(enumtype)s, IID_IE%(enumtype)s); + return PyCom_BuildPyException(hr, pIE{enumtype}, IID_IE{enumtype}); Py_INCREF(Py_None); return Py_None; -} +}} -// @pymethod |PyIEnum%(enumtype)s|Reset|Resets the enumeration sequence to the beginning. -PyObject *PyIEnum%(enumtype)s::Reset(PyObject *self, PyObject *args) -{ +// @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; - IEnum%(enumtype)s *pIE%(enumtype)s = GetI(self); - if ( pIE%(enumtype)s == NULL ) + IEnum{enumtype} *pIE{enumtype} = GetI(self); + if ( pIE{enumtype} == NULL ) return NULL; PY_INTERFACE_PRECALL; - HRESULT hr = pIE%(enumtype)s->Reset(); + HRESULT hr = pIE{enumtype}->Reset(); PY_INTERFACE_POSTCALL; if ( FAILED(hr) ) - return PyCom_BuildPyException(hr, pIE%(enumtype)s, IID_IE%(enumtype)s); + return PyCom_BuildPyException(hr, pIE{enumtype}, IID_IE{enumtype}); Py_INCREF(Py_None); return Py_None; -} +}} -// @pymethod |PyIEnum%(enumtype)s|Clone|Creates another enumerator that contains the same enumeration state as the current one -PyObject *PyIEnum%(enumtype)s::Clone(PyObject *self, PyObject *args) -{ +// @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; - IEnum%(enumtype)s *pIE%(enumtype)s = GetI(self); - if ( pIE%(enumtype)s == NULL ) + IEnum{enumtype} *pIE{enumtype} = GetI(self); + if ( pIE{enumtype} == NULL ) return NULL; - IEnum%(enumtype)s *pClone; + IEnum{enumtype} *pClone; PY_INTERFACE_PRECALL; - HRESULT hr = pIE%(enumtype)s->Clone(&pClone); + HRESULT hr = pIE{enumtype}->Clone(&pClone); PY_INTERFACE_POSTCALL; if ( FAILED(hr) ) - return PyCom_BuildPyException(hr, pIE%(enumtype)s, IID_IE%(enumtype)s); - - return PyCom_PyObjectFromIUnknown(pClone, IID_IEnum%(enumtype)s, FALSE); -} - -// @object PyIEnum%(enumtype)s|A Python interface to IEnum%(enumtype)s -static struct PyMethodDef PyIEnum%(enumtype)s_methods[] = -{ - { "Next", PyIEnum%(enumtype)s::Next, 1 }, // @pymeth Next|Retrieves a specified number of items in the enumeration sequence. - { "Skip", PyIEnum%(enumtype)s::Skip, 1 }, // @pymeth Skip|Skips over the next specified elementes. - { "Reset", PyIEnum%(enumtype)s::Reset, 1 }, // @pymeth Reset|Resets the enumeration sequence to the beginning. - { "Clone", PyIEnum%(enumtype)s::Clone, 1 }, // @pymeth Clone|Creates another enumerator that contains the same enumeration state as the current one. - { NULL } -}; - -PyComEnumTypeObject PyIEnum%(enumtype)s::type("PyIEnum%(enumtype)s", + return PyCom_BuildPyException(hr, pIE{enumtype}, IID_IE{enumtype}); + + 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 }} +}}; + +PyComEnumTypeObject PyIEnum{enumtype}::type("PyIEnum{enumtype}", &PyIUnknown::type, - sizeof(PyIEnum%(enumtype)s), - PyIEnum%(enumtype)s_methods, - GET_PYCOM_CTOR(PyIEnum%(enumtype)s)); -""" - % locals() + sizeof(PyIEnum{enumtype}), + PyIEnum{enumtype}_methods, + GET_PYCOM_CTOR(PyIEnum{enumtype})); +""".format( + **locals() + ) ) @@ -199,14 +201,15 @@ def _write_enumgw_cpp(f, interface): if is_interface_enum(enumtype): # Assume an interface. enum_interface = "I" + enumtype[:-1] - converter = ( - "if ( !PyCom_InterfaceFromPyObject(ob, IID_%(enum_interface)s, (void **)&rgVar[i], FALSE) )" - % locals() + converter = "if ( !PyCom_InterfaceFromPyObject(ob, IID_{enum_interface}, (void **)&rgVar[i], FALSE) )".format( + **locals() ) - argdeclare = "%(enum_interface)s __RPC_FAR * __RPC_FAR *rgVar" % locals() + argdeclare = "{enum_interface} __RPC_FAR * __RPC_FAR *rgVar".format(**locals()) else: - argdeclare = "%(enumtype)s __RPC_FAR *rgVar" % locals() - converter = "if ( !PyCom_PyObjectAs%(enumtype)s(ob, &rgVar[i]) )" % locals() + argdeclare = "{enumtype} __RPC_FAR *rgVar".format(**locals()) + converter = "if ( !PyCom_PyObjectAs{enumtype}(ob, &rgVar[i]) )".format( + **locals() + ) f.write( """ // --------------------------------------------------- @@ -214,19 +217,19 @@ def _write_enumgw_cpp(f, interface): // Gateway Implementation // Std delegation -STDMETHODIMP_(ULONG) PyGEnum%(enumtype)s::AddRef(void) {return PyGatewayBase::AddRef();} -STDMETHODIMP_(ULONG) PyGEnum%(enumtype)s::Release(void) {return PyGatewayBase::Release();} -STDMETHODIMP PyGEnum%(enumtype)s::QueryInterface(REFIID iid, void ** obj) {return PyGatewayBase::QueryInterface(iid, obj);} -STDMETHODIMP PyGEnum%(enumtype)s::GetTypeInfoCount(UINT FAR* pctInfo) {return PyGatewayBase::GetTypeInfoCount(pctInfo);} -STDMETHODIMP PyGEnum%(enumtype)s::GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo FAR* FAR* pptInfo) {return PyGatewayBase::GetTypeInfo(itinfo, lcid, pptInfo);} -STDMETHODIMP PyGEnum%(enumtype)s::GetIDsOfNames(REFIID refiid, OLECHAR FAR* FAR* rgszNames, UINT cNames, LCID lcid, DISPID FAR* rgdispid) {return PyGatewayBase::GetIDsOfNames( refiid, rgszNames, cNames, lcid, rgdispid);} -STDMETHODIMP PyGEnum%(enumtype)s::Invoke(DISPID dispid, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS FAR* params, VARIANT FAR* pVarResult, EXCEPINFO FAR* pexcepinfo, UINT FAR* puArgErr) {return PyGatewayBase::Invoke( dispid, riid, lcid, wFlags, params, pVarResult, pexcepinfo, puArgErr);} - -STDMETHODIMP PyGEnum%(enumtype)s::Next( +STDMETHODIMP_(ULONG) PyGEnum{enumtype}::AddRef(void) {{return PyGatewayBase::AddRef();}} +STDMETHODIMP_(ULONG) PyGEnum{enumtype}::Release(void) {{return PyGatewayBase::Release();}} +STDMETHODIMP PyGEnum{enumtype}::QueryInterface(REFIID iid, void ** obj) {{return PyGatewayBase::QueryInterface(iid, obj);}} +STDMETHODIMP PyGEnum{enumtype}::GetTypeInfoCount(UINT FAR* pctInfo) {{return PyGatewayBase::GetTypeInfoCount(pctInfo);}} +STDMETHODIMP PyGEnum{enumtype}::GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo FAR* FAR* pptInfo) {{return PyGatewayBase::GetTypeInfo(itinfo, lcid, pptInfo);}} +STDMETHODIMP PyGEnum{enumtype}::GetIDsOfNames(REFIID refiid, OLECHAR FAR* FAR* rgszNames, UINT cNames, LCID lcid, DISPID FAR* rgdispid) {{return PyGatewayBase::GetIDsOfNames( refiid, rgszNames, cNames, lcid, rgdispid);}} +STDMETHODIMP PyGEnum{enumtype}::Invoke(DISPID dispid, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS FAR* params, VARIANT FAR* pVarResult, EXCEPINFO FAR* pexcepinfo, UINT FAR* puArgErr) {{return PyGatewayBase::Invoke( dispid, riid, lcid, wFlags, params, pVarResult, pexcepinfo, puArgErr);}} + +STDMETHODIMP PyGEnum{enumtype}::Next( /* [in] */ ULONG celt, - /* [length_is][size_is][out] */ %(argdeclare)s, + /* [length_is][size_is][out] */ {argdeclare}, /* [out] */ ULONG __RPC_FAR *pCeltFetched) -{ +{{ PY_GATEWAY_METHOD; PyObject *result; HRESULT hr = InvokeViaPolicy("Next", &result, "i", celt); @@ -247,17 +250,17 @@ def _write_enumgw_cpp(f, interface): int i; for ( i = 0; i < len; ++i ) - { + {{ PyObject *ob = PySequence_GetItem(result, i); if ( ob == NULL ) goto error; - %(converter)s - { + {converter} + {{ Py_DECREF(result); - return PyCom_SetCOMErrorFromPyException(IID_IEnum%(enumtype)s); - } - } + return PyCom_SetCOMErrorFromPyException(IID_IEnum{enumtype}); + }} + }} Py_DECREF(result); @@ -266,25 +269,25 @@ def _write_enumgw_cpp(f, interface): error: PyErr_Clear(); // just in case Py_DECREF(result); - return PyCom_HandleIEnumNoSequence(IID_IEnum%(enumtype)s); -} + return PyCom_HandleIEnumNoSequence(IID_IEnum{enumtype}); +}} -STDMETHODIMP PyGEnum%(enumtype)s::Skip( +STDMETHODIMP PyGEnum{enumtype}::Skip( /* [in] */ ULONG celt) -{ +{{ PY_GATEWAY_METHOD; return InvokeViaPolicy("Skip", NULL, "i", celt); -} +}} -STDMETHODIMP PyGEnum%(enumtype)s::Reset(void) -{ +STDMETHODIMP PyGEnum{enumtype}::Reset(void) +{{ PY_GATEWAY_METHOD; return InvokeViaPolicy("Reset"); -} +}} -STDMETHODIMP PyGEnum%(enumtype)s::Clone( - /* [out] */ IEnum%(enumtype)s __RPC_FAR *__RPC_FAR *ppEnum) -{ +STDMETHODIMP PyGEnum{enumtype}::Clone( + /* [out] */ IEnum{enumtype} __RPC_FAR *__RPC_FAR *ppEnum) +{{ PY_GATEWAY_METHOD; PyObject * result; HRESULT hr = InvokeViaPolicy("Clone", &result); @@ -296,11 +299,11 @@ def _write_enumgw_cpp(f, interface): ** 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)s); - } + return PyCom_SetCOMErrorFromSimple(E_FAIL, IID_IEnum{enumtype}); + }} /* ** Get the IUnknown out of the thing. note that the Python ob maintains @@ -308,23 +311,24 @@ def _write_enumgw_cpp(f, interface): */ IUnknown *punk = ((PyIUnknown *)result)->m_obj; if ( !punk ) - { + {{ /* damn. the object was released. */ Py_DECREF(result); - return PyCom_SetCOMErrorFromSimple(E_FAIL, IID_IEnum%(enumtype)s); - } + 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)s. + ** This QI is actually going to instantiate a PyGEnum{enumtype}. */ - hr = punk->QueryInterface(IID_IEnum%(enumtype)s, (LPVOID *)ppEnum); + 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)s); -} -""" - % locals() + return PyCom_CheckIEnumNextResult(hr, IID_IEnum{enumtype}); +}} +""".format( + **locals() + ) ) diff --git a/com/win32com/makegw/makegwparse.py b/com/win32com/makegw/makegwparse.py index 178ab7adc8..ba32c7fa36 100644 --- a/com/win32com/makegw/makegwparse.py +++ b/com/win32com/makegw/makegwparse.py @@ -108,9 +108,13 @@ def GetInterfaceCppObjectInfo(self): # indirection was applied (plus the builtin amount) # the second return element is the variable declaration; it # should simply be builtin indirection - return self.GetIndirectedArgName( - self.builtinIndirection, self.arg.indirectionLevel + self.builtinIndirection - ), "%s %s" % (self.GetUnconstType(), self.arg.name) + return ( + self.GetIndirectedArgName( + self.builtinIndirection, + self.arg.indirectionLevel + self.builtinIndirection, + ), + f"{self.GetUnconstType()} {self.arg.name}", + ) def GetInterfaceArgCleanup(self): "Return cleanup code for C++ args passed to the interface method." @@ -195,7 +199,7 @@ def GetBuildForGatewayPostCode(self): return s def GetAutoduckString(self): - return "// @pyparm %s|%s||Description for %s" % ( + return "// @pyparm {}|{}||Description for {}".format( self._GetPythonTypeDesc(), self.arg.name, self.arg.name, @@ -309,17 +313,13 @@ def GetBuildForInterfacePostCode(self): return "\tPy_XDECREF(ob%s);\n" % self.arg.name def GetParsePostCode(self): - return ( - "\tif (bPythonIsHappy && !PyWinLong_AsULONG_PTR(ob%s, (ULONG_PTR *)%s)) bPythonIsHappy = FALSE;\n" - % (self.arg.name, self.GetIndirectedArgName(None, 2)) + return "\tif (bPythonIsHappy && !PyWinLong_AsULONG_PTR(ob{}, (ULONG_PTR *){})) bPythonIsHappy = FALSE;\n".format( + self.arg.name, self.GetIndirectedArgName(None, 2) ) def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) - return "\tob%s = PyWinObject_FromULONG_PTR(%s);\n" % ( - self.arg.name, - notdirected, - ) + return f"\tob{self.arg.name} = PyWinObject_FromULONG_PTR({notdirected});\n" def GetBuildForGatewayPostCode(self): return "\tPy_XDECREF(ob%s);\n" % self.arg.name @@ -356,19 +356,19 @@ def _GetPythonTypeDesc(self): return "" def GetParsePostCode(self): - return ( - "\tif (bPythonIsHappy && !PyWinObject_AsBstr(ob%s, %s)) bPythonIsHappy = FALSE;\n" - % (self.arg.name, self.GetIndirectedArgName(None, 2)) + return "\tif (bPythonIsHappy && !PyWinObject_AsBstr(ob{}, {})) bPythonIsHappy = FALSE;\n".format( + self.arg.name, self.GetIndirectedArgName(None, 2) ) def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) - return "\tob%s = MakeBstrToObj(%s);\n" % (self.arg.name, notdirected) + return f"\tob{self.arg.name} = MakeBstrToObj({notdirected});\n" def GetBuildForInterfacePostCode(self): - return "\tSysFreeString(%s);\n" % ( - self.arg.name, - ) + ArgFormatterPythonCOM.GetBuildForInterfacePostCode(self) + return ( + f"\tSysFreeString({self.arg.name});\n" + + ArgFormatterPythonCOM.GetBuildForInterfacePostCode(self) + ) def GetBuildForGatewayPostCode(self): return "\tPy_XDECREF(ob%s);\n" % self.arg.name @@ -385,9 +385,8 @@ def GetUnconstType(self): return self.arg.unc_type def GetParsePostCode(self): - return ( - "\tif (bPythonIsHappy && !PyWinObject_AsBstr(ob%s, %s)) bPythonIsHappy = FALSE;\n" - % (self.arg.name, self.GetIndirectedArgName(None, 2)) + return "\tif (bPythonIsHappy && !PyWinObject_AsBstr(ob{}, {})) bPythonIsHappy = FALSE;\n".format( + self.arg.name, self.GetIndirectedArgName(None, 2) ) def GetInterfaceArgCleanup(self): @@ -396,13 +395,14 @@ def GetInterfaceArgCleanup(self): def GetBuildForInterfacePreCode(self): # the variable was declared with just its builtin indirection notdirected = self.GetIndirectedArgName(self.builtinIndirection, 1) - return "\tob%s = MakeOLECHARToObj(%s);\n" % (self.arg.name, notdirected) + return f"\tob{self.arg.name} = MakeOLECHARToObj({notdirected});\n" def GetBuildForInterfacePostCode(self): # memory returned into an OLECHAR should be freed - return "\tCoTaskMemFree(%s);\n" % ( - self.arg.name, - ) + ArgFormatterPythonCOM.GetBuildForInterfacePostCode(self) + return ( + f"\tCoTaskMemFree({self.arg.name});\n" + + ArgFormatterPythonCOM.GetBuildForInterfacePostCode(self) + ) def GetBuildForGatewayPostCode(self): return "\tPy_XDECREF(ob%s);\n" % self.arg.name @@ -419,9 +419,8 @@ def GetUnconstType(self): return self.arg.unc_type def GetParsePostCode(self): - return ( - "\tif (bPythonIsHappy && !PyWinObject_AsTCHAR(ob%s, %s)) bPythonIsHappy = FALSE;\n" - % (self.arg.name, self.GetIndirectedArgName(None, 2)) + return "\tif (bPythonIsHappy && !PyWinObject_AsTCHAR(ob{}, {})) bPythonIsHappy = FALSE;\n".format( + self.arg.name, self.GetIndirectedArgName(None, 2) ) def GetInterfaceArgCleanup(self): @@ -430,7 +429,7 @@ def GetInterfaceArgCleanup(self): def GetBuildForInterfacePreCode(self): # the variable was declared with just its builtin indirection notdirected = self.GetIndirectedArgName(self.builtinIndirection, 1) - return "\tob%s = PyWinObject_FromTCHAR(%s);\n" % (self.arg.name, notdirected) + return f"\tob{self.arg.name} = PyWinObject_FromTCHAR({notdirected});\n" def GetBuildForInterfacePostCode(self): return "// ??? - TCHAR post code\n" @@ -444,7 +443,7 @@ def _GetPythonTypeDesc(self): return "" def GetParsePostCode(self): - return "\tif (!PyWinObject_AsIID(ob%s, &%s)) bPythonIsHappy = FALSE;\n" % ( + return "\tif (!PyWinObject_AsIID(ob{}, &{})) bPythonIsHappy = FALSE;\n".format( self.arg.name, self.arg.name, ) @@ -452,7 +451,7 @@ def GetParsePostCode(self): def GetBuildForInterfacePreCode(self): # notdirected = self.GetIndirectedArgName(self.arg.indirectionLevel, 0) notdirected = self.GetIndirectedArgName(None, 0) - return "\tob%s = PyWinObject_FromIID(%s);\n" % (self.arg.name, notdirected) + return f"\tob{self.arg.name} = PyWinObject_FromIID({notdirected});\n" def GetInterfaceCppObjectInfo(self): return self.arg.name, "IID %s" % (self.arg.name) @@ -476,19 +475,16 @@ def _GetPythonTypeDesc(self): def GetParsePostCode(self): # variable was declared with only the builtinIndirection ### NOTE: this is an [in] ... so use only builtin - return ( - '\tif (!PyTime_Check(ob%s)) {\n\t\tPyErr_SetString(PyExc_TypeError, "The argument must be a PyTime object");\n\t\tbPythonIsHappy = FALSE;\n\t}\n\tif (!((PyTime *)ob%s)->GetTime(%s)) bPythonIsHappy = FALSE;\n' - % ( - self.arg.name, - self.arg.name, - self.GetIndirectedArgName(self.builtinIndirection, 1), - ) + return '\tif (!PyTime_Check(ob{})) {{\n\t\tPyErr_SetString(PyExc_TypeError, "The argument must be a PyTime object");\n\t\tbPythonIsHappy = FALSE;\n\t}}\n\tif (!((PyTime *)ob{})->GetTime({})) bPythonIsHappy = FALSE;\n'.format( + self.arg.name, + self.arg.name, + self.GetIndirectedArgName(self.builtinIndirection, 1), ) def GetBuildForInterfacePreCode(self): ### use just the builtinIndirection again... notdirected = self.GetIndirectedArgName(self.builtinIndirection, 0) - return "\tob%s = new PyTime(%s);\n" % (self.arg.name, notdirected) + return f"\tob{self.arg.name} = new PyTime({notdirected});\n" def GetBuildForInterfacePostCode(self): ### hack to determine if we need to free stuff @@ -504,21 +500,17 @@ def _GetPythonTypeDesc(self): return "" def GetParsePostCode(self): - return ( - "\tif (!PyCom_PyObjectAsSTATSTG(ob%s, %s, 0/*flags*/)) bPythonIsHappy = FALSE;\n" - % (self.arg.name, self.GetIndirectedArgName(None, 1)) + return "\tif (!PyCom_PyObjectAsSTATSTG(ob{}, {}, 0/*flags*/)) bPythonIsHappy = FALSE;\n".format( + self.arg.name, self.GetIndirectedArgName(None, 1) ) def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) - return ( - "\tob%s = PyCom_PyObjectFromSTATSTG(%s);\n\t// STATSTG doco says our responsibility to free\n\tif ((%s).pwcsName) CoTaskMemFree((%s).pwcsName);\n" - % ( - self.arg.name, - self.GetIndirectedArgName(None, 1), - notdirected, - notdirected, - ) + return "\tob{} = PyCom_PyObjectFromSTATSTG({});\n\t// STATSTG doco says our responsibility to free\n\tif (({}).pwcsName) CoTaskMemFree(({}).pwcsName);\n".format( + self.arg.name, + self.GetIndirectedArgName(None, 1), + notdirected, + notdirected, ) @@ -527,18 +519,18 @@ def _GetPythonTypeDesc(self): return "" % self.arg.type def GetParsePostCode(self): - return "\tif (!PyObject_As%s(ob%s, &%s) bPythonIsHappy = FALSE;\n" % ( + return "\tif (!PyObject_As{}(ob{}, &{}) bPythonIsHappy = FALSE;\n".format( self.arg.type, self.arg.name, self.GetIndirectedArgName(None, 1), ) def GetInterfaceArgCleanup(self): - return "\tPyObject_Free%s(%s);\n" % (self.arg.type, self.arg.name) + return f"\tPyObject_Free{self.arg.type}({self.arg.name});\n" def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) - return "\tob%s = PyObject_From%s(%s);\n" % ( + return "\tob{} = PyObject_From{}({});\n".format( self.arg.name, self.arg.type, self.GetIndirectedArgName(None, 1), @@ -550,17 +542,16 @@ def _GetPythonTypeDesc(self): return "" def GetParsePostCode(self): - return ( - "\tif (bPythonIsHappy && !PyObject_AsPIDL(ob%s, &%s)) bPythonIsHappy = FALSE;\n" - % (self.arg.name, self.GetIndirectedArgName(None, 1)) + return "\tif (bPythonIsHappy && !PyObject_AsPIDL(ob{}, &{})) bPythonIsHappy = FALSE;\n".format( + self.arg.name, self.GetIndirectedArgName(None, 1) ) def GetInterfaceArgCleanup(self): - return "\tPyObject_FreePIDL(%s);\n" % (self.arg.name,) + return f"\tPyObject_FreePIDL({self.arg.name});\n" def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) - return "\tob%s = PyObject_FromPIDL(%s);\n" % ( + return "\tob{} = PyObject_FromPIDL({});\n".format( self.arg.name, self.GetIndirectedArgName(None, 1), ) @@ -571,14 +562,13 @@ def _GetPythonTypeDesc(self): return "" def GetParsePostCode(self): - return ( - "\tif (!PyWinObject_AsHANDLE(ob%s, &%s, FALSE) bPythonIsHappy = FALSE;\n" - % (self.arg.name, self.GetIndirectedArgName(None, 1)) + return "\tif (!PyWinObject_AsHANDLE(ob{}, &{}, FALSE) bPythonIsHappy = FALSE;\n".format( + self.arg.name, self.GetIndirectedArgName(None, 1) ) def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) - return "\tob%s = PyWinObject_FromHANDLE(%s);\n" % ( + return "\tob{} = PyWinObject_FromHANDLE({});\n".format( self.arg.name, self.GetIndirectedArgName(None, 0), ) @@ -592,7 +582,7 @@ def _GetPythonTypeDesc(self): return "" % self.GetKeyName() def GetParsePostCode(self): - return "\tif (!PyWinObject_As%s(ob%s, %s)) bPythonIsHappy = FALSE;\n" % ( + return "\tif (!PyWinObject_As{}(ob{}, {})) bPythonIsHappy = FALSE;\n".format( self.GetKeyName(), self.arg.name, self.GetIndirectedArgName(None, 1), @@ -600,7 +590,7 @@ def GetParsePostCode(self): def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 0) - return "\tob%s = PyWinObject_From%s(%s);\n" % ( + return "\tob{} = PyWinObject_From{}({});\n".format( self.arg.name, self.GetKeyName(), notdirected, @@ -614,7 +604,9 @@ def GetKeyName(self): class ArgFormatterInterface(ArgFormatterPythonCOM): def GetInterfaceCppObjectInfo(self): - return self.GetIndirectedArgName(1, self.arg.indirectionLevel), "%s * %s" % ( + return self.GetIndirectedArgName( + 1, self.arg.indirectionLevel + ), "{} * {}".format( self.GetUnconstType(), self.arg.name, ) @@ -626,13 +618,12 @@ def GetParsePostCode(self): else: # vs. in params for interface mode. sArg = self.GetIndirectedArgName(1, 2) - return ( - "\tif (bPythonIsHappy && !PyCom_InterfaceFromPyInstanceOrObject(ob%s, IID_%s, (void **)%s, TRUE /* bNoneOK */))\n\t\t bPythonIsHappy = FALSE;\n" - % (self.arg.name, self.arg.type, sArg) + return "\tif (bPythonIsHappy && !PyCom_InterfaceFromPyInstanceOrObject(ob{}, IID_{}, (void **){}, TRUE /* bNoneOK */))\n\t\t bPythonIsHappy = FALSE;\n".format( + self.arg.name, self.arg.type, sArg ) def GetBuildForInterfacePreCode(self): - return "\tob%s = PyCom_PyObjectFromIUnknown(%s, IID_%s, FALSE);\n" % ( + return "\tob{} = PyCom_PyObjectFromIUnknown({}, IID_{}, FALSE);\n".format( self.arg.name, self.arg.name, self.arg.type, @@ -640,7 +631,7 @@ def GetBuildForInterfacePreCode(self): def GetBuildForGatewayPreCode(self): sPrefix = self._IndirectPrefix(self._GetDeclaredIndirection(), 1) - return "\tob%s = PyCom_PyObjectFromIUnknown(%s%s, IID_%s, TRUE);\n" % ( + return "\tob{} = PyCom_PyObjectFromIUnknown({}{}, IID_{}, TRUE);\n".format( self.arg.name, sPrefix, self.arg.name, @@ -648,22 +639,18 @@ def GetBuildForGatewayPreCode(self): ) def GetInterfaceArgCleanup(self): - return "\tif (%s) %s->Release();\n" % (self.arg.name, self.arg.name) + return f"\tif ({self.arg.name}) {self.arg.name}->Release();\n" class ArgFormatterVARIANT(ArgFormatterPythonCOM): def GetParsePostCode(self): - return ( - "\tif ( !PyCom_VariantFromPyObject(ob%s, %s) )\n\t\tbPythonIsHappy = FALSE;\n" - % (self.arg.name, self.GetIndirectedArgName(None, 1)) + return "\tif ( !PyCom_VariantFromPyObject(ob{}, {}) )\n\t\tbPythonIsHappy = FALSE;\n".format( + self.arg.name, self.GetIndirectedArgName(None, 1) ) def GetBuildForGatewayPreCode(self): notdirected = self.GetIndirectedArgName(None, 1) - return "\tob%s = PyCom_PyObjectFromVariant(%s);\n" % ( - self.arg.name, - notdirected, - ) + return f"\tob{self.arg.name} = PyCom_PyObjectFromVariant({notdirected});\n" def GetBuildForGatewayPostCode(self): return "\tPy_XDECREF(ob%s);\n" % self.arg.name @@ -783,9 +770,7 @@ def make_arg_converter(arg): if arg.type[0] == "I": return ArgFormatterInterface(arg, 0, 1) - raise error_not_supported( - "The type '%s' (%s) is unknown." % (arg.type, arg.name) - ) + raise error_not_supported(f"The type '{arg.type}' ({arg.name}) is unknown.") ############################################################# @@ -850,8 +835,9 @@ def BuildFromFile(self, file): if VERBOSE: print( - " Arg %s of type %s%s (%s)" - % (self.name, self.type, "*" * self.indirectionLevel, self.inout) + " Arg {} of type {}{} ({})".format( + self.name, self.type, "*" * self.indirectionLevel, self.inout + ) ) def HasAttribute(self, typ): @@ -864,7 +850,7 @@ def HasAttribute(self, typ): return typ in self.inout def GetRawDeclaration(self): - ret = "%s %s" % (self.raw_type, self.name) + ret = f"{self.raw_type} {self.name}" if self.arrayDecl: ret = ret + "[]" return ret @@ -909,7 +895,7 @@ def BuildFromFile(self, file): "Method %s - Only HRESULT return types are supported." % self.name ) # raise error_not_supported, if VERBOSE: - print(" Method %s %s(" % (self.result, self.name)) + print(f" Method {self.result} {self.name}(") while 1: arg = Argument(self.good_interface_names) try: @@ -935,7 +921,7 @@ def __init__(self, mo): self.name = mo.group(2) self.base = mo.group(3) if VERBOSE: - print("Interface %s : public %s" % (self.name, self.base)) + print(f"Interface {self.name} : public {self.base}") def BuildMethods(self, file): """Build all sub-methods for this interface""" diff --git a/com/win32com/server/dispatcher.py b/com/win32com/server/dispatcher.py index 71b91e7a59..eb0eaaaecd 100644 --- a/com/win32com/server/dispatcher.py +++ b/com/win32com/server/dispatcher.py @@ -150,8 +150,9 @@ def _QueryInterface_(self, iid): rc = DispatcherBase._QueryInterface_(self, iid) if not rc: self._trace_( - "in %s._QueryInterface_ with unsupported IID %s (%s)" - % (repr(self.policy._obj_), IIDToInterfaceName(iid), iid) + "in {}._QueryInterface_ with unsupported IID {} ({})".format( + repr(self.policy._obj_), IIDToInterfaceName(iid), iid + ) ) return rc @@ -177,8 +178,9 @@ def _GetDispID_(self, name, fdex): def _InvokeEx_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider): self._trace_( - "in %r._InvokeEx_-%s%r [%x,%s,%r]" - % (self.policy._obj_, dispid, args, wFlags, lcid, serviceProvider) + "in {!r}._InvokeEx_-{}{!r} [{:x},{},{!r}]".format( + self.policy._obj_, dispid, args, wFlags, lcid, serviceProvider + ) ) return DispatcherBase._InvokeEx_( self, dispid, lcid, wFlags, args, kwargs, serviceProvider diff --git a/com/win32com/server/exception.py b/com/win32com/server/exception.py index e7f4d08060..599636e730 100644 --- a/com/win32com/server/exception.py +++ b/com/win32com/server/exception.py @@ -78,7 +78,7 @@ def __init__( pythoncom.com_error.__init__(self, scode, self.description, None, -1) def __repr__(self): - return "" % (self.scode, self.description) + return f"" # Old name for the COMException class. diff --git a/com/win32com/server/policy.py b/com/win32com/server/policy.py index aba1356dc6..7d46d83d02 100644 --- a/com/win32com/server/policy.py +++ b/com/win32com/server/policy.py @@ -223,9 +223,8 @@ def _CreateInstance_(self, clsid, reqIID): from win32com.util import IIDToInterfaceName desc = ( - "The object '%r' was created, but does not support the " - "interface '%s'(%s): %s" - % (myob, IIDToInterfaceName(reqIID), reqIID, desc) + f"The object '{myob!r}' was created, but does not support the " + f"interface '{IIDToInterfaceName(reqIID)}'({reqIID}): {desc}" ) raise pythoncom.com_error(hr, desc, exc, arg) @@ -641,9 +640,7 @@ def _invokeex_(self, dispid, lcid, wFlags, args, kwArgs, serviceProvider): # Particularly nasty is "wrong number of args" type error # This helps you see what 'func' and 'args' actually is if str(v).find("arguments") >= 0: - print( - "** TypeError %s calling function %r(%r)" % (v, func, args) - ) + print(f"** TypeError {v} calling function {func!r}({args!r})") raise if wFlags & DISPATCH_PROPERTYGET: diff --git a/com/win32com/server/register.py b/com/win32com/server/register.py index 250c20d5ca..211e7428b6 100644 --- a/com/win32com/server/register.py +++ b/com/win32com/server/register.py @@ -258,14 +258,14 @@ def RegisterServer( # If we are frozen, we write "{exe} /Automate", just # like "normal" .EXEs do exeName = win32api.GetShortPathName(sys.executable) - command = "%s /Automate" % (exeName,) + command = f"{exeName} /Automate" else: # Running from .py sources - we need to write # 'python.exe win32com\server\localserver.py {clsid}" exeName = _find_localserver_exe(1) exeName = win32api.GetShortPathName(exeName) pyfile = _find_localserver_module() - command = '%s "%s" %s' % (exeName, pyfile, str(clsid)) + command = f'{exeName} "{pyfile}" {str(clsid)}' _set_string(keyNameRoot + "\\LocalServer32", command) else: # Remove any old LocalServer32 registrations _remove_key(keyNameRoot + "\\LocalServer32") @@ -376,7 +376,7 @@ def UnregisterServer(clsid, progID=None, verProgID=None, customKeys=None): def GetRegisteredServerOption(clsid, optionName): """Given a CLSID for a server and option name, return the option value""" - keyNameRoot = "CLSID\\%s\\%s" % (str(clsid), str(optionName)) + keyNameRoot = f"CLSID\\{str(clsid)}\\{str(optionName)}" return _get_string(keyNameRoot) @@ -589,8 +589,9 @@ def ReExecuteElevated(flags): print(os.path.splitdrive(cwd)[0], file=batf) print('cd "%s"' % os.getcwd(), file=batf) print( - '%s %s > "%s" 2>&1' - % (win32api.GetShortPathName(exe_to_run), new_params, outfile), + '{} {} > "{}" 2>&1'.format( + win32api.GetShortPathName(exe_to_run), new_params, outfile + ), file=batf, ) finally: @@ -624,7 +625,7 @@ def ReExecuteElevated(flags): try: os.unlink(f) except OSError as exc: - print("Failed to remove tempfile '%s': %s" % (f, exc)) + print(f"Failed to remove tempfile '{f}': {exc}") def UseCommandLine(*classes, **flags): diff --git a/com/win32com/test/GenTestScripts.py b/com/win32com/test/GenTestScripts.py index 08b19d5905..627560fded 100644 --- a/com/win32com/test/GenTestScripts.py +++ b/com/win32com/test/GenTestScripts.py @@ -38,7 +38,7 @@ def GenerateFromRegistered(fname, *loadArgs): ) f.close() print("compiling -", end=" ") - fullModName = "win32com.test.%s.%s" % (genDir, fname) + fullModName = f"win32com.test.{genDir}.{fname}" exec("import " + fullModName) # Inject the generated module as a top level module. sys.modules[fname] = sys.modules[fullModName] diff --git a/com/win32com/test/daodump.py b/com/win32com/test/daodump.py index c222087a51..a1c9d68c5f 100644 --- a/com/win32com/test/daodump.py +++ b/com/win32com/test/daodump.py @@ -38,10 +38,7 @@ def DumpFields(fields): def DumpRelations(db, bDeep=1): for relation in db.Relations: - print( - "Relation %s - %s->%s" - % (relation.Name, relation.Table, relation.ForeignTable) - ) + print(f"Relation {relation.Name} - {relation.Table}->{relation.ForeignTable}") #### This dont work. TLB says it is a Fields collection, but apparently not! @@ -60,7 +57,7 @@ def DumpContainerDocuments(container): import time timeStr = time.ctime(int(doc.LastUpdated)) - print(" %s - updated %s (" % (doc.Name, timeStr), end=" ") + print(f" {doc.Name} - updated {timeStr} (", end=" ") print(doc.LastUpdated, ")") # test the _print_ method? diff --git a/com/win32com/test/errorSemantics.py b/com/win32com/test/errorSemantics.py index 49ebae2f1c..ddeddc93ad 100644 --- a/com/win32com/test/errorSemantics.py +++ b/com/win32com/test/errorSemantics.py @@ -91,7 +91,7 @@ def test(): ) # Check we saw a traceback in stderr if cap.get_captured().find("Traceback") < 0: - raise error("Could not find a traceback in stderr: %r" % (cap.get_captured(),)) + raise error(f"Could not find a traceback in stderr: {cap.get_captured()!r}") # Now do it all again, but using IDispatch com_server = Dispatch(wrap(TestServer())) @@ -143,7 +143,7 @@ def test(): ) # Check we saw a traceback in stderr if cap.get_captured().find("Traceback") < 0: - raise error("Could not find a traceback in stderr: %r" % (cap.get_captured(),)) + raise error(f"Could not find a traceback in stderr: {cap.get_captured()!r}") # And an explicit com_error cap.clear() diff --git a/com/win32com/test/pippo_server.py b/com/win32com/test/pippo_server.py index edcd91685e..1c2219d8c9 100644 --- a/com/win32com/test/pippo_server.py +++ b/com/win32com/test/pippo_server.py @@ -47,8 +47,8 @@ def BuildTypelib(): idl = os.path.abspath(os.path.join(this_dir, "pippo.idl")) tlb = os.path.splitext(idl)[0] + ".tlb" if newer(idl, tlb): - print("Compiling %s" % (idl,)) - rc = os.system('midl "%s"' % (idl,)) + print(f"Compiling {idl}") + rc = os.system(f'midl "{idl}"') if rc: raise RuntimeError("Compiling MIDL failed!") # Can't work out how to prevent MIDL from generating the stubs. @@ -56,7 +56,7 @@ def BuildTypelib(): for fname in "dlldata.c pippo_i.c pippo_p.c pippo.h".split(): os.remove(os.path.join(this_dir, fname)) - print("Registering %s" % (tlb,)) + print(f"Registering {tlb}") tli = pythoncom.LoadTypeLib(tlb) pythoncom.RegisterTypeLib(tli, tlb) diff --git a/com/win32com/test/testAXScript.py b/com/win32com/test/testAXScript.py index c37a5aff74..d7a4553ed9 100644 --- a/com/win32com/test/testAXScript.py +++ b/com/win32com/test/testAXScript.py @@ -24,7 +24,7 @@ def testHost(self): file = win32api.GetFullPathName( os.path.join(win32com.axscript.__path__[0], "test\\testHost.py") ) - cmd = '%s "%s"' % (win32api.GetModuleFileName(0), file) + cmd = f'{win32api.GetModuleFileName(0)} "{file}"' if verbose: print("Testing Python Scripting host") win32com.test.util.ExecuteShellCommand(cmd, self) diff --git a/com/win32com/test/testCollections.py b/com/win32com/test/testCollections.py index 9639c1395a..999c65b09f 100644 --- a/com/win32com/test/testCollections.py +++ b/com/win32com/test/testCollections.py @@ -36,15 +36,17 @@ def TestEnumAgainst(o, check): for i in range(len(check)): if o(i) != check[i]: raise error( - "Using default method gave the incorrect value - %s/%s" - % (repr(o(i)), repr(check[i])) + "Using default method gave the incorrect value - {}/{}".format( + repr(o(i)), repr(check[i]) + ) ) for i in range(len(check)): if o.Item(i) != check[i]: raise error( - "Using Item method gave the incorrect value - %s/%s" - % (repr(o(i)), repr(check[i])) + "Using Item method gave the incorrect value - {}/{}".format( + repr(o(i)), repr(check[i]) + ) ) # First try looping. @@ -54,8 +56,9 @@ def TestEnumAgainst(o, check): if cmp[: len(check)] != check: raise error( - "Result after looping isnt correct - %s/%s" - % (repr(cmp[: len(check)]), repr(check)) + "Result after looping isnt correct - {}/{}".format( + repr(cmp[: len(check)]), repr(check) + ) ) for i in range(len(check)): @@ -109,14 +112,14 @@ def TestEnum(quiet=None): raise error("default method with no args worked when it shouldnt have!") except pythoncom.com_error as exc: if exc.hresult != winerror.DISP_E_BADPARAMCOUNT: - raise error("Expected DISP_E_BADPARAMCOUNT - got %s" % (exc,)) + raise error(f"Expected DISP_E_BADPARAMCOUNT - got {exc}") try: o.Insert("foo", 2) raise error("Insert worked when it shouldnt have!") except pythoncom.com_error as exc: if exc.hresult != winerror.DISP_E_TYPEMISMATCH: - raise error("Expected DISP_E_TYPEMISMATCH - got %s" % (exc,)) + raise error(f"Expected DISP_E_TYPEMISMATCH - got {exc}") # Remove the sublist for this test! try: @@ -124,7 +127,7 @@ def TestEnum(quiet=None): raise error("Remove worked when it shouldnt have!") except pythoncom.com_error as exc: if exc.hresult != winerror.DISP_E_BADINDEX: - raise error("Expected DISP_E_BADINDEX - got %s" % (exc,)) + raise error(f"Expected DISP_E_BADINDEX - got {exc}") # Test an empty collection if not quiet: @@ -150,7 +153,7 @@ def TestEnum(quiet=None): raise error("Empty list could be indexed") except pythoncom.com_error as exc: if exc.hresult != winerror.DISP_E_BADINDEX: - raise error("Expected DISP_E_BADINDEX - got %s" % (exc,)) + raise error(f"Expected DISP_E_BADINDEX - got {exc}") class TestCase(win32com.test.util.TestCase): diff --git a/com/win32com/test/testDCOM.py b/com/win32com/test/testDCOM.py index 9dedf5d101..fea4d20404 100644 --- a/com/win32com/test/testDCOM.py +++ b/com/win32com/test/testDCOM.py @@ -35,8 +35,9 @@ def test(serverName): actualName = ob.Eval("win32api.GetComputerName()") if serverName.lower() != actualName.lower(): print( - "Error: The object created on server '%s' reported its name as '%s'" - % (serverName, actualName) + "Error: The object created on server '{}' reported its name as '{}'".format( + serverName, actualName + ) ) else: print("Object created and tested OK on server '%s'" % serverName) diff --git a/com/win32com/test/testDictionary.py b/com/win32com/test/testDictionary.py index 869cc1862f..c191dc4aa3 100644 --- a/com/win32com/test/testDictionary.py +++ b/com/win32com/test/testDictionary.py @@ -20,8 +20,9 @@ def TestDictAgainst(dict, check): for key, value in list(check.items()): if dict(key) != value: raise Exception( - "Indexing for '%s' gave the incorrect value - %s/%s" - % (repr(key), repr(dict[key]), repr(check[key])) + "Indexing for '{}' gave the incorrect value - {}/{}".format( + repr(key), repr(dict[key]), repr(check[key]) + ) ) diff --git a/com/win32com/test/testDynamic.py b/com/win32com/test/testDynamic.py index 8dd1d82a67..ed0c5d1ddf 100644 --- a/com/win32com/test/testDynamic.py +++ b/com/win32com/test/testDynamic.py @@ -68,8 +68,9 @@ def Test(): client.TestSequence = v if v != list(client.TestSequence): raise error( - "Dynamic sequences not working! %r/%r" - % (repr(v), repr(client.testSequence)) + "Dynamic sequences not working! {!r}/{!r}".format( + repr(v), repr(client.testSequence) + ) ) client.write("This", "output", "has", "come", "via", "testDynamic.py") diff --git a/com/win32com/test/testExchange.py b/com/win32com/test/testExchange.py index b41a44726a..bad0e121e6 100644 --- a/com/win32com/test/testExchange.py +++ b/com/win32com/test/testExchange.py @@ -90,7 +90,7 @@ def TestUser(session): id = PropTagsById[field.ID] except KeyError: id = field.ID - print("%s/%s=%s" % (field.Name, id, field.Value)) + print(f"{field.Name}/{id}={field.Value}") def test(): diff --git a/com/win32com/test/testGatewayAddresses.py b/com/win32com/test/testGatewayAddresses.py index d489916992..6fb2e1836a 100644 --- a/com/win32com/test/testGatewayAddresses.py +++ b/com/win32com/test/testGatewayAddresses.py @@ -60,7 +60,7 @@ def FailObjectIdentity(ob1, ob2, when): if not CheckObjectIdentity(ob1, ob2): global numErrors numErrors = numErrors + 1 - print(when, "are not identical (%s, %s)" % (repr(ob1), repr(ob2))) + print(when, f"are not identical ({repr(ob1)}, {repr(ob2)})") class Dummy: diff --git a/com/win32com/test/testPyComTest.py b/com/win32com/test/testPyComTest.py index c48490aefe..578376246f 100644 --- a/com/win32com/test/testPyComTest.py +++ b/com/win32com/test/testPyComTest.py @@ -50,7 +50,7 @@ def check_get_set(func, arg): got = func(arg) if got != arg: - raise error("%s failed - expected %r, got %r" % (func, arg, got)) + raise error(f"{func} failed - expected {arg!r}, got {got!r}") def check_get_set_raises(exc, func, arg): @@ -59,9 +59,7 @@ def check_get_set_raises(exc, func, arg): except exc as e: pass # what we expect! else: - raise error( - "%s with arg %r didn't raise %s - returned %r" % (func, arg, exc, got) - ) + raise error(f"{func} with arg {arg!r} didn't raise {exc} - returned {got!r}") def progress(*args): @@ -80,18 +78,17 @@ def TestApplyResult(fn, args, result): pref = "function " + fnName rc = fn(*args) if rc != result: - raise error("%s failed - result not %r but %r" % (pref, result, rc)) + raise error(f"{pref} failed - result not {result!r} but {rc!r}") def TestConstant(constName, pyConst): try: comConst = getattr(constants, constName) except: - raise error("Constant %s missing" % (constName,)) + raise error(f"Constant {constName} missing") if comConst != pyConst: raise error( - "Constant value wrong for %s - got %s, wanted %s" - % (constName, comConst, pyConst) + f"Constant value wrong for {constName} - got {comConst}, wanted {pyConst}" ) @@ -160,7 +157,7 @@ def TestCommon(o, is_generated): # CoClass instances have `default_interface` expected_class = getattr(expected_class, "default_interface", expected_class) if not isinstance(o.GetSetDispatch(o), expected_class): - raise error("GetSetDispatch failed: %r" % (o.GetSetDispatch(o),)) + raise error(f"GetSetDispatch failed: {o.GetSetDispatch(o)!r}") progress("Checking getting/passing IDispatch of known type") expected_class = o.__class__ expected_class = getattr(expected_class, "default_interface", expected_class) @@ -285,11 +282,11 @@ def TestCommon(o, is_generated): # currency. pythoncom.__future_currency__ = 1 if o.CurrencyProp != 0: - raise error("Expecting 0, got %r" % (o.CurrencyProp,)) + raise error(f"Expecting 0, got {o.CurrencyProp!r}") for val in ("1234.5678", "1234.56", "1234"): o.CurrencyProp = decimal.Decimal(val) if o.CurrencyProp != decimal.Decimal(val): - raise error("%s got %r" % (val, o.CurrencyProp)) + raise error(f"{val} got {o.CurrencyProp!r}") v1 = decimal.Decimal("1234.5678") TestApplyResult(o.DoubleCurrency, (v1,), v1 * 2) @@ -434,7 +431,7 @@ def TestGenerated(): if not isinstance(i1, DispatchBaseClass) or not isinstance(i2, DispatchBaseClass): # Yay - is now an instance returned! raise error( - "GetMultipleInterfaces did not return instances - got '%s', '%s'" % (i1, i2) + f"GetMultipleInterfaces did not return instances - got '{i1}', '{i2}'" ) del i1 del i2 @@ -553,7 +550,7 @@ def _TestPyVariant(o, is_generated, val, checker=None): def _TestPyVariantFails(o, is_generated, val, exc): try: _TestPyVariant(o, is_generated, val) - raise error("Setting %r didn't raise %s" % (val, exc)) + raise error(f"Setting {val!r} didn't raise {exc}") except exc: pass diff --git a/com/win32com/test/testStorage.py b/com/win32com/test/testStorage.py index 3bbe776ce2..27ae640e0d 100644 --- a/com/win32com/test/testStorage.py +++ b/com/win32com/test/testStorage.py @@ -66,7 +66,7 @@ def testit(self): ): pass else: - self.fail("Uxexpected property %s/%s" % (p, p_val)) + self.fail(f"Uxexpected property {p}/{p_val}") ps = None ## FMTID_UserDefinedProperties can't exist without FMTID_DocSummaryInformation, and isn't returned independently from Enum ## also can't be open at same time diff --git a/com/win32com/test/testall.py b/com/win32com/test/testall.py index 6ca312e344..1e44989059 100644 --- a/com/win32com/test/testall.py +++ b/com/win32com/test/testall.py @@ -101,7 +101,7 @@ def testit(self): # Execute testPyComTest in its own process so it can play # with the Python thread state fname = os.path.join(os.path.dirname(this_file), "testPyComTest.py") - cmd = '%s "%s" -q 2>&1' % (sys.executable, fname) + cmd = f'{sys.executable} "{fname}" -q 2>&1' data = ExecuteSilentlyIfOK(cmd, self) @@ -114,7 +114,7 @@ def testit(self): python = sys.executable fname = os.path.join(os.path.dirname(this_file), "testPippo.py") - cmd = '%s "%s" 2>&1' % (python, fname) + cmd = f'{python} "{fname}" 2>&1' ExecuteSilentlyIfOK(cmd, self) @@ -218,7 +218,7 @@ def make_test_suite(test_level=1): for mod_name in unittest_modules[i]: mod, func = get_test_mod_and_func(mod_name, import_failures) if mod is None: - raise Exception("no such module '{}'".format(mod_name)) + raise Exception(f"no such module '{mod_name}'") if func is not None: test = CapturingFunctionTestCase(func, description=mod_name) else: @@ -305,7 +305,7 @@ def usage(why): ) for mod_name, (exc_type, exc_val) in import_failures: desc = "\n".join(traceback.format_exception_only(exc_type, exc_val)) - testResult.stream.write("%s: %s" % (mod_name, desc)) + testResult.stream.write(f"{mod_name}: {desc}") testResult.stream.writeln( "*** %d test(s) could not be run ***" % len(import_failures) ) diff --git a/com/win32com/test/testmakepy.py b/com/win32com/test/testmakepy.py index 2eeb881871..2d414d3d8b 100644 --- a/com/win32com/test/testmakepy.py +++ b/com/win32com/test/testmakepy.py @@ -15,7 +15,7 @@ def TestBuildAll(verbose=1): tlbInfos = selecttlb.EnumTlbs() for info in tlbInfos: if verbose: - print("%s (%s)" % (info.desc, info.dll)) + print(f"{info.desc} ({info.dll})") try: makepy.GenerateFromTypeLibSpec(info) # sys.stderr.write("Attr typeflags for coclass referenced object %s=%d (%d), typekind=%d\n" % (name, refAttr.wTypeFlags, refAttr.wTypeFlags & pythoncom.TYPEFLAG_FDUAL,refAttr.typekind)) diff --git a/com/win32com/test/testvb.py b/com/win32com/test/testvb.py index c82b4e73fb..bd188ca0c2 100644 --- a/com/win32com/test/testvb.py +++ b/com/win32com/test/testvb.py @@ -96,8 +96,9 @@ def TestVB(vbtest, bUseGenerated): vbtest.VariantProperty = (1.0, 2.0, 3.0) if vbtest.VariantProperty != (1.0, 2.0, 3.0): raise error( - "Could not set the variant property to an array of floats correctly - '%s'." - % (vbtest.VariantProperty,) + "Could not set the variant property to an array of floats correctly - '{}'.".format( + vbtest.VariantProperty + ) ) TestArrays(vbtest, bUseGenerated) @@ -185,17 +186,16 @@ def _getcount(ob): for item in c: check.append(item) if check != list(expected): - raise error( - "Collection %s didn't have %r (had %r)" % (col_name, expected, check) - ) + raise error(f"Collection {col_name} didn't have {expected!r} (had {check!r})") # Just looping over the collection again works (ie, is restartable) check = [] for item in c: check.append(item) if check != list(expected): raise error( - "Collection 2nd time around %s didn't have %r (had %r)" - % (col_name, expected, check) + "Collection 2nd time around {} didn't have {!r} (had {!r})".format( + col_name, expected, check + ) ) # Check we can get it via iter() i = iter(getattr(vbtest, col_name)) @@ -204,8 +204,9 @@ def _getcount(ob): check.append(item) if check != list(expected): raise error( - "Collection iterator %s didn't have %r 2nd time around (had %r)" - % (col_name, expected, check) + "Collection iterator {} didn't have {!r} 2nd time around (had {!r})".format( + col_name, expected, check + ) ) # but an iterator is not restartable check = [] @@ -213,16 +214,16 @@ def _getcount(ob): check.append(item) if check != []: raise error( - "2nd time around Collection iterator %s wasn't empty (had %r)" - % (col_name, check) + "2nd time around Collection iterator {} wasn't empty (had {!r})".format( + col_name, check + ) ) # Check len()==Count() c = getattr(vbtest, col_name) if len(c) != _getcount(c): raise error( - "Collection %s __len__(%r) wasn't==Count(%r)" - % (col_name, len(c), _getcount(c)) + f"Collection {col_name} __len__({len(c)!r}) wasn't==Count({_getcount(c)!r})" ) # Check we can do it with zero based indexing. c = getattr(vbtest, col_name) @@ -230,9 +231,7 @@ def _getcount(ob): for i in range(_getcount(c)): check.append(c[i]) if check != list(expected): - raise error( - "Collection %s didn't have %r (had %r)" % (col_name, expected, check) - ) + raise error(f"Collection {col_name} didn't have {expected!r} (had {check!r})") # Check we can do it with our old "Skip/Next" methods. c = getattr(vbtest, col_name)._NewEnum() @@ -243,9 +242,7 @@ def _getcount(ob): break check.append(n[0]) if check != list(expected): - raise error( - "Collection %s didn't have %r (had %r)" % (col_name, expected, check) - ) + raise error(f"Collection {col_name} didn't have {expected!r} (had {check!r})") def TestCollections(vbtest): @@ -271,7 +268,7 @@ def _DoTestArray(vbtest, data, expected_exception=None): got = vbtest.ArrayProperty if got != data: raise error( - "Could not set the array data correctly - got %r, expected %r" % (got, data) + f"Could not set the array data correctly - got {got!r}, expected {data!r}" ) @@ -332,7 +329,7 @@ def TestArrays(vbtest, bUseGenerated): except pythoncom.com_error as exc: assert ( exc.excepinfo[1] == "Python COM Server Internal Error" - ), "Didnt get the correct exception - '%s'" % (exc,) + ), f"Didnt get the correct exception - '{exc}'" if bUseGenerated: # This one is a bit strange! The array param is "ByRef", as VB insists. @@ -355,11 +352,11 @@ def TestArrays(vbtest, bUseGenerated): assert testData == list(resultData) testData = ["hi", "from", "Python"] resultData, byRefParam = vbtest.PassSAFEARRAYVariant(testData) - assert testData == list(byRefParam), "Expected '%s', got '%s'" % ( + assert testData == list(byRefParam), "Expected '{}', got '{}'".format( testData, list(byRefParam), ) - assert testData == list(resultData), "Expected '%s', got '%s'" % ( + assert testData == list(resultData), "Expected '{}', got '{}'".format( testData, list(resultData), ) @@ -486,11 +483,13 @@ def TestStructs(vbtest): assert "foo" in str(exc), exc # test repr - it uses repr() of the sub-objects, so check it matches. - expected = "com_struct(int_val=%r, str_val=%r, ob_val=%r, sub_val=%r)" % ( - s.int_val, - s.str_val, - s.ob_val, - s.sub_val, + expected = ( + "com_struct(int_val={!r}, str_val={!r}, ob_val={!r}, sub_val={!r})".format( + s.int_val, + s.str_val, + s.ob_val, + s.sub_val, + ) ) if repr(s) != expected: print("Expected repr:", expected) diff --git a/com/win32com/test/testxslt.py b/com/win32com/test/testxslt.py index 62780ff429..26e089795c 100644 --- a/com/win32com/test/testxslt.py +++ b/com/win32com/test/testxslt.py @@ -19,8 +19,8 @@ def testAll(self): try: got = f.read() if got != expected_output: - print("ERROR: XSLT expected output of %r" % (expected_output,)) - print("but got %r" % (got,)) + print(f"ERROR: XSLT expected output of {expected_output!r}") + print(f"but got {got!r}") finally: f.close() finally: diff --git a/com/win32com/test/util.py b/com/win32com/test/util.py index 1704f63267..73dfd1f2a0 100644 --- a/com/win32com/test/util.py +++ b/com/win32com/test/util.py @@ -53,9 +53,11 @@ def RegisterPythonServer(filename, progids=None, verbose=0): "pythoncomloader%d%d.dll" % (sys.version_info[0], sys.version_info[1]), ] if os.path.basename(dll) not in ok_files: - why_not = "%r is registered against a different Python version (%s)" % ( - progid, - dll, + why_not = ( + "{!r} is registered against a different Python version ({})".format( + progid, + dll, + ) ) break else: @@ -84,7 +86,7 @@ def RegisterPythonServer(filename, progids=None, verbose=0): # them the same way as "real" errors. raise pythoncom.com_error(winerror.CO_E_CLASSSTRING, msg, None, -1) # so theoretically we are able to register it. - cmd = '%s "%s" --unattended > nul 2>&1' % (win32api.GetModuleFileName(0), filename) + cmd = f'{win32api.GetModuleFileName(0)} "{filename}" --unattended > nul 2>&1' if verbose: print("Registering engine", filename) # print cmd @@ -114,7 +116,7 @@ class Failed(Exception): if rc: raise Failed("exit code was " + str(rc)) if expected_output is not None and output != expected_output: - raise Failed("Expected output %r (got %r)" % (expected_output, output)) + raise Failed(f"Expected output {expected_output!r} (got {output!r})") if not tracebacks_ok and output.find("Traceback (most recent call last)") >= 0: raise Failed("traceback in program output") return output @@ -124,7 +126,7 @@ class Failed(Exception): print("** start of program output **") print(output) print("** end of program output **") - testcase.fail("Executing '%s' failed as %s" % (cmd, why)) + testcase.fail(f"Executing '{cmd}' failed as {why}") def assertRaisesCOM_HRESULT(testcase, hresult, func, *args, **kw): diff --git a/com/win32com/universal.py b/com/win32com/universal.py index f7d86e4dde..6a87f6857e 100644 --- a/com/win32com/universal.py +++ b/com/win32com/universal.py @@ -40,7 +40,7 @@ def RegisterInterfaces(typelibGUID, lcid, major, minor, interface_names=None): # Not sure why we don't get an exception here - BindType's C # impl looks correct.. if type_info is None: - raise ValueError("The interface '%s' can not be located" % (name,)) + raise ValueError(f"The interface '{name}' can not be located") # If we got back a Dispatch interface, convert to the real interface. attr = type_info.GetTypeAttr() if attr.typekind == pythoncom.TKIND_DISPATCH: @@ -66,14 +66,14 @@ def RegisterInterfaces(typelibGUID, lcid, major, minor, interface_names=None): iid = mod.NamesToIIDMap[name] except KeyError: raise ValueError( - "Interface '%s' does not exist in this cached typelib" % (name,) + f"Interface '{name}' does not exist in this cached typelib" ) # 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) if is_dispatch is None or method_defs is None: - raise ValueError("Interface '%s' is IDispatch only" % (name,)) + raise ValueError(f"Interface '{name}' is IDispatch only") # And create the univgw defn _doCreateVTable(iid, name, is_dispatch, method_defs) @@ -215,8 +215,9 @@ def dispatch( retVal = retVal[1:] else: raise TypeError( - "Expected %s return values, got: %s" - % (len(meth._gw_out_args) + 1, len(retVal)) + "Expected {} return values, got: {}".format( + len(meth._gw_out_args) + 1, len(retVal) + ) ) else: retVal = [retVal] diff --git a/com/win32comext/adsi/demos/scp.py b/com/win32comext/adsi/demos/scp.py index cc96e5a878..6f2c252839 100644 --- a/com/win32comext/adsi/demos/scp.py +++ b/com/win32comext/adsi/demos/scp.py @@ -199,7 +199,7 @@ def AllowAccessToScpProperties( setattr(scpObject, attribute, sd) # SetInfo updates the SCP object in the directory. scpObject.SetInfo() - logger.info("Set security on object for account '%s'" % (trustee,)) + logger.info(f"Set security on object for account '{trustee}'") # Service Principal Names functions from the same sample. @@ -391,7 +391,7 @@ def main(): arg_descs = [] for arg, func in handlers: this_desc = "\n".join(textwrap.wrap(func.__doc__, subsequent_indent=" " * 8)) - arg_descs.append(" %s: %s" % (arg, this_desc)) + arg_descs.append(f" {arg}: {this_desc}") _handlers_dict[arg.lower()] = func description = __doc__ + "\ncommands:\n" + "\n".join(arg_descs) + "\n" diff --git a/com/win32comext/adsi/demos/search.py b/com/win32comext/adsi/demos/search.py index 22c6a25811..a577da2c71 100644 --- a/com/win32comext/adsi/demos/search.py +++ b/com/win32comext/adsi/demos/search.py @@ -59,9 +59,9 @@ def print_attribute(col_data): value = [converters.get(prop_name, _null_converter)(v[0]) for v in values] if len(value) == 1: value = value[0] - print(" %s=%r" % (prop_name, value)) + print(f" {prop_name}={value!r}") else: - print(" %s is None" % (prop_name,)) + print(f" {prop_name} is None") def search(): diff --git a/com/win32comext/adsi/demos/test.py b/com/win32comext/adsi/demos/test.py index b0e15f5c64..64061ab68d 100644 --- a/com/win32comext/adsi/demos/test.py +++ b/com/win32comext/adsi/demos/test.py @@ -16,12 +16,12 @@ def DumpRoot(): rootdse = ADsGetObject(path) for item in rootdse.Get("SupportedLDAPVersion"): - print("%s supports ldap version %s" % (path, item)) + print(f"{path} supports ldap version {item}") attributes = ["CurrentTime", "defaultNamingContext"] for attr in attributes: val = rootdse.Get(attr) - print(" %s=%s" % (attr, val)) + print(f" {attr}={val}") ############################################### @@ -48,9 +48,9 @@ def _DumpTheseAttributes(child, attrs): (hr, msg, exc, arg) = details if exc and exc[2]: msg = exc[2] - val = "" % (msg,) + val = f"" if verbose_level >= 2: - print(" %s: %s=%s" % (child.Class, attr, val)) + print(f" {child.Class}: {attr}={val}") def DumpSchema(): @@ -90,7 +90,7 @@ def DumpSchema(): def _DumpObject(ob, level=0): prefix = " " * level - print("%s%s object: %s" % (prefix, ob.Class, ob.Name)) + print(f"{prefix}{ob.Class} object: {ob.Name}") # Do the directory object thing try: dir_ob = ADsGetObject(ob.ADsPath, IID_IDirectoryObject) @@ -98,13 +98,13 @@ def _DumpObject(ob, level=0): dir_ob = None if dir_ob is not None: info = dir_ob.GetObjectInformation() - print("%s RDN='%s', ObjectDN='%s'" % (prefix, info.RDN, info.ObjectDN)) + print(f"{prefix} RDN='{info.RDN}', ObjectDN='{info.ObjectDN}'") # Create a list of names to fetch names = ["distinguishedName"] attrs = dir_ob.GetObjectAttributes(names) for attr in attrs: for val, typ in attr.Values: - print("%s Attribute '%s' = %s" % (prefix, attr.AttrName, val)) + print(f"{prefix} Attribute '{attr.AttrName}' = {val}") for child in ob: _DumpObject(child, level + 1) @@ -139,7 +139,7 @@ def DumpAllObjects(): def DumpSchema2(): "Dumps the schema using an alternative technique" - path = "LDAP://%sschema" % (server,) + path = f"LDAP://{server}schema" schema = ADsGetObject(path, IID_IADsContainer) nclass = nprop = nsyntax = 0 for item in schema: @@ -157,8 +157,9 @@ def DumpSchema2(): iid_name = win32com.util.IIDToInterfaceName(item.PrimaryInterface) if verbose_level >= 2: print( - "Class: Name=%s, Flags=%s, Primary Interface=%s" - % (item.Name, desc, iid_name) + "Class: Name={}, Flags={}, Primary Interface={}".format( + item.Name, desc, iid_name + ) ) nclass = nclass + 1 elif item_class == "property": @@ -167,12 +168,12 @@ def DumpSchema2(): else: val_type = "Single-Valued" if verbose_level >= 2: - print("Property: Name=%s, %s" % (item.Name, val_type)) + print(f"Property: Name={item.Name}, {val_type}") nprop = nprop + 1 elif item_class == "syntax": data_type = vt_map.get(item.OleAutoDataType, "") if verbose_level >= 2: - print("Syntax: Name=%s, Datatype = %s" % (item.Name, data_type)) + print(f"Syntax: Name={item.Name}, Datatype = {data_type}") nsyntax = nsyntax + 1 if verbose_level >= 1: print("Processed", nclass, "classes") @@ -184,30 +185,30 @@ def DumpGC(): "Dumps the GC: object (whatever that is!)" ob = ADsGetObject("GC:", IID_IADsContainer) for sub_ob in ob: - print("GC ob: %s (%s)" % (sub_ob.Name, sub_ob.ADsPath)) + print(f"GC ob: {sub_ob.Name} ({sub_ob.ADsPath})") def DumpLocalUsers(): "Dumps the local machine users" - path = "WinNT://%s,computer" % (local_name,) + path = f"WinNT://{local_name},computer" ob = ADsGetObject(path, IID_IADsContainer) ob.put_Filter(["User", "Group"]) for sub_ob in ob: - print("User/Group: %s (%s)" % (sub_ob.Name, sub_ob.ADsPath)) + print(f"User/Group: {sub_ob.Name} ({sub_ob.ADsPath})") def DumpLocalGroups(): "Dumps the local machine groups" - path = "WinNT://%s,computer" % (local_name,) + path = f"WinNT://{local_name},computer" ob = ADsGetObject(path, IID_IADsContainer) ob.put_Filter(["Group"]) for sub_ob in ob: - print("Group: %s (%s)" % (sub_ob.Name, sub_ob.ADsPath)) + print(f"Group: {sub_ob.Name} ({sub_ob.ADsPath})") # get the members members = sub_ob.Members() for member in members: - print(" Group member: %s (%s)" % (member.Name, member.ADsPath)) + print(f" Group member: {member.Name} ({member.ADsPath})") def usage(tests): diff --git a/com/win32comext/axdebug/Test/host.py b/com/win32comext/axdebug/Test/host.py index da99b1b2fe..f1ec148f60 100644 --- a/com/win32comext/axdebug/Test/host.py +++ b/com/win32comext/axdebug/Test/host.py @@ -49,8 +49,9 @@ def _query_interface_(self, iid): from win32com.util import IIDToInterfaceName trace( - "PySourceModuleDebugDocumentHost QI with %s (%s)" - % (IIDToInterfaceName(iid), str(iid)) + "PySourceModuleDebugDocumentHost QI with {} ({})".format( + IIDToInterfaceName(iid), str(iid) + ) ) return 0 diff --git a/com/win32comext/axdebug/adb.py b/com/win32comext/axdebug/adb.py index 812c23e62a..68850b5c1b 100644 --- a/com/win32comext/axdebug/adb.py +++ b/com/win32comext/axdebug/adb.py @@ -427,8 +427,9 @@ def OnBreakFlagChange(self, abf, rdat): def _BreakFlagsChanged(self): traceenter( - "_BreakFlagsChanged to %s with our thread = %s, and debugging thread = %s" - % (self.breakFlags, self.debuggingThread, win32api.GetCurrentThreadId()) + "_BreakFlagsChanged to {} with our thread = {}, and debugging thread = {}".format( + self.breakFlags, self.debuggingThread, win32api.GetCurrentThreadId() + ) ) trace("_BreakFlagsChanged has breaks", self.breaks) # If a request comes on our debugging thread, then do it now! diff --git a/com/win32comext/axdebug/dump.py b/com/win32comext/axdebug/dump.py index 26ee51e0d0..c47654fb1c 100644 --- a/com/win32comext/axdebug/dump.py +++ b/com/win32comext/axdebug/dump.py @@ -18,7 +18,7 @@ def DumpDebugApplicationNode(node, level=0): info = node.GetName(attr) except pythoncom.com_error: info = "" - print("%s%s: %s" % (spacer, desc, info)) + print(f"{spacer}{desc}: {info}") try: doc = node.GetDocument() except pythoncom.com_error: @@ -32,7 +32,7 @@ def DumpDebugApplicationNode(node, level=0): "%sText is %s, %d bytes long" % (spacer, repr(text[:40] + "..."), len(text)) ) else: - print("%s%s" % (spacer, "")) + print("{}{}".format(spacer, "")) for child in Enumerator(node.EnumChildren()): DumpDebugApplicationNode(child, level + 1) diff --git a/com/win32comext/axdebug/util.py b/com/win32comext/axdebug/util.py index c3d4f733f6..ff0af1720d 100644 --- a/com/win32comext/axdebug/util.py +++ b/com/win32comext/axdebug/util.py @@ -129,9 +129,7 @@ def _Invoke_(self, dispid, lcid, wFlags, args): desc = " (" + str(v.description) + ")" except AttributeError: desc = "" - print( - "*** Invoke of %s raised COM exception 0x%x%s" % (dispid, scode, desc) - ) + print(f"*** Invoke of {dispid} raised COM exception 0x{scode:x}{desc}") except: print("*** Invoke of %s failed:" % dispid) typ, val, tb = sys.exc_info() diff --git a/com/win32comext/axscript/client/error.py b/com/win32comext/axscript/client/error.py index b92c15741b..c4d24db9de 100644 --- a/com/win32comext/axscript/client/error.py +++ b/com/win32comext/axscript/client/error.py @@ -113,7 +113,7 @@ def _BuildFromSyntaxError(self, site, exc, tb): try: msg = value[0] except: - msg = "Unknown Error (%s)" % (value,) + msg = f"Unknown Error ({value})" try: (filename, lineno, offset, line) = value[1] # Some of these may be None, which upsets us! @@ -178,7 +178,7 @@ def _BuildFromOther(self, site, exc_type, value, tb): bits = ["Traceback (most recent call last):\n"] bits.extend(traceback.format_list(format_items)) if exc_type == pythoncom.com_error: - desc = "%s (0x%x)" % (value.strerror, value.hresult) + desc = f"{value.strerror} (0x{value.hresult:x})" if ( value.hresult == winerror.DISP_E_EXCEPTION and value.excepinfo diff --git a/com/win32comext/axscript/client/framework.py b/com/win32comext/axscript/client/framework.py index 85021c4488..f94c553111 100644 --- a/com/win32comext/axscript/client/framework.py +++ b/com/win32comext/axscript/client/framework.py @@ -744,8 +744,9 @@ def SetScriptSite(self, site): except: traceback.print_exc() trace( - "*** Debugger Manager could not initialize - %s: %s" - % (sys.exc_info()[0], sys.exc_info()[1]) + "*** Debugger Manager could not initialize - {}: {}".format( + sys.exc_info()[0], sys.exc_info()[1] + ) ) self.debugManager = None diff --git a/com/win32comext/axscript/client/pyscript.py b/com/win32comext/axscript/client/pyscript.py index b359791051..0ce08fc35e 100644 --- a/com/win32comext/axscript/client/pyscript.py +++ b/com/win32comext/axscript/client/pyscript.py @@ -382,7 +382,7 @@ def DoParseScriptText( num = self._GetNextCodeBlockNumber() if num == 1: num = "" - name = "%s %s" % (name, num) + name = f"{name} {num}" codeBlock = AXScriptCodeBlock( name, code, sourceContextCookie, startLineNumber, flags ) diff --git a/com/win32comext/axscript/test/testHost.py b/com/win32comext/axscript/test/testHost.py index 466bdb3ac5..ee6210fa65 100644 --- a/com/win32comext/axscript/test/testHost.py +++ b/com/win32comext/axscript/test/testHost.py @@ -155,8 +155,7 @@ def _CheckEngineState(engine, name, state): got_name = state_map.get(got, str(got)) state_name = state_map.get(state, str(state)) raise RuntimeError( - "Warning - engine %s has state %s, but expected %s" - % (name, got_name, state_name) + f"Warning - engine {name} has state {got_name}, but expected {state_name}" ) @@ -180,18 +179,16 @@ def _TestEngine(self, engineName, code, expected_exc=None): ob.hello("Goober") self.assertTrue( expected_exc is None, - "Expected %r, but no exception seen" % (expected_exc,), + f"Expected {expected_exc!r}, but no exception seen", ) except pythoncom.com_error: if expected_exc is None: self.fail( - "Unexpected failure from script code: %s" - % (site.exception_seen,) + f"Unexpected failure from script code: {site.exception_seen}" ) if expected_exc not in site.exception_seen[2]: self.fail( - "Could not find %r in %r" - % (expected_exc, site.exception_seen[2]) + f"Could not find {expected_exc!r} in {site.exception_seen[2]!r}" ) return self.assertEqual(echoer.last, "Goober") diff --git a/com/win32comext/axscript/test/testHost4Dbg.py b/com/win32comext/axscript/test/testHost4Dbg.py index 3bfafd676d..9b38a9ef4a 100644 --- a/com/win32comext/axscript/test/testHost4Dbg.py +++ b/com/win32comext/axscript/test/testHost4Dbg.py @@ -65,7 +65,7 @@ def TestEngine(): pyEngine.Start() # Actually run the Python code vbEngine.Start() # Actually run the VB code except pythoncom.com_error as details: - print("Script failed: %s (0x%x)" % (details[1], details[0])) + print(f"Script failed: {details[1]} (0x{details[0]:x})") # Now run the code expected to fail! # try: # pyEngine2.Start() # Actually run the Python code that fails! diff --git a/com/win32comext/bits/test/test_bits.py b/com/win32comext/bits/test/test_bits.py index 6ff7005fb6..d414e074b8 100755 --- a/com/win32comext/bits/test/test_bits.py +++ b/com/win32comext/bits/test/test_bits.py @@ -57,7 +57,7 @@ def _print_error(self, err): hresult_msg = win32api.FormatMessage(hresult) except win32api.error: hresult_msg = "" - print("Context=0x%x, hresult=0x%x (%s)" % (ctx, hresult, hresult_msg)) + print(f"Context=0x{ctx:x}, hresult=0x{hresult:x} ({hresult_msg})") print(err.GetErrorDescription()) def JobModification(self, job, reserved): diff --git a/com/win32comext/ifilter/demo/filterDemo.py b/com/win32comext/ifilter/demo/filterDemo.py index 91b3c7c17b..513f70081c 100644 --- a/com/win32comext/ifilter/demo/filterDemo.py +++ b/com/win32comext/ifilter/demo/filterDemo.py @@ -93,9 +93,9 @@ def Parse(self, fileName, maxErrors=10): # the set guid and property id. (note: the id can be a number or a string. propSet = self.propertyToName.get(attr[0]) if propSet: - propName = propSet.get(attr[1], "%s:%s" % attr) + propName = propSet.get(attr[1], "{}:{}".format(*attr)) else: - propName = "%s:%s" % attr + propName = "{}:{}".format(*attr) except pythoncom.com_error as e: if e[0] == FILTER_E_END_OF_CHUNKS: @@ -227,7 +227,7 @@ def _trace(self, *args): def _usage(): import os - print("Usage: %s filename [verbose [dumpbody]]" % (os.path.basename(sys.argv[0]),)) + print(f"Usage: {os.path.basename(sys.argv[0])} filename [verbose [dumpbody]]") print() print("Where:-") print("filename = name of the file to extract text & properties from") diff --git a/com/win32comext/mapi/mapiutil.py b/com/win32comext/mapi/mapiutil.py index 03d2a63982..bf13788076 100644 --- a/com/win32comext/mapi/mapiutil.py +++ b/com/win32comext/mapi/mapiutil.py @@ -160,7 +160,7 @@ def SetPropertyValue(obj, prop, val): type_tag = _MapiTypeMap.get(type(val)) if type_tag is None: raise ValueError( - "Don't know what to do with '%r' ('%s')" % (val, type(val)) + f"Don't know what to do with '{val!r}' ('{type(val)}')" ) prop = mapitags.PROP_TAG(type_tag, mapitags.PROP_ID(propIds[0])) if val is None: @@ -201,8 +201,7 @@ def SetProperties(msg, propDict): tagType = mapitags.PT_SYSTIME else: raise ValueError( - "The type of object %s(%s) can not be written" - % (repr(val), type(val)) + f"The type of object {repr(val)}({type(val)}) can not be written" ) key = mapitags.PROP_TAG(tagType, mapitags.PROP_ID(newIds[newIdNo])) newIdNo = newIdNo + 1 diff --git a/com/win32comext/shell/demos/ITransferAdviseSink.py b/com/win32comext/shell/demos/ITransferAdviseSink.py index dfd25eb513..ae4a7dea71 100644 --- a/com/win32comext/shell/demos/ITransferAdviseSink.py +++ b/com/win32comext/shell/demos/ITransferAdviseSink.py @@ -50,9 +50,9 @@ def UpdateProgress( FoldersTotal, ): print("UpdateProgress - processed so far:") - print("\t %s out of %s bytes" % (SizeCurrent, SizeTotal)) - print("\t %s out of %s files" % (FilesCurrent, FilesTotal)) - print("\t %s out of %s folders" % (FoldersCurrent, FoldersTotal)) + print(f"\t {SizeCurrent} out of {SizeTotal} bytes") + print(f"\t {FilesCurrent} out of {FilesTotal} files") + print(f"\t {FoldersCurrent} out of {FoldersTotal} folders") def UpdateTransferState(self, State): print( diff --git a/com/win32comext/shell/demos/servers/empty_volume_cache.py b/com/win32comext/shell/demos/servers/empty_volume_cache.py index 6a0fb6a193..e5c8aa1636 100644 --- a/com/win32comext/shell/demos/servers/empty_volume_cache.py +++ b/com/win32comext/shell/demos/servers/empty_volume_cache.py @@ -155,7 +155,7 @@ def DllRegisterServer(): # See link at top of file. import winreg - kn = r"Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\%s" % ( + kn = r"Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\{}".format( EmptyVolumeCache._reg_desc_, ) key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, kn) @@ -165,7 +165,7 @@ def DllRegisterServer(): def DllUnregisterServer(): import winreg - kn = r"Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\%s" % ( + kn = r"Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\{}".format( EmptyVolumeCache._reg_desc_, ) try: diff --git a/com/win32comext/shell/demos/servers/folder_view.py b/com/win32comext/shell/demos/servers/folder_view.py index 08ca34731c..784fde81b2 100644 --- a/com/win32comext/shell/demos/servers/folder_view.py +++ b/com/win32comext/shell/demos/servers/folder_view.py @@ -822,7 +822,7 @@ def DllRegisterServer(): s = struct.pack("i", attr) winreg.SetValueEx(key, "Attributes", 0, winreg.REG_BINARY, s) # register the context menu handler under the FolderViewSampleType type. - keypath = "%s\\shellex\\ContextMenuHandlers\\%s" % ( + keypath = "{}\\shellex\\ContextMenuHandlers\\{}".format( ContextMenu._context_menu_type_, ContextMenu._reg_desc_, ) @@ -838,8 +838,9 @@ def DllUnregisterServer(): paths = [ "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Desktop\\Namespace\\" + ShellFolder._reg_clsid_, - "%s\\shellex\\ContextMenuHandlers\\%s" - % (ContextMenu._context_menu_type_, ContextMenu._reg_desc_), + "{}\\shellex\\ContextMenuHandlers\\{}".format( + ContextMenu._context_menu_type_, ContextMenu._reg_desc_ + ), ] for path in paths: try: @@ -848,7 +849,7 @@ def DllUnregisterServer(): import errno if details.errno != errno.ENOENT: - print("FAILED to remove %s: %s" % (path, details)) + print(f"FAILED to remove {path}: {details}") propsys.PSUnregisterPropertySchema(get_schema_fname()) print(ShellFolder._reg_desc_, "unregistration complete.") diff --git a/isapi/install.py b/isapi/install.py index 12416fd645..0631b50ed4 100644 --- a/isapi/install.py +++ b/isapi/install.py @@ -213,7 +213,7 @@ def LoadWebServer(path): msg = details.strerror if exc.excepinfo and exc.excepinfo[2]: msg = exc.excepinfo[2] - msg = "WebServer %s: %s" % (path, msg) + msg = f"WebServer {path}: {msg}" raise ItemNotFound(msg) return server @@ -274,12 +274,12 @@ def _CreateDirectory(iis_dir, name, params): # *any* existing object, regardless of Class assert name.strip("/"), "mustn't delete the root!" iis_dir.Delete("", name) - log(2, "Deleted old directory '%s'" % (name,)) + log(2, f"Deleted old directory '{name}'") except pythoncom.com_error: pass newDir = iis_dir.Create(params.Type, name) - log(2, "Creating new directory '%s' in %s..." % (name, iis_dir.Name)) + log(2, f"Creating new directory '{name}' in {iis_dir.Name}...") friendly = params.Description or params.Name newDir.AppFriendlyName = friendly @@ -326,7 +326,7 @@ def CreateDirectory(params, options): AssignScriptMaps(params.ScriptMaps, target_dir, params.ScriptMapUpdate) _CallHook(params, "PostInstall", options, target_dir) - log(1, "Configured Virtual Directory: %s" % (params.Name,)) + log(1, f"Configured Virtual Directory: {params.Name}") return target_dir @@ -395,7 +395,7 @@ def CreateISAPIFilter(filterParams, options): assert filterParams.Name.strip("/"), "mustn't delete the root!" try: filters.Delete(_IIS_FILTER, filterParams.Name) - log(2, "Deleted old filter '%s'" % (filterParams.Name,)) + log(2, f"Deleted old filter '{filterParams.Name}'") except pythoncom.com_error: pass newFilter = filters.Create(_IIS_FILTER, filterParams.Name) @@ -410,7 +410,7 @@ def CreateISAPIFilter(filterParams, options): filters.FilterLoadOrder = ",".join(load_order) filters.SetInfo() _CallHook(filterParams, "PostInstall", options, newFilter) - log(1, "Configured Filter: %s" % (filterParams.Name,)) + log(1, f"Configured Filter: {filterParams.Name}") return newFilter @@ -423,17 +423,17 @@ def DeleteISAPIFilter(filterParams, options): except pythoncom.com_error as details: # failure to open the filters just means a totally clean IIS install # (IIS5 at least has no 'Filters' key when freshly installed). - log(2, "ISAPI filter path '%s' did not exist." % (ob_path,)) + log(2, f"ISAPI filter path '{ob_path}' did not exist.") return try: assert filterParams.Name.strip("/"), "mustn't delete the root!" filters.Delete(_IIS_FILTER, filterParams.Name) - log(2, "Deleted ISAPI filter '%s'" % (filterParams.Name,)) + log(2, f"Deleted ISAPI filter '{filterParams.Name}'") except pythoncom.com_error as details: rc = _GetWin32ErrorCode(details) if rc != winerror.ERROR_PATH_NOT_FOUND: raise - log(2, "ISAPI filter '%s' did not exist." % (filterParams.Name,)) + log(2, f"ISAPI filter '{filterParams.Name}' did not exist.") # Remove from the load order load_order = [b.strip() for b in filters.FilterLoadOrder.split(",") if b] if filterParams.Name in load_order: @@ -441,7 +441,7 @@ def DeleteISAPIFilter(filterParams, options): filters.FilterLoadOrder = ",".join(load_order) filters.SetInfo() _CallHook(filterParams, "PostRemove", options) - log(1, "Deleted Filter: %s" % (filterParams.Name,)) + log(1, f"Deleted Filter: {filterParams.Name}") def _AddExtensionFile(module, def_groupid, def_desc, params, options): @@ -456,11 +456,11 @@ def _AddExtensionFile(module, def_groupid, def_desc, params, options): params.AddExtensionFile_CanDelete, desc, ) - log(2, "Added extension file '%s' (%s)" % (module, desc)) + log(2, f"Added extension file '{module}' ({desc})") except (pythoncom.com_error, AttributeError) as details: # IIS5 always fails. Probably should upgrade this to # complain more loudly if IIS6 fails. - log(2, "Failed to add extension file '%s': %s" % (module, details)) + log(2, f"Failed to add extension file '{module}': {details}") def AddExtensionFiles(params, options): @@ -486,7 +486,7 @@ def _DeleteExtensionFileRecord(module, options): ob.DeleteExtensionFileRecord(module) log(2, "Deleted extension file record for '%s'" % module) except (pythoncom.com_error, AttributeError) as details: - log(2, "Failed to remove extension file '%s': %s" % (module, details)) + log(2, f"Failed to remove extension file '{module}': {details}") def DeleteExtensionFileRecords(params, options): @@ -509,7 +509,7 @@ def CheckLoaderModule(dll_name): suffix = "_d" template = os.path.join(this_dir, "PyISAPI_loader" + suffix + ".dll") if not os.path.isfile(template): - raise ConfigurationError("Template loader '%s' does not exist" % (template,)) + raise ConfigurationError(f"Template loader '{template}' does not exist") # We can't do a simple "is newer" check, as the DLL is specific to the # Python version. So we check the date-time and size are identical, # and skip the copy in that case. @@ -524,11 +524,11 @@ def CheckLoaderModule(dll_name): and src_stat[stat.ST_MTIME] == dest_stat[stat.ST_MTIME] ) if not same: - log(2, "Updating %s->%s" % (template, dll_name)) + log(2, f"Updating {template}->{dll_name}") shutil.copyfile(template, dll_name) shutil.copystat(template, dll_name) else: - log(2, "%s is up to date." % (dll_name,)) + log(2, f"{dll_name} is up to date.") def _CallHook(ob, hook_name, options, *extra_args): @@ -568,15 +568,15 @@ def RemoveDirectory(params, options): directory.AppUnLoad() except: exc_val = sys.exc_info()[1] - log(2, "AppUnLoad() for %s failed: %s" % (params.Name, exc_val)) + log(2, f"AppUnLoad() for {params.Name} failed: {exc_val}") # Continue trying to delete it. try: parent = GetObject(directory.Parent) parent.Delete(directory.Class, directory.Name) - log(1, "Deleted Virtual Directory: %s" % (params.Name,)) + log(1, f"Deleted Virtual Directory: {params.Name}") except: exc_val = sys.exc_info()[1] - log(1, "Failed to remove directory %s: %s" % (params.Name, exc_val)) + log(1, f"Failed to remove directory {params.Name}: {exc_val}") def RemoveScriptMaps(vd_params, options): @@ -617,7 +617,7 @@ def Uninstall(params, options): def _PatchParamsModule(params, dll_name, file_must_exist=True): if file_must_exist: if not os.path.isfile(dll_name): - raise ConfigurationError("%s does not exist" % (dll_name,)) + raise ConfigurationError(f"{dll_name} does not exist") # Patch up all references to the DLL. for f in params.Filters: @@ -668,7 +668,7 @@ def InstallModule(conf_module_name, params, options, log=lambda *args: None): if not hasattr(sys, "frozen"): conf_module_name = os.path.abspath(conf_module_name) if not os.path.isfile(conf_module_name): - raise ConfigurationError("%s does not exist" % (conf_module_name,)) + raise ConfigurationError(f"{conf_module_name} does not exist") loader_dll = GetLoaderModuleName(conf_module_name) _PatchParamsModule(params, loader_dll) @@ -753,7 +753,7 @@ def HandleCommandLine( except win32api.error as exc: log( 2, - "Couldn't determine the long name for %r: %s" % (conf_module_name, exc), + f"Couldn't determine the long name for {conf_module_name!r}: {exc}", ) if opt_parser is None: @@ -795,7 +795,7 @@ def HandleCommandLine( "--server", action="store", help="Specifies the IIS server to install/uninstall on." - " Default is '%s/1'" % (_IIS_OBJECT,), + f" Default is '{_IIS_OBJECT}/1'", ) (options, args) = parser.parse_args(argv[1:]) @@ -810,6 +810,6 @@ def HandleCommandLine( except (ItemNotFound, InstallationError) as details: if options.verbose > 1: traceback.print_exc() - print("%s: %s" % (details.__class__.__name__, details)) + print(f"{details.__class__.__name__}: {details}") except KeyError: parser.error("Invalid arg '%s'" % arg) diff --git a/isapi/samples/advanced.py b/isapi/samples/advanced.py index c10d0c80c9..913de024a6 100644 --- a/isapi/samples/advanced.py +++ b/isapi/samples/advanced.py @@ -139,7 +139,7 @@ def HttpExtensionProc(self, ecb): print("
                    ", file=ecb)
                                 for q in queries:
                                     val = ecb.GetServerVariable(q, "<no such variable>")
                    -                print("%s=%r" % (q, val), file=ecb)
                    +                print(f"{q}={val!r}", file=ecb)
                                 print("

                    ", file=ecb) print("This module has been imported", file=ecb) diff --git a/isapi/samples/redirector.py b/isapi/samples/redirector.py index da62d40228..edc8815838 100644 --- a/isapi/samples/redirector.py +++ b/isapi/samples/redirector.py @@ -87,7 +87,7 @@ def Dispatch(self, ecb): ecb.SendResponseHeaders("200 OK", header_text, False) ecb.WriteClient(fp.read()) ecb.DoneWithSession() - print("Returned data from '%s'" % (new_url,)) + print(f"Returned data from '{new_url}'") return isapicon.HSE_STATUS_SUCCESS diff --git a/isapi/samples/redirector_asynch.py b/isapi/samples/redirector_asynch.py index 3c4b5e4f77..24af96e4b1 100644 --- a/isapi/samples/redirector_asynch.py +++ b/isapi/samples/redirector_asynch.py @@ -41,7 +41,7 @@ class Extension(threaded_extension.ThreadPoolExtension): "Python sample proxy server - asynch version." def Dispatch(self, ecb): - print('IIS dispatching "%s"' % (ecb.GetServerVariable("URL"),)) + print('IIS dispatching "{}"'.format(ecb.GetServerVariable("URL"))) url = ecb.GetServerVariable("URL") new_url = proxy + url diff --git a/isapi/samples/redirector_with_filter.py b/isapi/samples/redirector_with_filter.py index a63b1db13a..ba048a0913 100644 --- a/isapi/samples/redirector_with_filter.py +++ b/isapi/samples/redirector_with_filter.py @@ -74,11 +74,11 @@ def Dispatch(self, ecb): ecb.SendResponseHeaders("200 OK", str(headers) + "\r\n", False) ecb.WriteClient(fp.read()) ecb.DoneWithSession() - print("Returned data from '%s'!" % (new_url,)) + print(f"Returned data from '{new_url}'!") else: # this should never happen - we should only see requests that # start with our virtual directory name. - print("Not proxying '%s'" % (url,)) + print(f"Not proxying '{url}'") # The ISAPI filter. @@ -98,7 +98,7 @@ def HttpFilterProc(self, fc): prefix = virtualdir if not url.startswith(prefix): new_url = prefix + url - print("New proxied URL is '%s'" % (new_url,)) + print(f"New proxied URL is '{new_url}'") pp.SetHeader("url", new_url) # For the sake of demonstration, show how the FilterContext # attribute is used. It always starts out life as None, and @@ -110,7 +110,7 @@ def HttpFilterProc(self, fc): print("This is request number %d on this connection" % fc.FilterContext) return isapicon.SF_STATUS_REQ_HANDLED_NOTIFICATION else: - print("Filter ignoring URL '%s'" % (url,)) + print(f"Filter ignoring URL '{url}'") # Some older code that handled SF_NOTIFY_URL_MAP. # ~ print "Have URL_MAP notify" diff --git a/isapi/test/extension_simple.py b/isapi/test/extension_simple.py index 64bd71fd22..dfc79dfdd7 100644 --- a/isapi/test/extension_simple.py +++ b/isapi/test/extension_simple.py @@ -31,12 +31,12 @@ class Extension(threaded_extension.ThreadPoolExtension): "Python ISAPI Tester" def Dispatch(self, ecb): - print('Tester dispatching "%s"' % (ecb.GetServerVariable("URL"),)) + print('Tester dispatching "{}"'.format(ecb.GetServerVariable("URL"))) url = ecb.GetServerVariable("URL") test_name = url.split("/")[-1] meth = getattr(self, test_name, None) if meth is None: - raise AttributeError("No test named '%s'" % (test_name,)) + raise AttributeError(f"No test named '{test_name}'") result = meth(ecb) if result is None: # This means the test finalized everything diff --git a/isapi/threaded_extension.py b/isapi/threaded_extension.py index b31c8c9e70..12a1191df6 100644 --- a/isapi/threaded_extension.py +++ b/isapi/threaded_extension.py @@ -45,7 +45,7 @@ def run(self): # Let the parent extension handle the command. dispatcher = self.extension.dispatch_map.get(key) if dispatcher is None: - raise RuntimeError("Bad request '%s'" % (key,)) + raise RuntimeError(f"Bad request '{key}'") dispatcher(errCode, bytes, key, overlapped) @@ -166,8 +166,7 @@ def HandleDispatchError(self, ecb): exc_tb, limit ) + traceback.format_exception_only(exc_typ, exc_val) print( - "

                    %s%s
                    " - % ( + "
                    {}{}
                    ".format( cgi.escape("".join(list[:-1])), cgi.escape(list[-1]), ), diff --git a/pywin32_postinstall.py b/pywin32_postinstall.py index 1c0b396ad5..4801397066 100644 --- a/pywin32_postinstall.py +++ b/pywin32_postinstall.py @@ -137,7 +137,7 @@ def get_special_folder_path(path_name): if maybe == path_name: csidl = getattr(shellcon, maybe) return shell.SHGetSpecialFolderPath(0, csidl, False) - raise ValueError("%s is an unknown path ID" % (path_name,)) + raise ValueError(f"{path_name} is an unknown path ID") def CopyTo(desc, src, dest): @@ -155,10 +155,9 @@ def CopyTo(desc, src, dest): # Running silent mode - just re-raise the error. raise full_desc = ( - "Error %s\n\n" + f"Error {desc}\n\n" "If you have any Python applications running, " - "please close them now\nand select 'Retry'\n\n%s" - % (desc, details.strerror) + f"please close them now\nand select 'Retry'\n\n{details.strerror}" ) rc = win32api.MessageBox( 0, full_desc, "Installation Error", win32con.MB_ABORTRETRYIGNORE @@ -203,7 +202,7 @@ def SetPyKeyVal(key_name, value_name, value): try: winreg.SetValueEx(my_key, value_name, 0, winreg.REG_SZ, value) if verbose: - print("-> %s\\%s[%s]=%r" % (root_key_name, key_name, value_name, value)) + print(f"-> {root_key_name}\\{key_name}[{value_name}]={value!r}") finally: my_key.Close() finally: @@ -218,13 +217,13 @@ def UnsetPyKeyVal(key_name, value_name, delete_key=False): try: winreg.DeleteValue(my_key, value_name) if verbose: - print("-> DELETE %s\\%s[%s]" % (root_key_name, key_name, value_name)) + print(f"-> DELETE {root_key_name}\\{key_name}[{value_name}]") finally: my_key.Close() if delete_key: winreg.DeleteKey(root_key, key_name) if verbose: - print("-> DELETE %s\\%s" % (root_key_name, key_name)) + print(f"-> DELETE {root_key_name}\\{key_name}") except OSError as why: winerror = getattr(why, "winerror", why.errno) if winerror != 2: # file not found @@ -391,16 +390,15 @@ def fixup_dbi(): try: if os.path.isfile(this_dest): print( - "Old dbi '%s' already exists - deleting '%s'" - % (this_dest, this_pyd) + f"Old dbi '{this_dest}' already exists - deleting '{this_pyd}'" ) os.remove(this_pyd) else: os.rename(this_pyd, this_dest) - print("renamed '%s'->'%s.old'" % (this_pyd, this_pyd)) + print(f"renamed '{this_pyd}'->'{this_pyd}.old'") file_created(this_pyd + ".old") except OSError as exc: - print("FAILED to rename '%s': %s" % (this_pyd, exc)) + print(f"FAILED to rename '{this_pyd}': {exc}") def install(lib_dir): @@ -448,7 +446,7 @@ def install(lib_dir): dst = os.path.join(dest_dir, base) CopyTo("installing %s" % base, fname, dst) if verbose: - print("Copied %s to %s" % (base, dst)) + print(f"Copied {base} to {dst}") # Register the files with the uninstaller file_created(dst) worked = 1 @@ -536,7 +534,7 @@ def install(lib_dir): make_dir = os.path.join(lib_dir, "win32com", "gen_py") if not os.path.isdir(make_dir): if verbose: - print("Creating directory %s" % (make_dir,)) + print(f"Creating directory {make_dir}") directory_created(make_dir) os.mkdir(make_dir) @@ -569,7 +567,7 @@ def install(lib_dir): print("Shortcut to documentation created") else: if verbose: - print("Can't install shortcuts - %r is not a folder" % (fldr,)) + print(f"Can't install shortcuts - {fldr!r} is not a folder") except Exception as details: print(details) @@ -601,12 +599,12 @@ def uninstall(lib_dir): try: RegisterCOMObjects(False) except Exception as why: - print("Failed to unregister COM objects: %s" % (why,)) + print(f"Failed to unregister COM objects: {why}") try: RegisterHelpFile(False, lib_dir) except Exception as why: - print("Failed to unregister help file: %s" % (why,)) + print(f"Failed to unregister help file: {why}") else: if verbose: print("Unregistered help file") @@ -614,7 +612,7 @@ def uninstall(lib_dir): try: RegisterPythonwin(False, lib_dir) except Exception as why: - print("Failed to unregister Pythonwin: %s" % (why,)) + print(f"Failed to unregister Pythonwin: {why}") else: if verbose: print("Unregistered Pythonwin") @@ -625,7 +623,7 @@ def uninstall(lib_dir): if os.path.isdir(gen_dir): shutil.rmtree(gen_dir) if verbose: - print("Removed directory %s" % (gen_dir,)) + print(f"Removed directory {gen_dir}") # Remove pythonwin compiled "config" files. pywin_dir = os.path.join(lib_dir, "Pythonwin", "pywin") @@ -643,7 +641,7 @@ def uninstall(lib_dir): pass except Exception as why: - print("Failed to remove misc files: %s" % (why,)) + print(f"Failed to remove misc files: {why}") try: fldr = get_shortcuts_folder() @@ -652,9 +650,9 @@ def uninstall(lib_dir): if os.path.isfile(fqlink): os.remove(fqlink) if verbose: - print("Removed %s" % (link,)) + print(f"Removed {link}") except Exception as why: - print("Failed to remove shortcuts: %s" % (why,)) + print(f"Failed to remove shortcuts: {why}") # Now remove the system32 files. files = glob.glob(os.path.join(lib_dir, "pywin32_system32\\*.*")) # Try the system32 directory first - if that fails due to "access denied", @@ -673,11 +671,11 @@ def uninstall(lib_dir): if verbose: print("Removed file %s" % (dst)) except Exception: - print("FAILED to remove %s" % (dst,)) + print(f"FAILED to remove {dst}") if worked: break except Exception as why: - print("FAILED to remove system files: %s" % (why,)) + print(f"FAILED to remove system files: {why}") # NOTE: If this script is run from inside the bdist_wininst created @@ -692,7 +690,7 @@ def uninstall(lib_dir): def verify_destination(location): if not os.path.isdir(location): - raise argparse.ArgumentTypeError('Path "{}" does not exist!'.format(location)) + raise argparse.ArgumentTypeError(f'Path "{location}" does not exist!') return location @@ -756,7 +754,7 @@ def main(): args = parser.parse_args() if not args.quiet: - print("Parsed arguments are: {}".format(args)) + print(f"Parsed arguments are: {args}") if not args.install ^ args.remove: parser.error("You need to either choose to -install or -remove!") diff --git a/pywin32_testall.py b/pywin32_testall.py index a54f9d4fa8..e6c4b7c8c6 100644 --- a/pywin32_testall.py +++ b/pywin32_testall.py @@ -24,7 +24,7 @@ def run_test(script, cmdline_extras): print("--- Running '%s' ---" % script) sys.stdout.flush() result = subprocess.run(cmd, check=False, cwd=dirname) - print("*** Test script '%s' exited with %s" % (script, result.returncode)) + print(f"*** Test script '{script}' exited with {result.returncode}") sys.stdout.flush() if result.returncode: failures.append(script) diff --git a/setup.py b/setup.py index 89faf52458..596fecc14f 100644 --- a/setup.py +++ b/setup.py @@ -184,9 +184,9 @@ def finalize_options(self, build_ext): pch_dir = os.path.join(build_ext.build_temp) if not build_ext.debug: self.extra_compile_args.append("/Zi") - self.extra_compile_args.append("/Fd%s\\%s_vc.pdb" % (pch_dir, self.name)) + self.extra_compile_args.append(f"/Fd{pch_dir}\\{self.name}_vc.pdb") self.extra_link_args.append("/DEBUG") - self.extra_link_args.append("/PDB:%s\\%s.pdb" % (pch_dir, self.name)) + self.extra_link_args.append(f"/PDB:{pch_dir}\\{self.name}.pdb") # enable unwind semantics - some stuff needs it and I can't see # it hurting self.extra_compile_args.append("/EHsc") @@ -206,7 +206,7 @@ def finalize_options(self, build_ext): suffix = "_d" else: suffix = "" - self.extra_link_args.append("/IMPLIB:%s%s.lib" % (implib, suffix)) + self.extra_link_args.append(f"/IMPLIB:{implib}{suffix}.lib") # Try and find the MFC headers, so we can reach inside for # some of the ActiveX support we need. We need to do this late, so # the environment is setup correctly. @@ -371,7 +371,7 @@ def run(self): f.write("%s\n" % build_id) f.close() except OSError as why: - print("Failed to open '%s': %s" % (ver_fname, why)) + print(f"Failed to open '{ver_fname}': {why}") class my_build_ext(build_ext): @@ -433,7 +433,7 @@ def _why_cant_build_extension(self, ext): break else: log.debug("Header '%s' not found in %s", h, look_dirs) - return "The header '%s' can not be located." % (h,) + return f"The header '{h}' can not be located." common_dirs = self.compiler.library_dirs[:] common_dirs += os.environ.get("LIB", "").split(os.pathsep) @@ -451,7 +451,7 @@ def _why_cant_build_extension(self, ext): patched_libs.append(os.path.splitext(os.path.basename(found))[0]) if ext.platforms and self.plat_name not in ext.platforms: - return "Only available on platforms %s" % (ext.platforms,) + return f"Only available on platforms {ext.platforms}" # We update the .libraries list with the resolved library name. # This is really only so "_d" works. @@ -544,9 +544,7 @@ def _check_vc(self): # The afxres.h/atls.lib files aren't always included by default, # so find and add them if vcbase and not atlmfc_found: - atls_lib = glob.glob( - vcbase + r"ATLMFC\lib\{}\atls.lib".format(self.plat_dir) - ) + atls_lib = glob.glob(vcbase + rf"ATLMFC\lib\{self.plat_dir}\atls.lib") if atls_lib: self.library_dirs.append(os.path.dirname(atls_lib[0])) self.include_dirs.append( @@ -607,7 +605,7 @@ def build_extensions(self): if why is not None: self.excluded_extensions.append((ext, why)) assert why, "please give a reason, or None" - print("Skipping %s: %s" % (ext.name, why)) + print(f"Skipping {ext.name}: {why}") continue self.build_exefile(ext) @@ -652,8 +650,9 @@ def build_extensions(self): # typical path on newer Visual Studios - ensure corresponding version redist_globs.append( vcbase[: m.start()] - + r"\VC\Redist\MSVC\%s%s\*\mfc140u.dll" - % (vcverdir or "*\\", self.plat_dir) + + r"\VC\Redist\MSVC\{}{}\*\mfc140u.dll".format( + vcverdir or "*\\", self.plat_dir + ) ) # Only mfcNNNu DLL is required (mfcmNNNX is Windows Forms, rest is ANSI) mfc_contents = next(filter(None, map(glob.glob, redist_globs)), [])[:1] @@ -715,7 +714,7 @@ def build_extension(self, ext): if why is not None: assert why, "please give a reason, or None" self.excluded_extensions.append((ext, why)) - print("Skipping %s: %s" % (ext.name, why)) + print(f"Skipping {ext.name}: {why}") return self.current_extension = ext @@ -760,7 +759,7 @@ def build_extension(self, ext): sys.version_info[1], extra, ) - needed = "%s%s" % (ext.name, extra) + needed = f"{ext.name}{extra}" elif ext.name in ("win32ui",): # This one just needs a copy. created = needed = ext.name + extra @@ -839,12 +838,12 @@ def swig_sources(self, sources, ext=None): # More vile hacks. winxpmodule is built from win32gui.i - # just different #defines are setup for windows.h. new_target = os.path.join( - os.path.dirname(base), "winxpgui_swig%s" % (target_ext,) + os.path.dirname(base), f"winxpgui_swig{target_ext}" ) swig_targets[source] = new_target new_sources.append(new_target) else: - new_target = "%s_swig%s" % (base, target_ext) + new_target = f"{base}_swig{target_ext}" new_sources.append(new_target) swig_targets[source] = new_target else: @@ -932,7 +931,7 @@ def run(self): # may have had 2to3 run over it. filename = os.path.join(self.install_scripts, "pywin32_postinstall.py") if not os.path.isfile(filename): - raise RuntimeError("Can't find '%s'" % (filename,)) + raise RuntimeError(f"Can't find '{filename}'") print("Executing post install script...") # What executable to use? This one I guess. subprocess.Popen( @@ -1033,9 +1032,9 @@ def link( # verstamp must work.) if not skip_verstamp: args = ["py.exe", "-m" "win32verstamp"] - args.append("--version=%s" % (pywin32_version,)) + args.append(f"--version={pywin32_version}") args.append("--comments=https://github.com/mhammond/pywin32") - args.append("--original-filename=%s" % (os.path.basename(output_filename),)) + args.append(f"--original-filename={os.path.basename(output_filename)}") args.append("--product=PyWin32") if "-v" not in sys.argv: args.append("--quiet") @@ -1397,77 +1396,79 @@ def finalize_options(self): "pythoncom", sources=( """ - %(win32com)s/dllmain.cpp %(win32com)s/ErrorUtils.cpp - %(win32com)s/MiscTypes.cpp %(win32com)s/oleargs.cpp - %(win32com)s/PyComHelpers.cpp %(win32com)s/PyFactory.cpp - %(win32com)s/PyGatewayBase.cpp %(win32com)s/PyIBase.cpp - %(win32com)s/PyIClassFactory.cpp %(win32com)s/PyIDispatch.cpp - %(win32com)s/PyIUnknown.cpp %(win32com)s/PyRecord.cpp - %(win32com)s/extensions/PySTGMEDIUM.cpp %(win32com)s/PyStorage.cpp - %(win32com)s/PythonCOM.cpp %(win32com)s/Register.cpp - %(win32com)s/stdafx.cpp %(win32com)s/univgw.cpp - %(win32com)s/univgw_dataconv.cpp %(win32com)s/extensions/PyFUNCDESC.cpp - %(win32com)s/extensions/PyGConnectionPoint.cpp %(win32com)s/extensions/PyGConnectionPointContainer.cpp - %(win32com)s/extensions/PyGEnumVariant.cpp %(win32com)s/extensions/PyGErrorLog.cpp - %(win32com)s/extensions/PyGPersist.cpp %(win32com)s/extensions/PyGPersistPropertyBag.cpp - %(win32com)s/extensions/PyGPersistStorage.cpp %(win32com)s/extensions/PyGPersistStream.cpp - %(win32com)s/extensions/PyGPersistStreamInit.cpp %(win32com)s/extensions/PyGPropertyBag.cpp - %(win32com)s/extensions/PyGStream.cpp %(win32com)s/extensions/PyIBindCtx.cpp - %(win32com)s/extensions/PyICatInformation.cpp %(win32com)s/extensions/PyICatRegister.cpp - %(win32com)s/extensions/PyIConnectionPoint.cpp %(win32com)s/extensions/PyIConnectionPointContainer.cpp - %(win32com)s/extensions/PyICreateTypeInfo.cpp %(win32com)s/extensions/PyICreateTypeLib.cpp - %(win32com)s/extensions/PyICreateTypeLib2.cpp %(win32com)s/extensions/PyIDataObject.cpp - %(win32com)s/extensions/PyIDropSource.cpp %(win32com)s/extensions/PyIDropTarget.cpp - %(win32com)s/extensions/PyIEnumCATEGORYINFO.cpp %(win32com)s/extensions/PyIEnumConnectionPoints.cpp - %(win32com)s/extensions/PyIEnumConnections.cpp %(win32com)s/extensions/PyIEnumFORMATETC.cpp - %(win32com)s/extensions/PyIEnumGUID.cpp %(win32com)s/extensions/PyIEnumSTATPROPSETSTG.cpp - %(win32com)s/extensions/PyIEnumSTATPROPSTG.cpp %(win32com)s/extensions/PyIEnumSTATSTG.cpp - %(win32com)s/extensions/PyIEnumString.cpp %(win32com)s/extensions/PyIEnumVARIANT.cpp - %(win32com)s/extensions/PyIErrorLog.cpp %(win32com)s/extensions/PyIExternalConnection.cpp - %(win32com)s/extensions/PyIGlobalInterfaceTable.cpp %(win32com)s/extensions/PyILockBytes.cpp - %(win32com)s/extensions/PyIMoniker.cpp %(win32com)s/extensions/PyIOleWindow.cpp - %(win32com)s/extensions/PyIPersist.cpp %(win32com)s/extensions/PyIPersistFile.cpp - %(win32com)s/extensions/PyIPersistPropertyBag.cpp %(win32com)s/extensions/PyIPersistStorage.cpp - %(win32com)s/extensions/PyIPersistStream.cpp %(win32com)s/extensions/PyIPersistStreamInit.cpp - %(win32com)s/extensions/PyIPropertyBag.cpp %(win32com)s/extensions/PyIPropertySetStorage.cpp - %(win32com)s/extensions/PyIPropertyStorage.cpp %(win32com)s/extensions/PyIProvideClassInfo.cpp - %(win32com)s/extensions/PyIRunningObjectTable.cpp %(win32com)s/extensions/PyIServiceProvider.cpp - %(win32com)s/extensions/PyIStorage.cpp %(win32com)s/extensions/PyIStream.cpp - %(win32com)s/extensions/PyIType.cpp %(win32com)s/extensions/PyITypeObjects.cpp - %(win32com)s/extensions/PyTYPEATTR.cpp %(win32com)s/extensions/PyVARDESC.cpp - %(win32com)s/extensions/PyICancelMethodCalls.cpp %(win32com)s/extensions/PyIContext.cpp - %(win32com)s/extensions/PyIEnumContextProps.cpp %(win32com)s/extensions/PyIClientSecurity.cpp - %(win32com)s/extensions/PyIServerSecurity.cpp - """ - % dirs + {win32com}/dllmain.cpp {win32com}/ErrorUtils.cpp + {win32com}/MiscTypes.cpp {win32com}/oleargs.cpp + {win32com}/PyComHelpers.cpp {win32com}/PyFactory.cpp + {win32com}/PyGatewayBase.cpp {win32com}/PyIBase.cpp + {win32com}/PyIClassFactory.cpp {win32com}/PyIDispatch.cpp + {win32com}/PyIUnknown.cpp {win32com}/PyRecord.cpp + {win32com}/extensions/PySTGMEDIUM.cpp {win32com}/PyStorage.cpp + {win32com}/PythonCOM.cpp {win32com}/Register.cpp + {win32com}/stdafx.cpp {win32com}/univgw.cpp + {win32com}/univgw_dataconv.cpp {win32com}/extensions/PyFUNCDESC.cpp + {win32com}/extensions/PyGConnectionPoint.cpp {win32com}/extensions/PyGConnectionPointContainer.cpp + {win32com}/extensions/PyGEnumVariant.cpp {win32com}/extensions/PyGErrorLog.cpp + {win32com}/extensions/PyGPersist.cpp {win32com}/extensions/PyGPersistPropertyBag.cpp + {win32com}/extensions/PyGPersistStorage.cpp {win32com}/extensions/PyGPersistStream.cpp + {win32com}/extensions/PyGPersistStreamInit.cpp {win32com}/extensions/PyGPropertyBag.cpp + {win32com}/extensions/PyGStream.cpp {win32com}/extensions/PyIBindCtx.cpp + {win32com}/extensions/PyICatInformation.cpp {win32com}/extensions/PyICatRegister.cpp + {win32com}/extensions/PyIConnectionPoint.cpp {win32com}/extensions/PyIConnectionPointContainer.cpp + {win32com}/extensions/PyICreateTypeInfo.cpp {win32com}/extensions/PyICreateTypeLib.cpp + {win32com}/extensions/PyICreateTypeLib2.cpp {win32com}/extensions/PyIDataObject.cpp + {win32com}/extensions/PyIDropSource.cpp {win32com}/extensions/PyIDropTarget.cpp + {win32com}/extensions/PyIEnumCATEGORYINFO.cpp {win32com}/extensions/PyIEnumConnectionPoints.cpp + {win32com}/extensions/PyIEnumConnections.cpp {win32com}/extensions/PyIEnumFORMATETC.cpp + {win32com}/extensions/PyIEnumGUID.cpp {win32com}/extensions/PyIEnumSTATPROPSETSTG.cpp + {win32com}/extensions/PyIEnumSTATPROPSTG.cpp {win32com}/extensions/PyIEnumSTATSTG.cpp + {win32com}/extensions/PyIEnumString.cpp {win32com}/extensions/PyIEnumVARIANT.cpp + {win32com}/extensions/PyIErrorLog.cpp {win32com}/extensions/PyIExternalConnection.cpp + {win32com}/extensions/PyIGlobalInterfaceTable.cpp {win32com}/extensions/PyILockBytes.cpp + {win32com}/extensions/PyIMoniker.cpp {win32com}/extensions/PyIOleWindow.cpp + {win32com}/extensions/PyIPersist.cpp {win32com}/extensions/PyIPersistFile.cpp + {win32com}/extensions/PyIPersistPropertyBag.cpp {win32com}/extensions/PyIPersistStorage.cpp + {win32com}/extensions/PyIPersistStream.cpp {win32com}/extensions/PyIPersistStreamInit.cpp + {win32com}/extensions/PyIPropertyBag.cpp {win32com}/extensions/PyIPropertySetStorage.cpp + {win32com}/extensions/PyIPropertyStorage.cpp {win32com}/extensions/PyIProvideClassInfo.cpp + {win32com}/extensions/PyIRunningObjectTable.cpp {win32com}/extensions/PyIServiceProvider.cpp + {win32com}/extensions/PyIStorage.cpp {win32com}/extensions/PyIStream.cpp + {win32com}/extensions/PyIType.cpp {win32com}/extensions/PyITypeObjects.cpp + {win32com}/extensions/PyTYPEATTR.cpp {win32com}/extensions/PyVARDESC.cpp + {win32com}/extensions/PyICancelMethodCalls.cpp {win32com}/extensions/PyIContext.cpp + {win32com}/extensions/PyIEnumContextProps.cpp {win32com}/extensions/PyIClientSecurity.cpp + {win32com}/extensions/PyIServerSecurity.cpp + """.format( + **dirs + ) ).split(), depends=( """ - %(win32com)s/include\\propbag.h %(win32com)s/include\\PyComTypeObjects.h - %(win32com)s/include\\PyFactory.h %(win32com)s/include\\PyGConnectionPoint.h - %(win32com)s/include\\PyGConnectionPointContainer.h - %(win32com)s/include\\PyGPersistStorage.h %(win32com)s/include\\PyIBindCtx.h - %(win32com)s/include\\PyICatInformation.h %(win32com)s/include\\PyICatRegister.h - %(win32com)s/include\\PyIDataObject.h %(win32com)s/include\\PyIDropSource.h - %(win32com)s/include\\PyIDropTarget.h %(win32com)s/include\\PyIEnumConnectionPoints.h - %(win32com)s/include\\PyIEnumConnections.h %(win32com)s/include\\PyIEnumFORMATETC.h - %(win32com)s/include\\PyIEnumGUID.h %(win32com)s/include\\PyIEnumSTATPROPSETSTG.h - %(win32com)s/include\\PyIEnumSTATSTG.h %(win32com)s/include\\PyIEnumString.h - %(win32com)s/include\\PyIEnumVARIANT.h %(win32com)s/include\\PyIExternalConnection.h - %(win32com)s/include\\PyIGlobalInterfaceTable.h %(win32com)s/include\\PyILockBytes.h - %(win32com)s/include\\PyIMoniker.h %(win32com)s/include\\PyIOleWindow.h - %(win32com)s/include\\PyIPersist.h %(win32com)s/include\\PyIPersistFile.h - %(win32com)s/include\\PyIPersistStorage.h %(win32com)s/include\\PyIPersistStream.h - %(win32com)s/include\\PyIPersistStreamInit.h %(win32com)s/include\\PyIRunningObjectTable.h - %(win32com)s/include\\PyIStorage.h %(win32com)s/include\\PyIStream.h - %(win32com)s/include\\PythonCOM.h %(win32com)s/include\\PythonCOMRegister.h - %(win32com)s/include\\PythonCOMServer.h %(win32com)s/include\\stdafx.h - %(win32com)s/include\\univgw_dataconv.h - %(win32com)s/include\\PyICancelMethodCalls.h %(win32com)s/include\\PyIContext.h - %(win32com)s/include\\PyIEnumContextProps.h %(win32com)s/include\\PyIClientSecurity.h - %(win32com)s/include\\PyIServerSecurity.h - """ - % dirs + {win32com}/include\\propbag.h {win32com}/include\\PyComTypeObjects.h + {win32com}/include\\PyFactory.h {win32com}/include\\PyGConnectionPoint.h + {win32com}/include\\PyGConnectionPointContainer.h + {win32com}/include\\PyGPersistStorage.h {win32com}/include\\PyIBindCtx.h + {win32com}/include\\PyICatInformation.h {win32com}/include\\PyICatRegister.h + {win32com}/include\\PyIDataObject.h {win32com}/include\\PyIDropSource.h + {win32com}/include\\PyIDropTarget.h {win32com}/include\\PyIEnumConnectionPoints.h + {win32com}/include\\PyIEnumConnections.h {win32com}/include\\PyIEnumFORMATETC.h + {win32com}/include\\PyIEnumGUID.h {win32com}/include\\PyIEnumSTATPROPSETSTG.h + {win32com}/include\\PyIEnumSTATSTG.h {win32com}/include\\PyIEnumString.h + {win32com}/include\\PyIEnumVARIANT.h {win32com}/include\\PyIExternalConnection.h + {win32com}/include\\PyIGlobalInterfaceTable.h {win32com}/include\\PyILockBytes.h + {win32com}/include\\PyIMoniker.h {win32com}/include\\PyIOleWindow.h + {win32com}/include\\PyIPersist.h {win32com}/include\\PyIPersistFile.h + {win32com}/include\\PyIPersistStorage.h {win32com}/include\\PyIPersistStream.h + {win32com}/include\\PyIPersistStreamInit.h {win32com}/include\\PyIRunningObjectTable.h + {win32com}/include\\PyIStorage.h {win32com}/include\\PyIStream.h + {win32com}/include\\PythonCOM.h {win32com}/include\\PythonCOMRegister.h + {win32com}/include\\PythonCOMServer.h {win32com}/include\\stdafx.h + {win32com}/include\\univgw_dataconv.h + {win32com}/include\\PyICancelMethodCalls.h {win32com}/include\\PyIContext.h + {win32com}/include\\PyIEnumContextProps.h {win32com}/include\\PyIClientSecurity.h + {win32com}/include\\PyIServerSecurity.h + """.format( + **dirs + ) ).split(), libraries="oleaut32 ole32 user32 urlmon", export_symbol_file="com/win32com/src/PythonCOM.def", @@ -1484,19 +1485,20 @@ def finalize_options(self): libraries="ACTIVEDS ADSIID user32 advapi32", sources=( """ - %(adsi)s/adsi.i %(adsi)s/adsi.cpp - %(adsi)s/PyIADsContainer.i %(adsi)s/PyIADsContainer.cpp - %(adsi)s/PyIADsUser.i %(adsi)s/PyIADsUser.cpp - %(adsi)s/PyIADsDeleteOps.i %(adsi)s/PyIADsDeleteOps.cpp - %(adsi)s/PyIDirectoryObject.i %(adsi)s/PyIDirectoryObject.cpp - %(adsi)s/PyIDirectorySearch.i %(adsi)s/PyIDirectorySearch.cpp - %(adsi)s/PyIDsObjectPicker.i %(adsi)s/PyIDsObjectPicker.cpp - - %(adsi)s/adsilib.i - %(adsi)s/PyADSIUtil.cpp %(adsi)s/PyDSOPObjects.cpp - %(adsi)s/PyIADs.cpp - """ - % dirs + {adsi}/adsi.i {adsi}/adsi.cpp + {adsi}/PyIADsContainer.i {adsi}/PyIADsContainer.cpp + {adsi}/PyIADsUser.i {adsi}/PyIADsUser.cpp + {adsi}/PyIADsDeleteOps.i {adsi}/PyIADsDeleteOps.cpp + {adsi}/PyIDirectoryObject.i {adsi}/PyIDirectoryObject.cpp + {adsi}/PyIDirectorySearch.i {adsi}/PyIDirectorySearch.cpp + {adsi}/PyIDsObjectPicker.i {adsi}/PyIDsObjectPicker.cpp + + {adsi}/adsilib.i + {adsi}/PyADSIUtil.cpp {adsi}/PyDSOPObjects.cpp + {adsi}/PyIADs.cpp + """.format( + **dirs + ) ).split(), ), WinExt_win32com( @@ -1504,44 +1506,47 @@ def finalize_options(self): pch_header="axcontrol_pch.h", sources=( """ - %(axcontrol)s/AXControl.cpp - %(axcontrol)s/PyIOleControl.cpp %(axcontrol)s/PyIOleControlSite.cpp - %(axcontrol)s/PyIOleInPlaceActiveObject.cpp - %(axcontrol)s/PyIOleInPlaceSiteEx.cpp %(axcontrol)s/PyISpecifyPropertyPages.cpp - %(axcontrol)s/PyIOleInPlaceUIWindow.cpp %(axcontrol)s/PyIOleInPlaceFrame.cpp - %(axcontrol)s/PyIObjectWithSite.cpp %(axcontrol)s/PyIOleInPlaceObject.cpp - %(axcontrol)s/PyIOleInPlaceSiteWindowless.cpp %(axcontrol)s/PyIViewObject.cpp - %(axcontrol)s/PyIOleClientSite.cpp %(axcontrol)s/PyIOleInPlaceSite.cpp - %(axcontrol)s/PyIOleObject.cpp %(axcontrol)s/PyIViewObject2.cpp - %(axcontrol)s/PyIOleCommandTarget.cpp - """ - % dirs + {axcontrol}/AXControl.cpp + {axcontrol}/PyIOleControl.cpp {axcontrol}/PyIOleControlSite.cpp + {axcontrol}/PyIOleInPlaceActiveObject.cpp + {axcontrol}/PyIOleInPlaceSiteEx.cpp {axcontrol}/PyISpecifyPropertyPages.cpp + {axcontrol}/PyIOleInPlaceUIWindow.cpp {axcontrol}/PyIOleInPlaceFrame.cpp + {axcontrol}/PyIObjectWithSite.cpp {axcontrol}/PyIOleInPlaceObject.cpp + {axcontrol}/PyIOleInPlaceSiteWindowless.cpp {axcontrol}/PyIViewObject.cpp + {axcontrol}/PyIOleClientSite.cpp {axcontrol}/PyIOleInPlaceSite.cpp + {axcontrol}/PyIOleObject.cpp {axcontrol}/PyIViewObject2.cpp + {axcontrol}/PyIOleCommandTarget.cpp + """.format( + **dirs + ) ).split(), ), WinExt_win32com( "axscript", sources=( """ - %(axscript)s/AXScript.cpp - %(axscript)s/GUIDS.CPP %(axscript)s/PyGActiveScript.cpp - %(axscript)s/PyGActiveScriptError.cpp %(axscript)s/PyGActiveScriptParse.cpp - %(axscript)s/PyGActiveScriptSite.cpp %(axscript)s/PyGObjectSafety.cpp - %(axscript)s/PyIActiveScript.cpp %(axscript)s/PyIActiveScriptError.cpp - %(axscript)s/PyIActiveScriptParse.cpp %(axscript)s/PyIActiveScriptParseProcedure.cpp - %(axscript)s/PyIActiveScriptSite.cpp %(axscript)s/PyIMultiInfos.cpp - %(axscript)s/PyIObjectSafety.cpp %(axscript)s/stdafx.cpp - """ - % dirs + {axscript}/AXScript.cpp + {axscript}/GUIDS.CPP {axscript}/PyGActiveScript.cpp + {axscript}/PyGActiveScriptError.cpp {axscript}/PyGActiveScriptParse.cpp + {axscript}/PyGActiveScriptSite.cpp {axscript}/PyGObjectSafety.cpp + {axscript}/PyIActiveScript.cpp {axscript}/PyIActiveScriptError.cpp + {axscript}/PyIActiveScriptParse.cpp {axscript}/PyIActiveScriptParseProcedure.cpp + {axscript}/PyIActiveScriptSite.cpp {axscript}/PyIMultiInfos.cpp + {axscript}/PyIObjectSafety.cpp {axscript}/stdafx.cpp + """.format( + **dirs + ) ).split(), depends=( """ - %(axscript)s/AXScript.h - %(axscript)s/guids.h %(axscript)s/PyGActiveScriptError.h - %(axscript)s/PyIActiveScriptError.h %(axscript)s/PyIObjectSafety.h - %(axscript)s/PyIProvideMultipleClassInfo.h - %(axscript)s/stdafx.h - """ - % dirs + {axscript}/AXScript.h + {axscript}/guids.h {axscript}/PyGActiveScriptError.h + {axscript}/PyIActiveScriptError.h {axscript}/PyIObjectSafety.h + {axscript}/PyIProvideMultipleClassInfo.h + {axscript}/stdafx.h + """.format( + **dirs + ) ).split(), extra_compile_args=["-DPY_BUILD_AXSCRIPT"], implib_name="axscript", @@ -1553,52 +1558,53 @@ def finalize_options(self): pch_header="stdafx.h", sources=( """ - %(axdebug)s/AXDebug.cpp - %(axdebug)s/PyIActiveScriptDebug.cpp - %(axdebug)s/PyIActiveScriptErrorDebug.cpp - %(axdebug)s/PyIActiveScriptSiteDebug.cpp - %(axdebug)s/PyIApplicationDebugger.cpp - %(axdebug)s/PyIDebugApplication.cpp - %(axdebug)s/PyIDebugApplicationNode.cpp - %(axdebug)s/PyIDebugApplicationNodeEvents.cpp - %(axdebug)s/PyIDebugApplicationThread.cpp - %(axdebug)s/PyIDebugCodeContext.cpp - %(axdebug)s/PyIDebugDocument.cpp - %(axdebug)s/PyIDebugDocumentContext.cpp - %(axdebug)s/PyIDebugDocumentHelper.cpp - %(axdebug)s/PyIDebugDocumentHost.cpp - %(axdebug)s/PyIDebugDocumentInfo.cpp - %(axdebug)s/PyIDebugDocumentProvider.cpp - %(axdebug)s/PyIDebugDocumentText.cpp - %(axdebug)s/PyIDebugDocumentTextAuthor.cpp - %(axdebug)s/PyIDebugDocumentTextEvents.cpp - %(axdebug)s/PyIDebugDocumentTextExternalAuthor.cpp - %(axdebug)s/PyIDebugExpression.cpp - %(axdebug)s/PyIDebugExpressionCallBack.cpp - %(axdebug)s/PyIDebugExpressionContext.cpp - %(axdebug)s/PyIDebugProperties.cpp - %(axdebug)s/PyIDebugSessionProvider.cpp - %(axdebug)s/PyIDebugStackFrame.cpp - %(axdebug)s/PyIDebugStackFrameSniffer.cpp - %(axdebug)s/PyIDebugStackFrameSnifferEx.cpp - %(axdebug)s/PyIDebugSyncOperation.cpp - %(axdebug)s/PyIEnumDebugApplicationNodes.cpp - %(axdebug)s/PyIEnumDebugCodeContexts.cpp - %(axdebug)s/PyIEnumDebugExpressionContexts.cpp - %(axdebug)s/PyIEnumDebugPropertyInfo.cpp - %(axdebug)s/PyIEnumDebugStackFrames.cpp - %(axdebug)s/PyIEnumRemoteDebugApplications.cpp - %(axdebug)s/PyIEnumRemoteDebugApplicationThreads.cpp - %(axdebug)s/PyIMachineDebugManager.cpp - %(axdebug)s/PyIMachineDebugManagerEvents.cpp - %(axdebug)s/PyIProcessDebugManager.cpp - %(axdebug)s/PyIProvideExpressionContexts.cpp - %(axdebug)s/PyIRemoteDebugApplication.cpp - %(axdebug)s/PyIRemoteDebugApplicationEvents.cpp - %(axdebug)s/PyIRemoteDebugApplicationThread.cpp - %(axdebug)s/stdafx.cpp - """ - % dirs + {axdebug}/AXDebug.cpp + {axdebug}/PyIActiveScriptDebug.cpp + {axdebug}/PyIActiveScriptErrorDebug.cpp + {axdebug}/PyIActiveScriptSiteDebug.cpp + {axdebug}/PyIApplicationDebugger.cpp + {axdebug}/PyIDebugApplication.cpp + {axdebug}/PyIDebugApplicationNode.cpp + {axdebug}/PyIDebugApplicationNodeEvents.cpp + {axdebug}/PyIDebugApplicationThread.cpp + {axdebug}/PyIDebugCodeContext.cpp + {axdebug}/PyIDebugDocument.cpp + {axdebug}/PyIDebugDocumentContext.cpp + {axdebug}/PyIDebugDocumentHelper.cpp + {axdebug}/PyIDebugDocumentHost.cpp + {axdebug}/PyIDebugDocumentInfo.cpp + {axdebug}/PyIDebugDocumentProvider.cpp + {axdebug}/PyIDebugDocumentText.cpp + {axdebug}/PyIDebugDocumentTextAuthor.cpp + {axdebug}/PyIDebugDocumentTextEvents.cpp + {axdebug}/PyIDebugDocumentTextExternalAuthor.cpp + {axdebug}/PyIDebugExpression.cpp + {axdebug}/PyIDebugExpressionCallBack.cpp + {axdebug}/PyIDebugExpressionContext.cpp + {axdebug}/PyIDebugProperties.cpp + {axdebug}/PyIDebugSessionProvider.cpp + {axdebug}/PyIDebugStackFrame.cpp + {axdebug}/PyIDebugStackFrameSniffer.cpp + {axdebug}/PyIDebugStackFrameSnifferEx.cpp + {axdebug}/PyIDebugSyncOperation.cpp + {axdebug}/PyIEnumDebugApplicationNodes.cpp + {axdebug}/PyIEnumDebugCodeContexts.cpp + {axdebug}/PyIEnumDebugExpressionContexts.cpp + {axdebug}/PyIEnumDebugPropertyInfo.cpp + {axdebug}/PyIEnumDebugStackFrames.cpp + {axdebug}/PyIEnumRemoteDebugApplications.cpp + {axdebug}/PyIEnumRemoteDebugApplicationThreads.cpp + {axdebug}/PyIMachineDebugManager.cpp + {axdebug}/PyIMachineDebugManagerEvents.cpp + {axdebug}/PyIProcessDebugManager.cpp + {axdebug}/PyIProvideExpressionContexts.cpp + {axdebug}/PyIRemoteDebugApplication.cpp + {axdebug}/PyIRemoteDebugApplicationEvents.cpp + {axdebug}/PyIRemoteDebugApplicationThread.cpp + {axdebug}/stdafx.cpp + """.format( + **dirs + ) ).split(), ), WinExt_win32com( @@ -1606,80 +1612,84 @@ def finalize_options(self): pch_header="internet_pch.h", sources=( """ - %(internet)s/internet.cpp %(internet)s/PyIDocHostUIHandler.cpp - %(internet)s/PyIHTMLOMWindowServices.cpp %(internet)s/PyIInternetBindInfo.cpp - %(internet)s/PyIInternetPriority.cpp %(internet)s/PyIInternetProtocol.cpp - %(internet)s/PyIInternetProtocolInfo.cpp %(internet)s/PyIInternetProtocolRoot.cpp - %(internet)s/PyIInternetProtocolSink.cpp %(internet)s/PyIInternetSecurityManager.cpp - """ - % dirs + {internet}/internet.cpp {internet}/PyIDocHostUIHandler.cpp + {internet}/PyIHTMLOMWindowServices.cpp {internet}/PyIInternetBindInfo.cpp + {internet}/PyIInternetPriority.cpp {internet}/PyIInternetProtocol.cpp + {internet}/PyIInternetProtocolInfo.cpp {internet}/PyIInternetProtocolRoot.cpp + {internet}/PyIInternetProtocolSink.cpp {internet}/PyIInternetSecurityManager.cpp + """.format( + **dirs + ) ).split(), - depends=["%(internet)s/internet_pch.h" % dirs], + depends=["{internet}/internet_pch.h".format(**dirs)], ), WinExt_win32com( "mapi", libraries="advapi32", pch_header="PythonCOM.h", - include_dirs=["%(mapi)s/mapi_headers" % dirs], + include_dirs=["{mapi}/mapi_headers".format(**dirs)], sources=( """ - %(mapi)s/mapi.i %(mapi)s/mapi.cpp - %(mapi)s/PyIABContainer.i %(mapi)s/PyIABContainer.cpp - %(mapi)s/PyIAddrBook.i %(mapi)s/PyIAddrBook.cpp - %(mapi)s/PyIAttach.i %(mapi)s/PyIAttach.cpp - %(mapi)s/PyIDistList.i %(mapi)s/PyIDistList.cpp - %(mapi)s/PyIMailUser.i %(mapi)s/PyIMailUser.cpp - %(mapi)s/PyIMAPIContainer.i %(mapi)s/PyIMAPIContainer.cpp - %(mapi)s/PyIMAPIFolder.i %(mapi)s/PyIMAPIFolder.cpp - %(mapi)s/PyIMAPIProp.i %(mapi)s/PyIMAPIProp.cpp - %(mapi)s/PyIMAPISession.i %(mapi)s/PyIMAPISession.cpp - %(mapi)s/PyIMAPIStatus.i %(mapi)s/PyIMAPIStatus.cpp - %(mapi)s/PyIMAPITable.i %(mapi)s/PyIMAPITable.cpp - %(mapi)s/PyIMessage.i %(mapi)s/PyIMessage.cpp - %(mapi)s/PyIMsgServiceAdmin.i %(mapi)s/PyIMsgServiceAdmin.cpp - %(mapi)s/PyIMsgServiceAdmin2.i %(mapi)s/PyIMsgServiceAdmin2.cpp - %(mapi)s/PyIProviderAdmin.i %(mapi)s/PyIProviderAdmin.cpp - %(mapi)s/PyIMsgStore.i %(mapi)s/PyIMsgStore.cpp - %(mapi)s/PyIProfAdmin.i %(mapi)s/PyIProfAdmin.cpp - %(mapi)s/PyIProfSect.i %(mapi)s/PyIProfSect.cpp - %(mapi)s/PyIConverterSession.i %(mapi)s/PyIConverterSession.cpp - %(mapi)s/PyIMAPIAdviseSink.cpp - %(mapi)s/mapiutil.cpp - %(mapi)s/mapiguids.cpp - %(mapi)s/mapi_stub_library/MapiStubLibrary.cpp - %(mapi)s/mapi_stub_library/StubUtils.cpp - """ - % dirs + {mapi}/mapi.i {mapi}/mapi.cpp + {mapi}/PyIABContainer.i {mapi}/PyIABContainer.cpp + {mapi}/PyIAddrBook.i {mapi}/PyIAddrBook.cpp + {mapi}/PyIAttach.i {mapi}/PyIAttach.cpp + {mapi}/PyIDistList.i {mapi}/PyIDistList.cpp + {mapi}/PyIMailUser.i {mapi}/PyIMailUser.cpp + {mapi}/PyIMAPIContainer.i {mapi}/PyIMAPIContainer.cpp + {mapi}/PyIMAPIFolder.i {mapi}/PyIMAPIFolder.cpp + {mapi}/PyIMAPIProp.i {mapi}/PyIMAPIProp.cpp + {mapi}/PyIMAPISession.i {mapi}/PyIMAPISession.cpp + {mapi}/PyIMAPIStatus.i {mapi}/PyIMAPIStatus.cpp + {mapi}/PyIMAPITable.i {mapi}/PyIMAPITable.cpp + {mapi}/PyIMessage.i {mapi}/PyIMessage.cpp + {mapi}/PyIMsgServiceAdmin.i {mapi}/PyIMsgServiceAdmin.cpp + {mapi}/PyIMsgServiceAdmin2.i {mapi}/PyIMsgServiceAdmin2.cpp + {mapi}/PyIProviderAdmin.i {mapi}/PyIProviderAdmin.cpp + {mapi}/PyIMsgStore.i {mapi}/PyIMsgStore.cpp + {mapi}/PyIProfAdmin.i {mapi}/PyIProfAdmin.cpp + {mapi}/PyIProfSect.i {mapi}/PyIProfSect.cpp + {mapi}/PyIConverterSession.i {mapi}/PyIConverterSession.cpp + {mapi}/PyIMAPIAdviseSink.cpp + {mapi}/mapiutil.cpp + {mapi}/mapiguids.cpp + {mapi}/mapi_stub_library/MapiStubLibrary.cpp + {mapi}/mapi_stub_library/StubUtils.cpp + """.format( + **dirs + ) ).split(), ), WinExt_win32com_mapi( "exchange", libraries="advapi32 legacy_stdio_definitions", - include_dirs=["%(mapi)s/mapi_headers" % dirs], + include_dirs=["{mapi}/mapi_headers".format(**dirs)], sources=( """ - %(mapi)s/exchange.i %(mapi)s/exchange.cpp - %(mapi)s/PyIExchangeManageStore.i %(mapi)s/PyIExchangeManageStore.cpp - %(mapi)s/PyIExchangeManageStoreEx.i %(mapi)s/PyIExchangeManageStoreEx.cpp - %(mapi)s/mapiutil.cpp - %(mapi)s/exchangeguids.cpp - %(mapi)s/mapi_stub_library/MapiStubLibrary.cpp - %(mapi)s/mapi_stub_library/StubUtils.cpp - """ - % dirs + {mapi}/exchange.i {mapi}/exchange.cpp + {mapi}/PyIExchangeManageStore.i {mapi}/PyIExchangeManageStore.cpp + {mapi}/PyIExchangeManageStoreEx.i {mapi}/PyIExchangeManageStoreEx.cpp + {mapi}/mapiutil.cpp + {mapi}/exchangeguids.cpp + {mapi}/mapi_stub_library/MapiStubLibrary.cpp + {mapi}/mapi_stub_library/StubUtils.cpp + """.format( + **dirs + ) ).split(), ), WinExt_win32com_mapi( "exchdapi", libraries="advapi32", - include_dirs=["%(mapi)s/mapi_headers" % dirs], + include_dirs=["{mapi}/mapi_headers".format(**dirs)], sources=( """ - %(mapi)s/exchdapi.i %(mapi)s/exchdapi.cpp - %(mapi)s/mapi_stub_library/MapiStubLibrary.cpp - %(mapi)s/mapi_stub_library/StubUtils.cpp - """ - % dirs + {mapi}/exchdapi.i {mapi}/exchdapi.cpp + {mapi}/mapi_stub_library/MapiStubLibrary.cpp + {mapi}/mapi_stub_library/StubUtils.cpp + """.format( + **dirs + ) ).split(), ), WinExt_win32com( @@ -1689,79 +1699,80 @@ def finalize_options(self): windows_h_version=0x600, sources=( """ - %(shell)s/PyIActiveDesktop.cpp - %(shell)s/PyIApplicationDestinations.cpp - %(shell)s/PyIApplicationDocumentLists.cpp - %(shell)s/PyIAsyncOperation.cpp - %(shell)s/PyIBrowserFrameOptions.cpp - %(shell)s/PyICategorizer.cpp - %(shell)s/PyICategoryProvider.cpp - %(shell)s/PyIColumnProvider.cpp - %(shell)s/PyIContextMenu.cpp - %(shell)s/PyIContextMenu2.cpp - %(shell)s/PyIContextMenu3.cpp - %(shell)s/PyICopyHook.cpp - %(shell)s/PyICurrentItem.cpp - %(shell)s/PyICustomDestinationList.cpp - %(shell)s/PyIDefaultExtractIconInit.cpp - %(shell)s/PyIDeskBand.cpp - %(shell)s/PyIDisplayItem.cpp - %(shell)s/PyIDockingWindow.cpp - %(shell)s/PyIDropTargetHelper.cpp - %(shell)s/PyIEnumExplorerCommand.cpp - %(shell)s/PyIEnumIDList.cpp - %(shell)s/PyIEnumObjects.cpp - %(shell)s/PyIEnumResources.cpp - %(shell)s/PyIEnumShellItems.cpp - %(shell)s/PyIEmptyVolumeCache.cpp - %(shell)s/PyIEmptyVolumeCacheCallBack.cpp - %(shell)s/PyIExplorerBrowser.cpp - %(shell)s/PyIExplorerBrowserEvents.cpp - %(shell)s/PyIExplorerCommand.cpp - %(shell)s/PyIExplorerCommandProvider.cpp - %(shell)s/PyIExplorerPaneVisibility.cpp - %(shell)s/PyIExtractIcon.cpp - %(shell)s/PyIExtractIconW.cpp - %(shell)s/PyIExtractImage.cpp - %(shell)s/PyIFileOperation.cpp - %(shell)s/PyIFileOperationProgressSink.cpp - %(shell)s/PyIIdentityName.cpp - %(shell)s/PyIInputObject.cpp - %(shell)s/PyIKnownFolder.cpp - %(shell)s/PyIKnownFolderManager.cpp - %(shell)s/PyINameSpaceTreeControl.cpp - %(shell)s/PyIObjectArray.cpp - %(shell)s/PyIObjectCollection.cpp - %(shell)s/PyIPersistFolder.cpp - %(shell)s/PyIPersistFolder2.cpp - %(shell)s/PyIQueryAssociations.cpp - %(shell)s/PyIRelatedItem.cpp - %(shell)s/PyIShellBrowser.cpp - %(shell)s/PyIShellExtInit.cpp - %(shell)s/PyIShellFolder.cpp - %(shell)s/PyIShellFolder2.cpp - %(shell)s/PyIShellIcon.cpp - %(shell)s/PyIShellIconOverlay.cpp - %(shell)s/PyIShellIconOverlayIdentifier.cpp - %(shell)s/PyIShellIconOverlayManager.cpp - %(shell)s/PyIShellItem.cpp - %(shell)s/PyIShellItem2.cpp - %(shell)s/PyIShellItemArray.cpp - %(shell)s/PyIShellItemResources.cpp - %(shell)s/PyIShellLibrary.cpp - %(shell)s/PyIShellLink.cpp - %(shell)s/PyIShellLinkDataList.cpp - %(shell)s/PyIShellView.cpp - %(shell)s/PyITaskbarList.cpp - %(shell)s/PyITransferAdviseSink.cpp - %(shell)s/PyITransferDestination.cpp - %(shell)s/PyITransferMediumItem.cpp - %(shell)s/PyITransferSource.cpp - %(shell)s/PyIUniformResourceLocator.cpp - %(shell)s/shell.cpp - - """ - % dirs + {shell}/PyIActiveDesktop.cpp + {shell}/PyIApplicationDestinations.cpp + {shell}/PyIApplicationDocumentLists.cpp + {shell}/PyIAsyncOperation.cpp + {shell}/PyIBrowserFrameOptions.cpp + {shell}/PyICategorizer.cpp + {shell}/PyICategoryProvider.cpp + {shell}/PyIColumnProvider.cpp + {shell}/PyIContextMenu.cpp + {shell}/PyIContextMenu2.cpp + {shell}/PyIContextMenu3.cpp + {shell}/PyICopyHook.cpp + {shell}/PyICurrentItem.cpp + {shell}/PyICustomDestinationList.cpp + {shell}/PyIDefaultExtractIconInit.cpp + {shell}/PyIDeskBand.cpp + {shell}/PyIDisplayItem.cpp + {shell}/PyIDockingWindow.cpp + {shell}/PyIDropTargetHelper.cpp + {shell}/PyIEnumExplorerCommand.cpp + {shell}/PyIEnumIDList.cpp + {shell}/PyIEnumObjects.cpp + {shell}/PyIEnumResources.cpp + {shell}/PyIEnumShellItems.cpp + {shell}/PyIEmptyVolumeCache.cpp + {shell}/PyIEmptyVolumeCacheCallBack.cpp + {shell}/PyIExplorerBrowser.cpp + {shell}/PyIExplorerBrowserEvents.cpp + {shell}/PyIExplorerCommand.cpp + {shell}/PyIExplorerCommandProvider.cpp + {shell}/PyIExplorerPaneVisibility.cpp + {shell}/PyIExtractIcon.cpp + {shell}/PyIExtractIconW.cpp + {shell}/PyIExtractImage.cpp + {shell}/PyIFileOperation.cpp + {shell}/PyIFileOperationProgressSink.cpp + {shell}/PyIIdentityName.cpp + {shell}/PyIInputObject.cpp + {shell}/PyIKnownFolder.cpp + {shell}/PyIKnownFolderManager.cpp + {shell}/PyINameSpaceTreeControl.cpp + {shell}/PyIObjectArray.cpp + {shell}/PyIObjectCollection.cpp + {shell}/PyIPersistFolder.cpp + {shell}/PyIPersistFolder2.cpp + {shell}/PyIQueryAssociations.cpp + {shell}/PyIRelatedItem.cpp + {shell}/PyIShellBrowser.cpp + {shell}/PyIShellExtInit.cpp + {shell}/PyIShellFolder.cpp + {shell}/PyIShellFolder2.cpp + {shell}/PyIShellIcon.cpp + {shell}/PyIShellIconOverlay.cpp + {shell}/PyIShellIconOverlayIdentifier.cpp + {shell}/PyIShellIconOverlayManager.cpp + {shell}/PyIShellItem.cpp + {shell}/PyIShellItem2.cpp + {shell}/PyIShellItemArray.cpp + {shell}/PyIShellItemResources.cpp + {shell}/PyIShellLibrary.cpp + {shell}/PyIShellLink.cpp + {shell}/PyIShellLinkDataList.cpp + {shell}/PyIShellView.cpp + {shell}/PyITaskbarList.cpp + {shell}/PyITransferAdviseSink.cpp + {shell}/PyITransferDestination.cpp + {shell}/PyITransferMediumItem.cpp + {shell}/PyITransferSource.cpp + {shell}/PyIUniformResourceLocator.cpp + {shell}/shell.cpp + + """.format( + **dirs + ) ).split(), ), WinExt_win32com( @@ -1770,27 +1781,28 @@ def finalize_options(self): delay_load_libraries="shell32", sources=( """ - %(propsys)s/propsys.cpp - %(propsys)s/PyIInitializeWithFile.cpp - %(propsys)s/PyIInitializeWithStream.cpp - %(propsys)s/PyINamedPropertyStore.cpp - %(propsys)s/PyIPropertyDescription.cpp - %(propsys)s/PyIPropertyDescriptionAliasInfo.cpp - %(propsys)s/PyIPropertyDescriptionList.cpp - %(propsys)s/PyIPropertyDescriptionSearchInfo.cpp - %(propsys)s/PyIPropertyEnumType.cpp - %(propsys)s/PyIPropertyEnumTypeList.cpp - %(propsys)s/PyIPropertyStore.cpp - %(propsys)s/PyIPropertyStoreCache.cpp - %(propsys)s/PyIPropertyStoreCapabilities.cpp - %(propsys)s/PyIPropertySystem.cpp - %(propsys)s/PyPROPVARIANT.cpp - %(propsys)s/PyIPersistSerializedPropStorage.cpp - %(propsys)s/PyIObjectWithPropertyKey.cpp - %(propsys)s/PyIPropertyChange.cpp - %(propsys)s/PyIPropertyChangeArray.cpp - """ - % dirs + {propsys}/propsys.cpp + {propsys}/PyIInitializeWithFile.cpp + {propsys}/PyIInitializeWithStream.cpp + {propsys}/PyINamedPropertyStore.cpp + {propsys}/PyIPropertyDescription.cpp + {propsys}/PyIPropertyDescriptionAliasInfo.cpp + {propsys}/PyIPropertyDescriptionList.cpp + {propsys}/PyIPropertyDescriptionSearchInfo.cpp + {propsys}/PyIPropertyEnumType.cpp + {propsys}/PyIPropertyEnumTypeList.cpp + {propsys}/PyIPropertyStore.cpp + {propsys}/PyIPropertyStoreCache.cpp + {propsys}/PyIPropertyStoreCapabilities.cpp + {propsys}/PyIPropertySystem.cpp + {propsys}/PyPROPVARIANT.cpp + {propsys}/PyIPersistSerializedPropStorage.cpp + {propsys}/PyIObjectWithPropertyKey.cpp + {propsys}/PyIPropertyChange.cpp + {propsys}/PyIPropertyChangeArray.cpp + """.format( + **dirs + ) ).split(), implib_name="pypropsys", ), @@ -1799,15 +1811,16 @@ def finalize_options(self): libraries="mstask", sources=( """ - %(taskscheduler)s/taskscheduler.cpp - %(taskscheduler)s/PyIProvideTaskPage.cpp - %(taskscheduler)s/PyIScheduledWorkItem.cpp - %(taskscheduler)s/PyITask.cpp - %(taskscheduler)s/PyITaskScheduler.cpp - %(taskscheduler)s/PyITaskTrigger.cpp - - """ - % dirs + {taskscheduler}/taskscheduler.cpp + {taskscheduler}/PyIProvideTaskPage.cpp + {taskscheduler}/PyIScheduledWorkItem.cpp + {taskscheduler}/PyITask.cpp + {taskscheduler}/PyITaskScheduler.cpp + {taskscheduler}/PyITaskTrigger.cpp + + """.format( + **dirs + ) ).split(), ), WinExt_win32com( @@ -1816,50 +1829,53 @@ def finalize_options(self): pch_header="bits_pch.h", sources=( """ - %(bits)s/bits.cpp - %(bits)s/PyIBackgroundCopyManager.cpp - %(bits)s/PyIBackgroundCopyCallback.cpp - %(bits)s/PyIBackgroundCopyError.cpp - %(bits)s/PyIBackgroundCopyJob.cpp - %(bits)s/PyIBackgroundCopyJob2.cpp - %(bits)s/PyIBackgroundCopyJob3.cpp - %(bits)s/PyIBackgroundCopyFile.cpp - %(bits)s/PyIBackgroundCopyFile2.cpp - %(bits)s/PyIEnumBackgroundCopyJobs.cpp - %(bits)s/PyIEnumBackgroundCopyFiles.cpp - - """ - % dirs + {bits}/bits.cpp + {bits}/PyIBackgroundCopyManager.cpp + {bits}/PyIBackgroundCopyCallback.cpp + {bits}/PyIBackgroundCopyError.cpp + {bits}/PyIBackgroundCopyJob.cpp + {bits}/PyIBackgroundCopyJob2.cpp + {bits}/PyIBackgroundCopyJob3.cpp + {bits}/PyIBackgroundCopyFile.cpp + {bits}/PyIBackgroundCopyFile2.cpp + {bits}/PyIEnumBackgroundCopyJobs.cpp + {bits}/PyIEnumBackgroundCopyFiles.cpp + + """.format( + **dirs + ) ).split(), ), WinExt_win32com( "ifilter", libraries="ntquery", - sources=("%(ifilter)s/PyIFilter.cpp" % dirs).split(), - depends=("%(ifilter)s/PyIFilter.h %(ifilter)s/stdafx.h" % dirs).split(), + sources=("{ifilter}/PyIFilter.cpp".format(**dirs)).split(), + depends=("{ifilter}/PyIFilter.h {ifilter}/stdafx.h".format(**dirs)).split(), ), WinExt_win32com( "directsound", pch_header="directsound_pch.h", sources=( """ - %(directsound)s/directsound.cpp %(directsound)s/PyDSBCAPS.cpp - %(directsound)s/PyDSBUFFERDESC.cpp %(directsound)s/PyDSCAPS.cpp - %(directsound)s/PyDSCBCAPS.cpp %(directsound)s/PyDSCBUFFERDESC.cpp - %(directsound)s/PyDSCCAPS.cpp %(directsound)s/PyIDirectSound.cpp - %(directsound)s/PyIDirectSoundBuffer.cpp %(directsound)s/PyIDirectSoundCapture.cpp - %(directsound)s/PyIDirectSoundCaptureBuffer.cpp - %(directsound)s/PyIDirectSoundNotify.cpp - """ - % dirs + {directsound}/directsound.cpp {directsound}/PyDSBCAPS.cpp + {directsound}/PyDSBUFFERDESC.cpp {directsound}/PyDSCAPS.cpp + {directsound}/PyDSCBCAPS.cpp {directsound}/PyDSCBUFFERDESC.cpp + {directsound}/PyDSCCAPS.cpp {directsound}/PyIDirectSound.cpp + {directsound}/PyIDirectSoundBuffer.cpp {directsound}/PyIDirectSoundCapture.cpp + {directsound}/PyIDirectSoundCaptureBuffer.cpp + {directsound}/PyIDirectSoundNotify.cpp + """.format( + **dirs + ) ).split(), depends=( """ - %(directsound)s/directsound_pch.h %(directsound)s/PyIDirectSound.h - %(directsound)s/PyIDirectSoundBuffer.h %(directsound)s/PyIDirectSoundCapture.h - %(directsound)s/PyIDirectSoundCaptureBuffer.h %(directsound)s/PyIDirectSoundNotify.h - """ - % dirs + {directsound}/directsound_pch.h {directsound}/PyIDirectSound.h + {directsound}/PyIDirectSoundBuffer.h {directsound}/PyIDirectSoundCapture.h + {directsound}/PyIDirectSoundCaptureBuffer.h {directsound}/PyIDirectSoundNotify.h + """.format( + **dirs + ) ).split(), optional_headers=["dsound.h"], libraries="user32 dsound dxguid", @@ -1869,10 +1885,11 @@ def finalize_options(self): libraries="aclui advapi32", sources=( """ - %(authorization)s/authorization.cpp - %(authorization)s/PyGSecurityInformation.cpp - """ - % dirs + {authorization}/authorization.cpp + {authorization}/PyGSecurityInformation.cpp + """.format( + **dirs + ) ).split(), ), ] @@ -2301,7 +2318,7 @@ def maybe_fixup_exes(): options={ "bdist_wininst": { "install_script": "pywin32_postinstall.py", - "title": "pywin32-%s" % (build_id,), + "title": f"pywin32-{build_id}", "user_access_control": "auto", }, }, @@ -2413,7 +2430,7 @@ def maybe_fixup_exes(): skipped_ex = [] print("*** NOTE: The following extensions were NOT %s:" % what_string) for ext, why in excluded_extensions: - print(" %s: %s" % (ext.name, why)) + print(f" {ext.name}: {why}") if ext.name not in skip_whitelist: skipped_ex.append(ext.name) print("For more details on installing the correct libraries and headers,") @@ -2425,4 +2442,4 @@ def maybe_fixup_exes(): ) sys.exit(1000 + len(skipped_ex)) else: - print("All extension modules %s OK" % (what_string,)) + print(f"All extension modules {what_string} OK") diff --git a/win32/Demos/EvtFormatMessage.py b/win32/Demos/EvtFormatMessage.py index 125438692a..ecd5075a78 100644 --- a/win32/Demos/EvtFormatMessage.py +++ b/win32/Demos/EvtFormatMessage.py @@ -21,7 +21,7 @@ def main(): event, win32evtlog.EvtRenderEventValues, Context=context ) - print("Event {}".format(i)) + print(f"Event {i}") level_value, level_variant = result[win32evtlog.EvtSystemLevel] if level_variant != win32evtlog.EvtVarTypeNull: @@ -42,17 +42,17 @@ def main(): win32evtlog.EvtSystemTimeCreated ] if time_created_variant != win32evtlog.EvtVarTypeNull: - print(" Timestamp: {}".format(time_created_value.isoformat())) + print(f" Timestamp: {time_created_value.isoformat()}") computer_value, computer_variant = result[win32evtlog.EvtSystemComputer] if computer_variant != win32evtlog.EvtVarTypeNull: - print(" FQDN: {}".format(computer_value)) + print(f" FQDN: {computer_value}") provider_name_value, provider_name_variant = result[ win32evtlog.EvtSystemProviderName ] if provider_name_variant != win32evtlog.EvtVarTypeNull: - print(" Provider: {}".format(provider_name_value)) + print(f" Provider: {provider_name_value}") try: metadata = win32evtlog.EvtOpenPublisherMetadata(provider_name_value) @@ -69,7 +69,7 @@ def main(): pass else: try: - print(" Message: {}".format(message)) + print(f" Message: {message}") except UnicodeEncodeError: # Obscure error when run under subprocess.Popen(), presumably due to # not knowing the correct encoding for the console. diff --git a/win32/Demos/SystemParametersInfo.py b/win32/Demos/SystemParametersInfo.py index 55a331e673..d748009d81 100644 --- a/win32/Demos/SystemParametersInfo.py +++ b/win32/Demos/SystemParametersInfo.py @@ -46,7 +46,7 @@ # the new value isn't what we set or the original if new_value != orig_value + 1: assert new_value == orig_value - print("Strange - setting %s seems to have been ignored" % (pname,)) + print(f"Strange - setting {pname} seems to have been ignored") win32gui.SystemParametersInfo(cset, orig_value) assert win32gui.SystemParametersInfo(cget) == orig_value diff --git a/win32/Demos/cerapi.py b/win32/Demos/cerapi.py index c5d9316601..385daa1f0b 100644 --- a/win32/Demos/cerapi.py +++ b/win32/Demos/cerapi.py @@ -22,7 +22,7 @@ def DumpPythonRegistry(): print("The remote device does not appear to have Python installed") return 0 path, typ = wincerapi.CeRegQueryValueEx(h, None) - print("The remote PythonPath is '%s'" % (str(path),)) + print(f"The remote PythonPath is '{str(path)}'") h.Close() return 1 @@ -38,7 +38,7 @@ def DumpRegistry(root, level=0): name, data, typ = wincerapi.CeRegEnumValue(root, index) except win32api.error: break - print("%s%s=%s" % (level_prefix, name, repr(str(data)))) + print(f"{level_prefix}{name}={repr(str(data))}") index = index + 1 # Now enumerate all keys. index = 0 @@ -47,7 +47,7 @@ def DumpRegistry(root, level=0): name, klass = wincerapi.CeRegEnumKeyEx(root, index) except win32api.error: break - print("%s%s\\" % (level_prefix, name)) + print(f"{level_prefix}{name}\\") subkey = wincerapi.CeRegOpenKeyEx(root, name) DumpRegistry(subkey, level + 1) index = index + 1 @@ -108,10 +108,7 @@ def DumpRemoteMachineStatus(): batPerc = "unknown" else: batPerc = BatteryLifePercent - print( - "The batteries are at %s%%, and is currently being powered by %s" - % (batPerc, power) - ) + print(f"The batteries are at {batPerc}%, and is currently being powered by {power}") ( memLoad, @@ -142,7 +139,7 @@ def DumpRemoteFolders(): if name[:6] == "CSIDL_": try: loc = str(wincerapi.CeGetSpecialFolderPath(val)) - print("Folder %s is at %s" % (name, loc)) + print(f"Folder {name} is at {loc}") except win32api.error as details: pass @@ -163,7 +160,7 @@ def DumpRemoteFolders(): except win32api.error as xxx_todo_changeme: (rc, fn, msg) = xxx_todo_changeme.args resolved = "#Error - %s" % msg - print("%s->%s" % (fileName, resolved)) + print(f"{fileName}->{resolved}") # print "The start menu is at", # print wincerapi.CeSHGetShortcutTarget("\\Windows\\Start Menu\\Shortcut to Python.exe.lnk") diff --git a/win32/Demos/dde/ddeclient.py b/win32/Demos/dde/ddeclient.py index 32af3130ff..f140e2438b 100644 --- a/win32/Demos/dde/ddeclient.py +++ b/win32/Demos/dde/ddeclient.py @@ -15,4 +15,4 @@ conversation.ConnectTo("RunAny", "ComputeStringLength") s = "abcdefghi" sl = conversation.Request(s) -print('length of "%s" is %s' % (s, sl)) +print(f'length of "{s}" is {sl}') diff --git a/win32/Demos/eventLogDemo.py b/win32/Demos/eventLogDemo.py index 52d3ae9f37..fe796b5458 100644 --- a/win32/Demos/eventLogDemo.py +++ b/win32/Demos/eventLogDemo.py @@ -28,16 +28,17 @@ def ReadLog(computer, logType="Application", dumpEachRecord=0): domain, user, typ = win32security.LookupAccountSid( computer, object.Sid ) - sidDesc = "%s/%s" % (domain, user) + sidDesc = f"{domain}/{user}" except win32security.error: sidDesc = str(object.Sid) - user_desc = "Event associated with user %s" % (sidDesc,) + user_desc = f"Event associated with user {sidDesc}" else: user_desc = None if dumpEachRecord: print( - "Event record from %r generated at %s" - % (object.SourceName, object.TimeGenerated.Format()) + "Event record from {!r} generated at {}".format( + object.SourceName, object.TimeGenerated.Format() + ) ) if user_desc: print(user_desc) diff --git a/win32/Demos/getfilever.py b/win32/Demos/getfilever.py index 721e72f35d..337db45252 100644 --- a/win32/Demos/getfilever.py +++ b/win32/Demos/getfilever.py @@ -28,6 +28,6 @@ for lang, codepage in pairs: print("lang: ", lang, "codepage:", codepage) for ver_string in ver_strings: - str_info = "\\StringFileInfo\\%04X%04X\\%s" % (lang, codepage, ver_string) + str_info = f"\\StringFileInfo\\{lang:04X}{codepage:04X}\\{ver_string}" ## print str_info print(ver_string, repr(win32api.GetFileVersionInfo(fname, str_info))) diff --git a/win32/Demos/rastest.py b/win32/Demos/rastest.py index e737acd9de..52f6a1611a 100644 --- a/win32/Demos/rastest.py +++ b/win32/Demos/rastest.py @@ -157,7 +157,7 @@ def main(): if opt == "-c": hras, rc = Connect(val, bCallback) if hras is not None: - print("hras: 0x%8lx, rc: 0x%04x" % (hras, rc)) + print(f"hras: 0x{hras:8x}, rc: 0x{rc:04x}") if opt == "-d": Disconnect(val) if opt == "-e": diff --git a/win32/Demos/security/localized_names.py b/win32/Demos/security/localized_names.py index 30a0bde6d3..ae2acc28c4 100644 --- a/win32/Demos/security/localized_names.py +++ b/win32/Demos/security/localized_names.py @@ -55,10 +55,10 @@ def main(): targetComputer = None name = LookupUserGroupFromRid(targetComputer, DOMAIN_USER_RID_ADMIN) - print("'Administrator' user name = %s" % (name,)) + print(f"'Administrator' user name = {name}") name = LookupAliasFromRid(targetComputer, DOMAIN_ALIAS_RID_ADMINS) - print("'Administrators' local group/alias name = %s" % (name,)) + print(f"'Administrators' local group/alias name = {name}") if __name__ == "__main__": diff --git a/win32/Demos/security/sspi/fetch_url.py b/win32/Demos/security/sspi/fetch_url.py index 3b43b7e46c..d6addf9eef 100644 --- a/win32/Demos/security/sspi/fetch_url.py +++ b/win32/Demos/security/sspi/fetch_url.py @@ -37,7 +37,7 @@ def open_url(host, url): if options.show_headers: print("Initial response headers:") for name, val in list(resp.msg.items()): - print(" %s: %s" % (name, val)) + print(f" {name}: {val}") if options.show_body: print(body) if resp.status == 401: @@ -61,7 +61,7 @@ def open_url(host, url): if options.show_headers: print("Token dance headers:") for name, val in list(resp.msg.items()): - print(" %s: %s" % (name, val)) + print(f" {name}: {val}") if err == 0: break @@ -85,9 +85,7 @@ def open_url(host, url): data = decodestring(scheme[len(auth_scheme) + 1 :]) break else: - print( - "Could not find scheme '%s' in schemes %r" % (auth_scheme, schemes) - ) + print(f"Could not find scheme '{auth_scheme}' in schemes {schemes!r}") break resp.read() @@ -110,7 +108,7 @@ def open_url(host, url): if options.show_headers: print("Second response headers:") for name, val in list(resp.msg.items()): - print(" %s: %s" % (name, val)) + print(f" {name}: {val}") resp.read(int(resp.msg.get("content-length", 0))) elif resp.status == 500: @@ -156,5 +154,5 @@ def open_url(host, url): if (scheme != "http") or params or query or fragment: parser.error("Scheme must be http, URL must be simple") - print("Opening '%s' from '%s'" % (path, netloc)) + print(f"Opening '{path}' from '{netloc}'") r = open_url(netloc, path) diff --git a/win32/Demos/security/sspi/validate_password.py b/win32/Demos/security/sspi/validate_password.py index 40b6ad5b2f..f99ba681f4 100644 --- a/win32/Demos/security/sspi/validate_password.py +++ b/win32/Demos/security/sspi/validate_password.py @@ -23,7 +23,7 @@ def validate(username, password, domain=""): if __name__ == "__main__": if len(sys.argv) not in [2, 3, 4]: - print("Usage: %s username [password [domain]]" % (__file__,)) + print(f"Usage: {__file__} username [password [domain]]") sys.exit(1) # password and domain are optional! diff --git a/win32/Demos/service/serviceEvents.py b/win32/Demos/service/serviceEvents.py index a62784f954..16598096ef 100644 --- a/win32/Demos/service/serviceEvents.py +++ b/win32/Demos/service/serviceEvents.py @@ -61,15 +61,15 @@ def SvcOtherEx(self, control, event_type, data): # docs for "HandlerEx callback" for more info. if control == win32service.SERVICE_CONTROL_DEVICEEVENT: info = win32gui_struct.UnpackDEV_BROADCAST(data) - msg = "A device event occurred: %x - %s" % (event_type, info) + msg = f"A device event occurred: {event_type:x} - {info}" elif control == win32service.SERVICE_CONTROL_HARDWAREPROFILECHANGE: - msg = "A hardware profile changed: type=%s, data=%s" % (event_type, data) + msg = f"A hardware profile changed: type={event_type}, data={data}" elif control == win32service.SERVICE_CONTROL_POWEREVENT: msg = "A power event: setting %s" % data elif control == win32service.SERVICE_CONTROL_SESSIONCHANGE: # data is a single elt tuple, but this could potentially grow # in the future if the win32 struct does - msg = "Session event: type=%s, data=%s" % (event_type, data) + msg = f"Session event: type={event_type}, data={data}" else: msg = "Other event: code=%d, type=%s, data=%s" % (control, event_type, data) diff --git a/win32/Demos/win32clipboardDemo.py b/win32/Demos/win32clipboardDemo.py index 5794be6ff2..1c1c9f5d0f 100644 --- a/win32/Demos/win32clipboardDemo.py +++ b/win32/Demos/win32clipboardDemo.py @@ -34,7 +34,7 @@ def TestText(): SetClipboardText(text) got = GetClipboardData(win32con.CF_TEXT) # CF_TEXT always gives us 'bytes' back . - assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) + assert got == text_bytes, f"Didnt get the correct result back - '{got!r}'." finally: CloseClipboard() @@ -42,14 +42,12 @@ def TestText(): try: # CF_UNICODE text always gives unicode objects back. got = GetClipboardData(win32con.CF_UNICODETEXT) - assert got == text, "Didnt get the correct result back - '%r'." % (got,) - assert isinstance(got, str), "Didnt get the correct result back - '%r'." % ( - got, - ) + assert got == text, f"Didnt get the correct result back - '{got!r}'." + assert isinstance(got, str), f"Didnt get the correct result back - '{got!r}'." # CF_OEMTEXT is a bytes-based format. got = GetClipboardData(win32con.CF_OEMTEXT) - assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) + assert got == text_bytes, f"Didnt get the correct result back - '{got!r}'." # Unicode tests EmptyClipboard() @@ -59,10 +57,8 @@ def TestText(): SetClipboardData(win32con.CF_UNICODETEXT, text) # Get it in Unicode. got = GetClipboardData(win32con.CF_UNICODETEXT) - assert got == text, "Didnt get the correct result back - '%r'." % (got,) - assert isinstance(got, str), "Didnt get the correct result back - '%r'." % ( - got, - ) + assert got == text, f"Didnt get the correct result back - '{got!r}'." + assert isinstance(got, str), f"Didnt get the correct result back - '{got!r}'." # Close and open the clipboard to ensure auto-conversions take place. finally: @@ -72,14 +68,12 @@ def TestText(): try: # Make sure I can still get the text as bytes got = GetClipboardData(win32con.CF_TEXT) - assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) + assert got == text_bytes, f"Didnt get the correct result back - '{got!r}'." # Make sure we get back the correct types. got = GetClipboardData(win32con.CF_UNICODETEXT) - assert isinstance(got, str), "Didnt get the correct result back - '%r'." % ( - got, - ) + assert isinstance(got, str), f"Didnt get the correct result back - '{got!r}'." got = GetClipboardData(win32con.CF_OEMTEXT) - assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) + assert got == text_bytes, f"Didnt get the correct result back - '{got!r}'." print("Clipboard text tests worked correctly") finally: CloseClipboard() @@ -102,7 +96,7 @@ def TestClipboardEnum(): try: n = GetClipboardFormatName(enum) except error: - n = "unknown (%s)" % (enum,) + n = f"unknown ({enum})" print("Have format", n) print("Clipboard enumerator tests worked correctly") diff --git a/win32/Demos/win32comport_demo.py b/win32/Demos/win32comport_demo.py index 9266292b25..2ee4c3c154 100644 --- a/win32/Demos/win32comport_demo.py +++ b/win32/Demos/win32comport_demo.py @@ -78,7 +78,7 @@ def __init__(self, port): dcb.Parity = NOPARITY dcb.StopBits = ONESTOPBIT SetCommState(self.handle, dcb) - print("Connected to %s at %s baud" % (port, dcb.BaudRate)) + print(f"Connected to {port} at {dcb.BaudRate} baud") def _UserInputReaderThread(self): overlapped = OVERLAPPED() diff --git a/win32/Demos/win32gui_dialog.py b/win32/Demos/win32gui_dialog.py index c4086563b5..522cac6de9 100644 --- a/win32/Demos/win32gui_dialog.py +++ b/win32/Demos/win32gui_dialog.py @@ -52,7 +52,7 @@ def __init__(self, **kw): full_fmt += fmt for name, val in kw.items(): if name not in self.__dict__: - raise ValueError("LVITEM structures do not have an item '%s'" % (name,)) + raise ValueError(f"LVITEM structures do not have an item '{name}'") self.__dict__[name] = val def __setattr__(self, attr, val): diff --git a/win32/Demos/win32netdemo.py b/win32/Demos/win32netdemo.py index e9bca62106..17fcb4ae7e 100644 --- a/win32/Demos/win32netdemo.py +++ b/win32/Demos/win32netdemo.py @@ -74,14 +74,14 @@ def GroupEnum(): data, total, resume = win32net.NetGroupEnum(server, 1, resume) # print "Call to NetGroupEnum obtained %d entries of %d total" % (len(data), total) for group in data: - verbose("Found group %(name)s:%(comment)s " % group) + verbose("Found group {name}:{comment} ".format(**group)) memberresume = 0 while 1: memberdata, total, memberresume = win32net.NetGroupGetUsers( server, group["name"], 0, resume ) for member in memberdata: - verbose(" Member %(name)s" % member) + verbose(" Member {name}".format(**member)) nmembers = nmembers + 1 if memberresume == 0: break @@ -98,7 +98,7 @@ def LocalGroupEnum(): while 1: data, total, resume = win32net.NetLocalGroupEnum(server, 1, resume) for group in data: - verbose("Found group %(name)s:%(comment)s " % group) + verbose("Found group {name}:{comment} ".format(**group)) memberresume = 0 while 1: memberdata, total, memberresume = win32net.NetLocalGroupGetMembers( @@ -110,7 +110,7 @@ def LocalGroupEnum(): server, member["sid"] ) nmembers = nmembers + 1 - verbose(" Member %s (%s)" % (username, member["domainandname"])) + verbose(" Member {} ({})".format(username, member["domainandname"])) if memberresume == 0: break if not resume: @@ -168,7 +168,7 @@ def LocalGroup(uname=None): mem, tot, res = win32net.NetLocalGroupGetMembers(server, group, level) print("members are", mem) if mem[0]["domainandname"] != uname: - print("ERROR: LocalGroup just added %s, but members are %r" % (uname, mem)) + print(f"ERROR: LocalGroup just added {uname}, but members are {mem!r}") # Convert the list of dicts to a list of strings. win32net.NetLocalGroupDelMembers( server, group, [m["domainandname"] for m in mem] @@ -185,7 +185,7 @@ def GetInfo(userName=None): print("Dumping level 3 information about user") info = win32net.NetUserGetInfo(server, userName, 3) for key, val in list(info.items()): - verbose("%s=%s" % (key, val)) + verbose(f"{key}={val}") def SetInfo(userName=None): diff --git a/win32/Demos/win32rcparser_demo.py b/win32/Demos/win32rcparser_demo.py index 6a41d453ac..6d85d3db33 100644 --- a/win32/Demos/win32rcparser_demo.py +++ b/win32/Demos/win32rcparser_demo.py @@ -14,7 +14,7 @@ ) if not os.path.isfile(g_rcname): - raise RuntimeError("Can't locate test.rc (should be at '%s')" % (g_rcname,)) + raise RuntimeError(f"Can't locate test.rc (should be at '{g_rcname}')") class DemoWindow: diff --git a/win32/Demos/win32wnet/testwnet.py b/win32/Demos/win32wnet/testwnet.py index 3b21ac29c4..ca913e58fc 100644 --- a/win32/Demos/win32wnet/testwnet.py +++ b/win32/Demos/win32wnet/testwnet.py @@ -85,14 +85,12 @@ def TestConnection(): fname = os.path.join(localName + "\\", os.listdir(localName + "\\")[0]) try: print( - "Universal name of '%s' is '%s'" - % (fname, win32wnet.WNetGetUniversalName(fname)) + "Universal name of '{}' is '{}'".format( + fname, win32wnet.WNetGetUniversalName(fname) + ) ) except win32wnet.error as details: - print( - "Couldn't get universal name of '%s': %s" - % (fname, details.strerror) - ) + print(f"Couldn't get universal name of '{fname}': {details.strerror}") print("User name for this connection is", win32wnet.WNetGetUser(localName)) finally: win32wnet.WNetCancelConnection2(localName, 0, 0) diff --git a/win32/Lib/netbios.py b/win32/Lib/netbios.py index 3f80b6b62c..fe7f28b36c 100644 --- a/win32/Lib/netbios.py +++ b/win32/Lib/netbios.py @@ -291,5 +291,5 @@ def ACTION_HEADER(): Netbios(ncb) print("Adapter address:", end=" ") for ch in adapter.adapter_address: - print("%02x" % (ch,), end=" ") + print(f"{ch:02x}", end=" ") print() diff --git a/win32/Lib/pywin32_testutil.py b/win32/Lib/pywin32_testutil.py index 41a971967c..eac897c143 100644 --- a/win32/Lib/pywin32_testutil.py +++ b/win32/Lib/pywin32_testutil.py @@ -260,7 +260,7 @@ def addError(self, test, err): self.skips.setdefault(reason, 0) self.skips[reason] += 1 if self.showAll: - self.stream.writeln("SKIP (%s)" % (reason,)) + self.stream.writeln(f"SKIP ({reason})") elif self.dots: self.stream.write("S") self.stream.flush() diff --git a/win32/Lib/pywintypes.py b/win32/Lib/pywintypes.py index 631e7db884..6839664f2c 100644 --- a/win32/Lib/pywintypes.py +++ b/win32/Lib/pywintypes.py @@ -44,9 +44,7 @@ def __import_pywin32_system_module__(modname, globs): if os.path.isfile(found): break else: - raise ImportError( - "Module '%s' isn't in frozen sys.path %s" % (modname, sys.path) - ) + raise ImportError(f"Module '{modname}' isn't in frozen sys.path {sys.path}") else: # First see if it already in our process - if so, we must use that. import _win32sysloader @@ -105,7 +103,7 @@ def __import_pywin32_system_module__(modname, globs): if found is None: # give up in disgust. - raise ImportError("No system module '%s' (%s)" % (modname, filename)) + raise ImportError(f"No system module '{modname}' ({filename})") # After importing the module, sys.modules is updated to the DLL we just # loaded - which isn't what we want. So we update sys.modules to refer to # this module, and update our globals from it. diff --git a/win32/Lib/sspi.py b/win32/Lib/sspi.py index b10f63dbc7..657577831d 100644 --- a/win32/Lib/sspi.py +++ b/win32/Lib/sspi.py @@ -361,7 +361,9 @@ def authorize(self, sec_buffer_in): sspiserver = ServerAuth(ssp, scflags=flags) print( - "SSP : %s (%s)" % (sspiclient.pkg_info["Name"], sspiclient.pkg_info["Comment"]) + "SSP : {} ({})".format( + sspiclient.pkg_info["Name"], sspiclient.pkg_info["Comment"] + ) ) # Perform the authentication dance, each loop exchanging more information diff --git a/win32/Lib/win32evtlogutil.py b/win32/Lib/win32evtlogutil.py index 78e231c994..f7b67a553c 100644 --- a/win32/Lib/win32evtlogutil.py +++ b/win32/Lib/win32evtlogutil.py @@ -43,8 +43,7 @@ def AddSourceToRegistry( # Create a new key for our application hkey = win32api.RegCreateKey( win32con.HKEY_LOCAL_MACHINE, - "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" - % (eventLogType, appName), + f"SYSTEM\\CurrentControlSet\\Services\\EventLog\\{eventLogType}\\{appName}", ) # Add the Event-ID message-file name to the subkey. @@ -100,8 +99,7 @@ def RemoveSourceFromRegistry(appName, eventLogType="Application"): try: win32api.RegDeleteKey( win32con.HKEY_LOCAL_MACHINE, - "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" - % (eventLogType, appName), + f"SYSTEM\\CurrentControlSet\\Services\\EventLog\\{eventLogType}\\{appName}", ) except win32api.error as exc: if exc.winerror != winerror.ERROR_FILE_NOT_FOUND: @@ -148,7 +146,7 @@ def FormatMessage(eventLogRecord, logType="Application"): # key to look under for the name of the message DLL that contains # the messages we need to extract with FormatMessage. So first get # the event log source name... - keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % ( + keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\{}\\{}".format( logType, eventLogRecord.SourceName, ) diff --git a/win32/Lib/win32rcparser.py b/win32/Lib/win32rcparser.py index 627cea1baf..629fcd23a8 100644 --- a/win32/Lib/win32rcparser.py +++ b/win32/Lib/win32rcparser.py @@ -166,7 +166,7 @@ def __init__(self, id, idNum, value): self.value = value def __repr__(self): - return "StringDef(%r, %r, %r)" % (self.id, self.idNum, self.value) + return f"StringDef({self.id!r}, {self.idNum!r}, {self.value!r})" class RCParser: @@ -204,10 +204,7 @@ def ungetToken(self): def getCheckToken(self, expected): tok = self.getToken() - assert tok == expected, "Expected token '%s', but got token '%s'!" % ( - expected, - tok, - ) + assert tok == expected, f"Expected token '{expected}', but got token '{tok}'!" return tok def getCommaToken(self): @@ -324,7 +321,7 @@ def parse(self): else: rp = id_parsers.get(self.token) if rp is not None: - self.debug("Dispatching '%s'" % (self.token,)) + self.debug(f"Dispatching '{self.token}'") rp(resource_id) else: # We don't know what the resource type is, but we @@ -639,7 +636,7 @@ def GenerateFrozenResource(rc_name, output_name, h_name=None): out.write("class FakeParser:\n") for name in "dialogs", "ids", "names", "bitmaps", "icons", "stringTable": - out.write("\t%s = \\\n" % (name,)) + out.write(f"\t{name} = \\\n") pprint.pprint(getattr(rcp, name), out) out.write("\n") @@ -665,11 +662,11 @@ def GenerateFrozenResource(rc_name, output_name, h_name=None): pprint.pprint(ddef) print() for id, sdef in resources.stringTable.items(): - print("String %s=%r" % (id, sdef.value)) + print(f"String {id}={sdef.value!r}") print() for id, sdef in resources.bitmaps.items(): - print("Bitmap %s=%r" % (id, sdef)) + print(f"Bitmap {id}={sdef!r}") print() for id, sdef in resources.icons.items(): - print("Icon %s=%r" % (id, sdef)) + print(f"Icon {id}={sdef!r}") print() diff --git a/win32/Lib/win32serviceutil.py b/win32/Lib/win32serviceutil.py index 4778c630c9..19b425b065 100644 --- a/win32/Lib/win32serviceutil.py +++ b/win32/Lib/win32serviceutil.py @@ -592,7 +592,7 @@ def DebugService(cls, argv=[]): global g_debugService - print("Debugging service %s - press Ctrl+C to stop." % (cls._svc_name_,)) + print(f"Debugging service {cls._svc_name_} - press Ctrl+C to stop.") servicemanager.Debugging(True) servicemanager.PrepareToHostSingle(cls) g_debugService = cls(argv) @@ -801,7 +801,7 @@ def HandleCommandLine( sys.exit(1) raise try: - os.system("%s -debug %s %s" % (exeName, serviceName, svcArgs)) + os.system(f"{exeName} -debug {serviceName} {svcArgs}") # ^C is used to kill the debug service. Sometimes Python also gets # interrupted - ignore it... except KeyboardInterrupt: @@ -832,7 +832,7 @@ def HandleCommandLine( description = cls._svc_description_ except AttributeError: description = None - print("Installing service %s" % (serviceName,)) + print(f"Installing service {serviceName}") # Note that we install the service before calling the custom option # handler, so if the custom handler fails, we have an installed service (from NT's POV) # but is unlikely to work, as the Python code controlling it failed. Therefore diff --git a/win32/Lib/win32timezone.py b/win32/Lib/win32timezone.py index 442cb1f6d2..8af89c1df5 100644 --- a/win32/Lib/win32timezone.py +++ b/win32/Lib/win32timezone.py @@ -583,7 +583,7 @@ def _LoadDynamicInfoFromKey(self, key): ) def __repr__(self): - result = "%s(%s" % (self.__class__.__name__, repr(self.timeZoneName)) + result = f"{self.__class__.__name__}({repr(self.timeZoneName)}" if self.fixedStandardTime: result += ", True" result += ")" diff --git a/win32/Lib/win32verstamp.py b/win32/Lib/win32verstamp.py index 64038cd233..a705c967fd 100644 --- a/win32/Lib/win32verstamp.py +++ b/win32/Lib/win32verstamp.py @@ -127,7 +127,7 @@ def stamp(pathname, options): f = open(pathname, "a+b") f.close() except OSError as why: - print("WARNING: File %s could not be opened - %s" % (pathname, why)) + print(f"WARNING: File {pathname} could not be opened - {why}") ver = options.version try: diff --git a/win32/scripts/VersionStamp/BrandProject.py b/win32/scripts/VersionStamp/BrandProject.py index cfa9ca0c99..2612dbc94b 100644 --- a/win32/scripts/VersionStamp/BrandProject.py +++ b/win32/scripts/VersionStamp/BrandProject.py @@ -39,9 +39,9 @@ def BrandProject( def usage(msg): print(msg) print( - """\ -%s Usage: -%s [options] vssProject descFile stampPath + f"""\ +{os.path.basename(sys.argv[0])} Usage: +{os.path.basename(sys.argv[0])} [options] vssProject descFile stampPath Automatically brand a VSS project with an automatically incremented build number, and stamp DLL/EXE files with the build number. @@ -57,7 +57,6 @@ def usage(msg): -f infile=outfile - Substitute special VSS labels in the specified text file with the text extracted from VSS. """ - % (os.path.basename(sys.argv[0]), os.path.basename(sys.argv[0])) ) sys.exit(1) diff --git a/win32/scripts/VersionStamp/vssutil.py b/win32/scripts/VersionStamp/vssutil.py index 23be6278d4..e04e2564a0 100644 --- a/win32/scripts/VersionStamp/vssutil.py +++ b/win32/scripts/VersionStamp/vssutil.py @@ -89,10 +89,9 @@ def VssLog(project, linePrefix="", noLabels=5, maxItems=150): if str(itemDesc[-4:]) == ".dsp": continue if i.Comment: - commentDesc = "\n%s\t%s" % (linePrefix, i.Comment) + commentDesc = f"\n{linePrefix}\t{i.Comment}" lines.append( - "%s%s\t%s%s" - % ( + "{}{}\t{}{}".format( linePrefix, time.asctime(time.localtime(int(i.Date))), itemDesc, @@ -181,13 +180,13 @@ def MakeNewBuildNo(project, buildDesc=None, auto=0, bRebrand=0): from pywin.mfc import dialog buildNo = dialog.GetSimpleInput( - "Enter new build number", buildNo, "%s - Prev: %s" % (project, oldBuild) + "Enter new build number", buildNo, f"{project} - Prev: {oldBuild}" ) if buildNo is None: return - i.Label(buildNo, "Build %s: %s" % (buildNo, buildDesc)) + i.Label(buildNo, f"Build {buildNo}: {buildDesc}") if auto: - print("Branded project %s with label %s" % (project, buildNo)) + print(f"Branded project {project} with label {buildNo}") return buildNo diff --git a/win32/scripts/backupEventLog.py b/win32/scripts/backupEventLog.py index 6dd37bb227..0f3dbf9b93 100644 --- a/win32/scripts/backupEventLog.py +++ b/win32/scripts/backupEventLog.py @@ -18,7 +18,7 @@ def BackupClearLog(logType): try: fname = os.path.join( win32api.GetTempPath(), - "%s%s-%s" % (datePrefix, index, logType) + ".evt", + f"{datePrefix}{index}-{logType}" + ".evt", ) os.stat(fname) except OSError: @@ -35,7 +35,7 @@ def BackupClearLog(logType): print("No records in event log %s - not backed up" % logType) return win32evtlog.ClearEventLog(hlog, fname) - print("Backed up %s log to %s" % (logType, fname)) + print(f"Backed up {logType} log to {fname}") finally: win32evtlog.CloseEventLog(hlog) diff --git a/win32/scripts/killProcName.py b/win32/scripts/killProcName.py index c9b399ff8b..4011241523 100644 --- a/win32/scripts/killProcName.py +++ b/win32/scripts/killProcName.py @@ -38,7 +38,7 @@ def killProcName(procname): if len(pids) == 0: result = "Can't find %s" % procname elif len(pids) > 1: - result = "Found too many %s's - pids=`%s`" % (procname, pids) + result = f"Found too many {procname}'s - pids=`{pids}`" else: handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, pids[0]) win32api.TerminateProcess(handle, 0) diff --git a/win32/scripts/regsetup.py b/win32/scripts/regsetup.py index 20a4f84719..fd0f636a06 100644 --- a/win32/scripts/regsetup.py +++ b/win32/scripts/regsetup.py @@ -120,7 +120,7 @@ def FindAppPath(appName, knownFileName, searchPaths): # Found it return os.path.abspath(pathLook) raise error( - "The file %s can not be located for application %s" % (knownFileName, appName) + f"The file {knownFileName} can not be located for application {appName}" ) @@ -209,7 +209,7 @@ def LocateFileName(fileNamesString, searchPaths): # Display a common dialog to locate the file. flags = win32con.OFN_FILEMUSTEXIST ext = os.path.splitext(fileName)[1] - filter = "Files of requested type (*%s)|*%s||" % (ext, ext) + filter = f"Files of requested type (*{ext})|*{ext}||" dlg = win32ui.CreateFileDialog(1, None, fileName, flags, filter, None) dlg.SetOFNTitle("Locate " + fileName) if dlg.DoModal() != win32con.IDOK: @@ -307,9 +307,7 @@ def FindRegisterPackage(packageName, knownFile, searchPaths, registryAppName=Non regutil.RegisterNamedPath(registryAppName, pathAdd) return pathLook except error as details: - print( - "*** The %s package could not be registered - %s" % (packageName, details) - ) + print(f"*** The {packageName} package could not be registered - {details}") print( "*** Please ensure you have passed the correct paths on the command line." ) diff --git a/win32/scripts/setup_d.py b/win32/scripts/setup_d.py index 8d009dfa59..caf10f9a7c 100644 --- a/win32/scripts/setup_d.py +++ b/win32/scripts/setup_d.py @@ -32,7 +32,7 @@ def usage_and_die(rc): import pythoncom except ImportError as details: print("Could not import the release version of pythoncom") - print("The error details are: %s" % (details,)) + print(f"The error details are: {details}") print("Please correct this error and rerun the script") usage_and_die(2) @@ -40,7 +40,7 @@ def usage_and_die(rc): import pywintypes except ImportError as details: print("Could not import the release version of pywintypes") - print("The error details are: %s" % (details,)) + print(f"The error details are: {details}") print("Please correct this error and rerun the script") usage_and_die(2) @@ -50,16 +50,17 @@ def _docopy(src, dest): if not os.path.isfile(src): src = os.path.join(os.path.split(sys.argv[0])[0], src) print( - "Can not find %s or %s to copy" - % (os.path.abspath(orig_src), os.path.abspath(src)) + "Can not find {} or {} to copy".format( + os.path.abspath(orig_src), os.path.abspath(src) + ) ) return 0 try: shutil.copy(src, dest) - print("Copied %s -> %s" % (src, dest)) + print(f"Copied {src} -> {dest}") return 1 except: - print("Error copying '%s' -> '%s'" % (src, dest)) + print(f"Error copying '{src}' -> '{dest}'") print(str(sys.exc_info[1])) usage_and_die(3) @@ -69,25 +70,25 @@ def _doregister(mod_name, dll_name): try: key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, - "Software\\Python\\PythonCore\\%s\\Modules\\%s" % (sys.winver, mod_name), + f"Software\\Python\\PythonCore\\{sys.winver}\\Modules\\{mod_name}", ) except winreg.error: try: key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, - "Software\\Python\\PythonCore\\%s\\Modules\\%s" - % (sys.winver, mod_name), + f"Software\\Python\\PythonCore\\{sys.winver}\\Modules\\{mod_name}", ) except winreg.error: print( - "Could not find the existing '%s' module registered in the registry" - % (mod_name,) + "Could not find the existing '{}' module registered in the registry".format( + mod_name + ) ) usage_and_die(4) # Create the debug key. sub_key = winreg.CreateKey(key, "Debug") winreg.SetValue(sub_key, None, winreg.REG_SZ, dll_name) - print("Registered '%s' in the registry" % (dll_name,)) + print(f"Registered '{dll_name}' in the registry") def _domodule(mod_name, release_mod_filename): diff --git a/win32/test/test_odbc.py b/win32/test/test_odbc.py index 8cba6310f3..b40a3f6c51 100644 --- a/win32/test/test_odbc.py +++ b/win32/test/test_odbc.py @@ -43,8 +43,10 @@ def setUp(self): newdb.Close() - conn_str = "Driver={Microsoft Access Driver (*.mdb)};dbq=%s;Uid=;Pwd=;" % ( - self.db_filename, + conn_str = ( + "Driver={{Microsoft Access Driver (*.mdb)}};dbq={};Uid=;Pwd=;".format( + self.db_filename, + ) ) ## print 'Connection string:', conn_str self.conn = odbc.odbc(conn_str) @@ -163,14 +165,13 @@ def _test_val(self, fieldName, value): self.cur.execute("delete from %s where userid='Frank'" % self.tablename) self.assertEqual( self.cur.execute( - "insert into %s (userid, %s) values (?,?)" - % (self.tablename, fieldName), + f"insert into {self.tablename} (userid, {fieldName}) values (?,?)", ["Frank", value], ), 1, ) self.cur.execute( - "select %s from %s where userid = ?" % (fieldName, self.tablename), + f"select {fieldName} from {self.tablename} where userid = ?", ["Frank"], ) rows = self.cur.fetchmany() diff --git a/win32/test/test_pywintypes.py b/win32/test/test_pywintypes.py index 313171c63e..67c4a5afe5 100644 --- a/win32/test/test_pywintypes.py +++ b/win32/test/test_pywintypes.py @@ -17,7 +17,7 @@ def testPyTimeFormat(self): for fmt in format_strings.split(): v1 = pytime_current.Format(fmt) v2 = time.strftime(fmt, struct_current) - self.assertEqual(v1, v2, "format %s failed - %r != %r" % (fmt, v1, v2)) + self.assertEqual(v1, v2, f"format {fmt} failed - {v1!r} != {v2!r}") def testPyTimePrint(self): # This used to crash with an invalid, or too early time. diff --git a/win32/test/test_sspi.py b/win32/test/test_sspi.py index a9db878e93..85d20587b6 100644 --- a/win32/test/test_sspi.py +++ b/win32/test/test_sspi.py @@ -30,7 +30,7 @@ class TestSSPI(unittest.TestCase): def assertRaisesHRESULT(self, hr, func, *args): try: return func(*args) - raise RuntimeError("expecting %s failure" % (hr,)) + raise RuntimeError(f"expecting {hr} failure") except win32security.error as exc: self.assertEqual(exc.winerror, hr) diff --git a/win32/test/test_win32api.py b/win32/test/test_win32api.py index 81b2fe5ef9..d43b964af3 100644 --- a/win32/test/test_win32api.py +++ b/win32/test/test_win32api.py @@ -19,7 +19,7 @@ def testGetCurrentUser(self): if domain == "NT AUTHORITY": # Running as a service account, so the comparison will fail raise TestSkipped("running as service account") - name = "%s\\%s" % (domain, win32api.GetUserName()) + name = f"{domain}\\{win32api.GetUserName()}" self.assertEqual(name, win32api.GetUserNameEx(win32api.NameSamCompatible)) @@ -149,17 +149,17 @@ def testShortLongPathNames(self): long_name = win32api.GetLongPathName(short_name).lower() self.assertTrue( long_name == fname, - "Expected long name ('%s') to be original name ('%s')" % (long_name, fname), + f"Expected long name ('{long_name}') to be original name ('{fname}')", ) self.assertEqual(long_name, win32api.GetLongPathNameW(short_name).lower()) long_name = win32api.GetLongPathNameW(short_name).lower() self.assertTrue( isinstance(long_name, str), - "GetLongPathNameW returned type '%s'" % (type(long_name),), + f"GetLongPathNameW returned type '{type(long_name)}'", ) self.assertTrue( long_name == fname, - "Expected long name ('%s') to be original name ('%s')" % (long_name, fname), + f"Expected long name ('{long_name}') to be original name ('{fname}')", ) def testShortUnicodeNames(self): @@ -174,17 +174,17 @@ def testShortUnicodeNames(self): long_name = win32api.GetLongPathName(short_name).lower() self.assertTrue( long_name == fname, - "Expected long name ('%s') to be original name ('%s')" % (long_name, fname), + f"Expected long name ('{long_name}') to be original name ('{fname}')", ) self.assertEqual(long_name, win32api.GetLongPathNameW(short_name).lower()) long_name = win32api.GetLongPathNameW(short_name).lower() self.assertTrue( isinstance(long_name, str), - "GetLongPathNameW returned type '%s'" % (type(long_name),), + f"GetLongPathNameW returned type '{type(long_name)}'", ) self.assertTrue( long_name == fname, - "Expected long name ('%s') to be original name ('%s')" % (long_name, fname), + f"Expected long name ('{long_name}') to be original name ('{fname}')", ) def testLongLongPathNames(self): diff --git a/win32/test/test_win32file.py b/win32/test/test_win32file.py index 9c0b37488f..0088d6dff3 100644 --- a/win32/test/test_win32file.py +++ b/win32/test/test_win32file.py @@ -229,12 +229,12 @@ def testFileTimes(self): ct, at, wt = win32file.GetFileTime(f) self.assertTrue( ct >= now, - "File was created in the past - now=%s, created=%s" % (now, ct), + f"File was created in the past - now={now}, created={ct}", ) self.assertTrue(now <= ct <= nowish, (now, ct)) self.assertTrue( wt >= now, - "File was written-to in the past now=%s, written=%s" % (now, wt), + f"File was written-to in the past now={now}, written={wt}", ) self.assertTrue(now <= wt <= nowish, (now, wt)) diff --git a/win32/test/test_win32guistruct.py b/win32/test/test_win32guistruct.py index 0c1d1d1c09..2cea9d5fbc 100644 --- a/win32/test/test_win32guistruct.py +++ b/win32/test/test_win32guistruct.py @@ -11,7 +11,7 @@ class TestBase(unittest.TestCase): def assertDictEquals(self, d, **kw): checked = {} for n, v in kw.items(): - self.assertEqual(v, d[n], "'%s' doesn't match: %r != %r" % (n, v, d[n])) + self.assertEqual(v, d[n], f"'{n}' doesn't match: {v!r} != {d[n]!r}") checked[n] = True checked_keys = list(checked.keys()) passed_keys = list(kw.keys()) diff --git a/win32/test/test_win32pipe.py b/win32/test/test_win32pipe.py index 00a474caba..841dee84a9 100644 --- a/win32/test/test_win32pipe.py +++ b/win32/test/test_win32pipe.py @@ -17,7 +17,7 @@ def _serverThread(self, pipe_handle, event, wait_time): # just do one connection and terminate. hr = win32pipe.ConnectNamedPipe(pipe_handle) self.assertTrue( - hr in (0, winerror.ERROR_PIPE_CONNECTED), "Got error code 0x%x" % (hr,) + hr in (0, winerror.ERROR_PIPE_CONNECTED), f"Got error code 0x{hr:x}" ) hr, got = win32file.ReadFile(pipe_handle, 100) self.assertEqual(got, b"foo\0bar") diff --git a/win32/test/test_win32trace.py b/win32/test/test_win32trace.py index b06a83462e..89d53b9ea3 100644 --- a/win32/test/test_win32trace.py +++ b/win32/test/test_win32trace.py @@ -258,8 +258,9 @@ def __init__(self, threadCount): def start(self): procHandle, threadHandle, procId, threadId = win32process.CreateProcess( None, # appName - 'python.exe "%s" /run_test_process %s %s' - % (this_file, self.BucketCount, self.threadCount), + 'python.exe "{}" /run_test_process {} {}'.format( + this_file, self.BucketCount, self.threadCount + ), None, # process security None, # thread security 0, # inherit handles diff --git a/win32/test/test_win32wnet.py b/win32/test/test_win32wnet.py index 316c2e29dd..0c0b6150c3 100644 --- a/win32/test/test_win32wnet.py +++ b/win32/test/test_win32wnet.py @@ -59,20 +59,20 @@ def _checkItemAttributes(self, item, attrs): val = getattr(item, attr) if typ is int: self.assertTrue( - isinstance(val, int), "Attr %r has value %r" % (attr, val) + isinstance(val, int), f"Attr {attr!r} has value {val!r}" ) new_val = val + 1 elif typ is str: if val is not None: # must be string self.assertTrue( - isinstance(val, str), "Attr %r has value %r" % (attr, val) + isinstance(val, str), f"Attr {attr!r} has value {val!r}" ) new_val = val + " new value" else: new_val = "new value" else: - self.fail("Don't know what %s is" % (typ,)) + self.fail(f"Don't know what {typ} is") # set the attribute just to make sure we can. setattr(item, attr, new_val) diff --git a/win32/test/testall.py b/win32/test/testall.py index 85adf736e3..72aa42fc84 100644 --- a/win32/test/testall.py +++ b/win32/test/testall.py @@ -85,7 +85,7 @@ def find_exception_in_output(data): class TestRunner: def __init__(self, argv): self.argv = argv - self.__name__ = "Test Runner for cmdline {}".format(argv) + self.__name__ = f"Test Runner for cmdline {argv}" def __call__(self): import subprocess @@ -103,7 +103,7 @@ def __call__(self): if reconstituted is not None: raise reconstituted raise AssertionError( - "%s failed with exit code %s. Output is:\n%s" % (base, rc, output) + f"{base} failed with exit code {rc}. Output is:\n{output}" ) From 47229235b0992563a7f6f6ca9de4c8cb3573b8b3 Mon Sep 17 00:00:00 2001 From: Avasam Date: Wed, 1 Nov 2023 13:13:48 -0400 Subject: [PATCH 13/22] Fix some importlib usages (#2123) --- isapi/install.py | 7 +------ win32/Lib/win32serviceutil.py | 2 +- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/isapi/install.py b/isapi/install.py index 0631b50ed4..f28cf2ea0c 100644 --- a/isapi/install.py +++ b/isapi/install.py @@ -39,9 +39,6 @@ _DEFAULT_ENABLE_DIR_BROWSING = False _DEFAULT_ENABLE_DEFAULT_DOC = False -_extensions = [ext for ext, _, _ in importlib.machinery.EXTENSION_SUFFIXES] -is_debug_build = "_d.pyd" in _extensions - this_dir = os.path.abspath(os.path.dirname(__file__)) @@ -504,9 +501,7 @@ def DeleteExtensionFileRecords(params, options): def CheckLoaderModule(dll_name): - suffix = "" - if is_debug_build: - suffix = "_d" + suffix = "_d" if "_d.pyd" in importlib.machinery.EXTENSION_SUFFIXES else "" template = os.path.join(this_dir, "PyISAPI_loader" + suffix + ".dll") if not os.path.isfile(template): raise ConfigurationError(f"Template loader '{template}' does not exist") diff --git a/win32/Lib/win32serviceutil.py b/win32/Lib/win32serviceutil.py index 19b425b065..16de6814c5 100644 --- a/win32/Lib/win32serviceutil.py +++ b/win32/Lib/win32serviceutil.py @@ -6,7 +6,7 @@ # when things go wrong - eg, not enough permissions to hit the # registry etc. -import importlib +import importlib.machinery import os import sys import warnings From 9f24116d5825803b67ca88a5c5d0186eaa8fd6f7 Mon Sep 17 00:00:00 2001 From: Avasam Date: Wed, 1 Nov 2023 13:16:19 -0400 Subject: [PATCH 14/22] Removed unused imports found by type-checkers (#2124) --- Pythonwin/pywin/Demos/app/helloapp.py | 2 +- Pythonwin/pywin/Demos/dyndlg.py | 2 +- Pythonwin/pywin/Demos/ocx/msoffice.py | 3 +-- Pythonwin/pywin/Demos/threadedgui.py | 2 +- Pythonwin/pywin/debugger/debugger.py | 2 +- Pythonwin/pywin/docking/DockingBar.py | 2 -- .../framework/editor/color/coloreditor.py | 8 +------ Pythonwin/pywin/framework/editor/configui.py | 11 +--------- Pythonwin/pywin/framework/editor/editor.py | 4 +--- Pythonwin/pywin/framework/winout.py | 21 +++++++------------ Pythonwin/pywin/scintilla/view.py | 5 ++--- Pythonwin/pywin/tools/hierlist.py | 2 +- Pythonwin/pywin/tools/regedit.py | 4 ---- com/win32comext/axdebug/Test/host.py | 6 ++---- com/win32comext/axdebug/contexts.py | 2 +- com/win32comext/axdebug/debugger.py | 2 +- com/win32comext/axdebug/documents.py | 4 ++-- com/win32comext/axdebug/expressions.py | 2 +- com/win32comext/axscript/client/debug.py | 3 +-- isapi/test/extension_simple.py | 7 +------ 20 files changed, 28 insertions(+), 66 deletions(-) diff --git a/Pythonwin/pywin/Demos/app/helloapp.py b/Pythonwin/pywin/Demos/app/helloapp.py index 876f16f71d..6ac35b431a 100644 --- a/Pythonwin/pywin/Demos/app/helloapp.py +++ b/Pythonwin/pywin/Demos/app/helloapp.py @@ -14,7 +14,7 @@ import win32con import win32ui -from pywin.mfc import afxres, dialog, window +from pywin.mfc import window from pywin.mfc.thread import WinApp diff --git a/Pythonwin/pywin/Demos/dyndlg.py b/Pythonwin/pywin/Demos/dyndlg.py index 46a4e7fc67..ea1ef09a53 100644 --- a/Pythonwin/pywin/Demos/dyndlg.py +++ b/Pythonwin/pywin/Demos/dyndlg.py @@ -21,7 +21,7 @@ import win32con import win32ui -from pywin.mfc import dialog, window +from pywin.mfc import dialog def MakeDlgTemplate(): diff --git a/Pythonwin/pywin/Demos/ocx/msoffice.py b/Pythonwin/pywin/Demos/ocx/msoffice.py index be24ead82f..22b65f8b47 100644 --- a/Pythonwin/pywin/Demos/ocx/msoffice.py +++ b/Pythonwin/pywin/Demos/ocx/msoffice.py @@ -4,11 +4,10 @@ # It is not comlpete yet, but it _does_ show an Excel spreadsheet in a frame! # -import regutil import win32con import win32ui import win32uiole -from pywin.mfc import activex, docview, object, window +from pywin.mfc import docview, object, window from win32com.client import gencache # WordModule = gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 1033, 8, 0) diff --git a/Pythonwin/pywin/Demos/threadedgui.py b/Pythonwin/pywin/Demos/threadedgui.py index bbe1369e48..556ed18d5c 100644 --- a/Pythonwin/pywin/Demos/threadedgui.py +++ b/Pythonwin/pywin/Demos/threadedgui.py @@ -6,7 +6,7 @@ import win32api import win32con import win32ui -from pywin.mfc import docview, thread, window +from pywin.mfc import window from pywin.mfc.thread import WinThread WM_USER_PREPARE_TO_CLOSE = win32con.WM_USER + 32 diff --git a/Pythonwin/pywin/debugger/debugger.py b/Pythonwin/pywin/debugger/debugger.py index d063f06d57..3b801fc851 100644 --- a/Pythonwin/pywin/debugger/debugger.py +++ b/Pythonwin/pywin/debugger/debugger.py @@ -23,7 +23,7 @@ import win32ui from pywin.framework import app, editor, interact, scriptutils from pywin.framework.editor.color.coloreditor import MARKER_BREAKPOINT, MARKER_CURRENT -from pywin.mfc import afxres, dialog, object, window +from pywin.mfc import afxres, window from pywin.tools import browser, hierlist from .dbgcon import * diff --git a/Pythonwin/pywin/docking/DockingBar.py b/Pythonwin/pywin/docking/DockingBar.py index 3e51eb7031..34b14a41a1 100644 --- a/Pythonwin/pywin/docking/DockingBar.py +++ b/Pythonwin/pywin/docking/DockingBar.py @@ -658,8 +658,6 @@ def EditCreator(parent): def test(): - import pywin.mfc.dialog - global bar bar = DockingBar() creator = EditCreator diff --git a/Pythonwin/pywin/framework/editor/color/coloreditor.py b/Pythonwin/pywin/framework/editor/color/coloreditor.py index 4aacc0eab5..3d9b7e09e6 100644 --- a/Pythonwin/pywin/framework/editor/color/coloreditor.py +++ b/Pythonwin/pywin/framework/editor/color/coloreditor.py @@ -5,13 +5,7 @@ import win32api import win32con import win32ui -from pywin.framework.editor import ( - GetEditorFontOption, - GetEditorOption, - SetEditorFontOption, - SetEditorOption, - defaultCharacterFormat, -) +from pywin.framework.editor import GetEditorOption from pywin.scintilla import bindings # from pywin.framework.editor import EditorPropertyPage diff --git a/Pythonwin/pywin/framework/editor/configui.py b/Pythonwin/pywin/framework/editor/configui.py index 903ad66c74..174cb907ba 100644 --- a/Pythonwin/pywin/framework/editor/configui.py +++ b/Pythonwin/pywin/framework/editor/configui.py @@ -2,15 +2,7 @@ import win32api import win32con import win32ui -from pywin.framework.editor import ( - DeleteEditorOption, - GetEditorFontOption, - GetEditorOption, - SetEditorFontOption, - SetEditorOption, - defaultCharacterFormat, - editorTemplate, -) +from pywin.framework.editor import DeleteEditorOption, GetEditorOption, SetEditorOption from pywin.mfc import dialog from . import document @@ -119,7 +111,6 @@ def OnInitDialog(self): import traceback traceback.print_exc() - pass self.HookCommand(self.OnButSimple, win32ui.IDC_FOLD_ENABLE) self.HookCommand(self.OnButSimple, win32ui.IDC_RADIO1) diff --git a/Pythonwin/pywin/framework/editor/editor.py b/Pythonwin/pywin/framework/editor/editor.py index 63df9cfcdb..c14a2b7242 100644 --- a/Pythonwin/pywin/framework/editor/editor.py +++ b/Pythonwin/pywin/framework/editor/editor.py @@ -26,11 +26,9 @@ from pywin.framework.editor import ( GetEditorFontOption, GetEditorOption, - SetEditorFontOption, - SetEditorOption, defaultCharacterFormat, ) -from pywin.mfc import afxres, dialog, docview +from pywin.mfc import afxres, docview patImport = regex.symcomp(r"import \(.*\)") patIndent = regex.compile(r"^\([ \t]*[~ \t]\)") diff --git a/Pythonwin/pywin/framework/winout.py b/Pythonwin/pywin/framework/winout.py index 7badd38415..1e831c2ea9 100644 --- a/Pythonwin/pywin/framework/winout.py +++ b/Pythonwin/pywin/framework/winout.py @@ -23,17 +23,21 @@ import queue import re +import pywin.scintilla.document import win32api import win32con import win32ui from pywin.framework import app, window from pywin.mfc import docview +from pywin.scintilla import scintillacon debug = lambda msg: None - -##debug=win32ui.OutputDebugString -##import win32trace;win32trace.InitWrite() # for debugging - delete me! -##debug = win32trace.write +# debug=win32ui.OutputDebugString +# import win32trace;win32trace.InitWrite() # for debugging - delete me! +# debug = win32trace.write +# WindowOutputDocumentParent=docview.RichEditDoc +# WindowOutputDocumentParent=docview.Document +WindowOutputDocumentParent = pywin.scintilla.document.CScintillaDocument class flags: @@ -43,15 +47,6 @@ class flags: WQ_IDLE = 2 -# WindowOutputDocumentParent=docview.RichEditDoc -# WindowOutputDocumentParent=docview.Document -import pywin.scintilla.document -from pywin import default_scintilla_encoding -from pywin.scintilla import scintillacon - -WindowOutputDocumentParent = pywin.scintilla.document.CScintillaDocument - - class WindowOutputDocument(WindowOutputDocumentParent): def SaveModified(self): return 1 # say it is OK to destroy my document diff --git a/Pythonwin/pywin/scintilla/view.py b/Pythonwin/pywin/scintilla/view.py index 305c9904d3..cf570ea1f2 100644 --- a/Pythonwin/pywin/scintilla/view.py +++ b/Pythonwin/pywin/scintilla/view.py @@ -1,6 +1,5 @@ # A general purpose MFC CCtrlView view that uses Scintilla. -import array import os import re import string @@ -11,10 +10,10 @@ import afxres import win32con import win32ui -from pywin.mfc import dialog, docview +from pywin.mfc import docview from . import IDLEenvironment # IDLE emulation. -from . import bindings, control, keycodes, scintillacon +from . import bindings, control, scintillacon PRINTDLGORD = 1538 IDC_PRINT_MAG_EDIT = 1010 diff --git a/Pythonwin/pywin/tools/hierlist.py b/Pythonwin/pywin/tools/hierlist.py index a7dd4c72eb..580d4dcc3f 100644 --- a/Pythonwin/pywin/tools/hierlist.py +++ b/Pythonwin/pywin/tools/hierlist.py @@ -18,7 +18,7 @@ import win32api import win32con import win32ui -from pywin.mfc import dialog, docview, object, window +from pywin.mfc import dialog, object from win32api import RGB diff --git a/Pythonwin/pywin/tools/regedit.py b/Pythonwin/pywin/tools/regedit.py index 14e1e43c98..c62a029910 100644 --- a/Pythonwin/pywin/tools/regedit.py +++ b/Pythonwin/pywin/tools/regedit.py @@ -128,8 +128,6 @@ def OnDeleteKey(self, command, code): self.hierList.Refresh(hparent) def OnAddKey(self, command, code): - from pywin.mfc import dialog - val = dialog.GetSimpleInput("New key name", "", "Add new key") if val is None: return # cancelled. @@ -139,8 +137,6 @@ def OnAddKey(self, command, code): self.hierList.Refresh(hitem) def OnAddValue(self, command, code): - from pywin.mfc import dialog - val = dialog.GetSimpleInput("New value", "", "Add new value") if val is None: return # cancelled. diff --git a/com/win32comext/axdebug/Test/host.py b/com/win32comext/axdebug/Test/host.py index f1ec148f60..cb3a160a8d 100644 --- a/com/win32comext/axdebug/Test/host.py +++ b/com/win32comext/axdebug/Test/host.py @@ -5,10 +5,8 @@ import win32api import win32com.server.util import winerror -from win32com.axdebug import adb, axdebug, codecontainer, contexts, documents, gateways -from win32com.axdebug.util import _wrap, _wrap_remove, trace -from win32com.axscript import axscript -from win32com.client.util import Enumerator +from win32com.axdebug import adb, axdebug, codecontainer, gateways +from win32com.axdebug.util import trace from win32com.server.exception import Exception diff --git a/com/win32comext/axdebug/contexts.py b/com/win32comext/axdebug/contexts.py index 8581663943..d1f5d4801e 100644 --- a/com/win32comext/axdebug/contexts.py +++ b/com/win32comext/axdebug/contexts.py @@ -7,7 +7,7 @@ from . import adb, axdebug, gateways # Utility function for wrapping object created by this module. -from .util import _wrap, _wrap_remove, trace +from .util import _wrap class DebugCodeContext(gateways.DebugCodeContext, gateways.DebugDocumentContext): diff --git a/com/win32comext/axdebug/debugger.py b/com/win32comext/axdebug/debugger.py index 2630e9188d..5738007903 100644 --- a/com/win32comext/axdebug/debugger.py +++ b/com/win32comext/axdebug/debugger.py @@ -12,7 +12,7 @@ expressions, gateways, ) -from win32com.axdebug.util import _wrap, _wrap_remove, trace +from win32com.axdebug.util import _wrap from win32com.axscript import axscript currentDebugger = None diff --git a/com/win32comext/axdebug/documents.py b/com/win32comext/axdebug/documents.py index 2bcc1c6f14..f5a3823b22 100644 --- a/com/win32comext/axdebug/documents.py +++ b/com/win32comext/axdebug/documents.py @@ -7,8 +7,8 @@ from win32com.server.exception import Exception from win32com.server.util import unwrap -from . import axdebug, codecontainer, contexts, gateways -from .util import RaiseNotImpl, _wrap, _wrap_remove, trace +from . import axdebug, gateways +from .util import _wrap, trace # def trace(*args): # pass diff --git a/com/win32comext/axdebug/expressions.py b/com/win32comext/axdebug/expressions.py index 67bf148e77..8a95842dcb 100644 --- a/com/win32comext/axdebug/expressions.py +++ b/com/win32comext/axdebug/expressions.py @@ -7,7 +7,7 @@ from win32com.server.exception import COMException from . import axdebug, gateways -from .util import RaiseNotImpl, _wrap, _wrap_remove +from .util import RaiseNotImpl, _wrap # Given an object, return a nice string diff --git a/com/win32comext/axscript/client/debug.py b/com/win32comext/axscript/client/debug.py index b3871ab19c..e2eec02911 100644 --- a/com/win32comext/axscript/client/debug.py +++ b/com/win32comext/axscript/client/debug.py @@ -3,10 +3,9 @@ import pythoncom import win32api -import win32com.client.connect import win32com.server.util import winerror -from win32com.axdebug import adb, axdebug, contexts, documents, gateways, stackframe +from win32com.axdebug import adb, axdebug, documents, gateways from win32com.axdebug.codecontainer import SourceCodeContainer from win32com.axdebug.util import _wrap, _wrap_remove from win32com.client.util import Enumerator diff --git a/isapi/test/extension_simple.py b/isapi/test/extension_simple.py index dfc79dfdd7..b7fe37b6a3 100644 --- a/isapi/test/extension_simple.py +++ b/isapi/test/extension_simple.py @@ -6,17 +6,12 @@ # This will execute the method 'test1' below. See below for the list of # test methods that are acceptable. -import urllib.error -import urllib.parse -import urllib.request - # If we have no console (eg, am running from inside IIS), redirect output # somewhere useful - in this case, the standard win32 trace collector. import win32api import winerror -from isapi import ExtensionError, isapicon, threaded_extension -from isapi.simple import SimpleFilter +from isapi import ExtensionError, threaded_extension try: win32api.GetConsoleTitle() From ea43be24129115020a7a0c99b863d5899f1a0ab8 Mon Sep 17 00:00:00 2001 From: Avasam Date: Wed, 1 Nov 2023 15:36:30 -0400 Subject: [PATCH 15/22] Cleanup `win32comext.axdebug` (#2126) --- .../framework/editor/color/coloreditor.py | 18 ++-- Pythonwin/pywin/framework/editor/editor.py | 21 ++--- com/win32comext/axdebug/Test/host.py | 82 +++---------------- com/win32comext/axdebug/adb.py | 55 ++++++------- com/win32comext/axdebug/codecontainer.py | 34 ++++---- com/win32comext/axdebug/contexts.py | 3 - com/win32comext/axdebug/debugger.py | 37 +++------ com/win32comext/axdebug/documents.py | 15 ++-- com/win32comext/axdebug/dump.py | 10 +-- com/win32comext/axdebug/expressions.py | 9 +- com/win32comext/axdebug/stackframe.py | 39 +++++---- com/win32comext/axdebug/util.py | 34 ++------ com/win32comext/axscript/client/debug.py | 6 +- com/win32comext/axscript/test/testHost4Dbg.py | 1 - 14 files changed, 123 insertions(+), 241 deletions(-) diff --git a/Pythonwin/pywin/framework/editor/color/coloreditor.py b/Pythonwin/pywin/framework/editor/color/coloreditor.py index 3d9b7e09e6..9de95a392f 100644 --- a/Pythonwin/pywin/framework/editor/color/coloreditor.py +++ b/Pythonwin/pywin/framework/editor/color/coloreditor.py @@ -2,29 +2,23 @@ # even tighter into Pythonwin. import pywin.scintilla.keycodes +import pywin.scintilla.view import win32api import win32con import win32ui +from pywin.debugger import dbgcon from pywin.framework.editor import GetEditorOption -from pywin.scintilla import bindings - -# from pywin.framework.editor import EditorPropertyPage +from pywin.framework.editor.document import EditorDocumentBase +from pywin.scintilla import bindings, scintillacon -MSG_CHECK_EXTERNAL_FILE = ( - win32con.WM_USER + 1999 -) ## WARNING: Duplicated in document.py and editor.py +# WARNING: Duplicated in document.py and editor.py +MSG_CHECK_EXTERNAL_FILE = win32con.WM_USER + 1999 # Define a few common markers MARKER_BOOKMARK = 0 MARKER_BREAKPOINT = 1 MARKER_CURRENT = 2 -import pywin.scintilla.view -from pywin.debugger import dbgcon -from pywin.framework.editor.document import EditorDocumentBase -from pywin.scintilla import scintillacon # For the marker definitions -from pywin.scintilla.document import CScintillaDocument - class SyntEditDocument(EditorDocumentBase): "A SyntEdit document." diff --git a/Pythonwin/pywin/framework/editor/editor.py b/Pythonwin/pywin/framework/editor/editor.py index c14a2b7242..e394a06bfb 100644 --- a/Pythonwin/pywin/framework/editor/editor.py +++ b/Pythonwin/pywin/framework/editor/editor.py @@ -28,16 +28,21 @@ GetEditorOption, defaultCharacterFormat, ) -from pywin.mfc import afxres, docview +from pywin.mfc import afxres +from pywin.mfc.docview import RichEditView as ParentEditorView + +from .document import EditorDocumentBase as ParentEditorDocument + +# from pywin.mfc.docview import EditView as ParentEditorView +# from pywin.mfc.docview import Document as ParentEditorDocument patImport = regex.symcomp(r"import \(.*\)") patIndent = regex.compile(r"^\([ \t]*[~ \t]\)") ID_LOCATE_FILE = 0xE200 ID_GOTO_LINE = 0xE2001 -MSG_CHECK_EXTERNAL_FILE = ( - win32con.WM_USER + 1999 -) ## WARNING: Duplicated in document.py and coloreditor.py +# WARNING: Duplicated in document.py and coloreditor.py +MSG_CHECK_EXTERNAL_FILE = win32con.WM_USER + 1999 # Key Codes that modify the bufffer when Ctrl or Alt are NOT pressed. MODIFYING_VK_KEYS = [ @@ -76,11 +81,6 @@ isRichText = 1 # We are using the Rich Text control. This has not been tested with value "0" for quite some time! -# ParentEditorDocument=docview.Document -from .document import EditorDocumentBase - -ParentEditorDocument = EditorDocumentBase - class EditorDocument(ParentEditorDocument): # @@ -164,9 +164,6 @@ def SetLineColor(self, lineNo, color): # self.saveFileHandle.write(data) # return 1 # keep em coming! -# ParentEditorView=docview.EditView -ParentEditorView = docview.RichEditView - class EditorView(ParentEditorView): def __init__(self, doc): diff --git a/com/win32comext/axdebug/Test/host.py b/com/win32comext/axdebug/Test/host.py index cb3a160a8d..b3d1317462 100644 --- a/com/win32comext/axdebug/Test/host.py +++ b/com/win32comext/axdebug/Test/host.py @@ -3,10 +3,9 @@ import pythoncom import win32api -import win32com.server.util import winerror -from win32com.axdebug import adb, axdebug, codecontainer, gateways -from win32com.axdebug.util import trace +from win32com.axdebug import codecontainer, gateways +from win32com.axdebug.util import _wrap, trace from win32com.server.exception import Exception @@ -24,8 +23,10 @@ def ReleaseConnection(self, extconn, reserved, fLastReleaseCloses): return self.numExtRefs -# externalConnectionManager = ExternalConnection() -# wrappedExternalConnectionManager = _wrap(externalConnectionManager, pythoncom.IID_IExternalConnection) +externalConnectionManager = ExternalConnection() +wrappedExternalConnectionManager = _wrap( + externalConnectionManager, pythoncom.IID_IExternalConnection +) def DelegatedExternalConnectionQI(iid): @@ -47,9 +48,7 @@ def _query_interface_(self, iid): from win32com.util import IIDToInterfaceName trace( - "PySourceModuleDebugDocumentHost QI with {} ({})".format( - IIDToInterfaceName(iid), str(iid) - ) + f"PySourceModuleDebugDocumentHost QI with {IIDToInterfaceName(iid)} ({iid})" ) return 0 @@ -58,7 +57,7 @@ def _GetCodeContainer(self): try: codeText = open(self.module.__file__, "rt").read() except OSError as details: - codeText = "# Exception opening file\n# %s" % (details) + codeText = f"# Exception opening file\n# {details}" self.codeContainer = codecontainer.SourceCodeContainer( codeText, self.module.__file__ @@ -96,71 +95,25 @@ def GetPathName(self): try: return win32api.GetFullPathName(self.module.__file__), 1 except (AttributeError, win32api.error): - raise Exception(scode == E_FAIL) + raise Exception(scode=winerror.E_FAIL) def GetFileName(self): # Result is a string with just the name of the document, no path information. trace("GetFileName") - return os.path.split(module.__file__) + return os.path.split(self.module.__file__) def NotifyChanged(): trace("NotifyChanged") raise Exception(scode=winerror.E_NOTIMPL) -def TestSmartHelper(): - pdm = pythoncom.CoCreateInstance( - axdebug.CLSID_ProcessDebugManager, - None, - pythoncom.CLSCTX_ALL, - axdebug.IID_IProcessDebugManager, - ) - app = pdm.CreateApplication() - app.SetName("Python Process") - - pydebugger = adb.Debugger() - - nodes = BuildModuleTree() - - all_real_nodes = CreateDebugDocumentHelperNodes(pdm, app, nodes) - root = app.GetRootNode() - AttachParentNodes(root, nodes, all_real_nodes) - - pydebugger.AttachApp(app) - cookie = pdm.AddApplication(app) - input("Waiting...") - ttest.test() - - pdm.RemoveApplication(cookie) - print("Done") - - -def testdumb(): - pdm = pythoncom.CoCreateInstance( - axdebug.CLSID_ProcessDebugManager, - None, - pythoncom.CLSCTX_ALL, - axdebug.IID_IProcessDebugManager, - ) - app = pdm.GetDefaultApplication() - - nodes = BuildModuleTree() - all_real_nodes = CreateDebugDocumentHelperNodes(pdm, app, nodes) - AttachParentNodes(None, nodes, all_real_nodes) - - parentNode = None - all_real_nodes = {} - input("Waiting...") - print("Done") - - def TestSmartProvider(): import ttest from win32com.axdebug import debugger d = debugger.AXDebugger() - # d.StartDebugger() - # d.Attach() + # d.StartDebugger() + # d.Attach() d.Break() input("Waiting...") ttest.test() @@ -170,22 +123,13 @@ def TestSmartProvider(): def test(): try: - # app = TestSmartHelper() app = TestSmartProvider() - # app = testdumb() except: traceback.print_exc() -# _wrap_remove(externalConnectionManager) -# wrappedExternalConnectionManager = None - if __name__ == "__main__": test() - import win32com.axdebug.util - - win32com.axdebug.util._dump_wrapped() print( - " %d/%d com objects still alive" - % (pythoncom._GetInterfaceCount(), pythoncom._GetGatewayCount()) + f" {pythoncom._GetInterfaceCount()}/{pythoncom._GetGatewayCount()} com objects still alive" ) diff --git a/com/win32comext/axdebug/adb.py b/com/win32comext/axdebug/adb.py index 68850b5c1b..7f0984535d 100644 --- a/com/win32comext/axdebug/adb.py +++ b/com/win32comext/axdebug/adb.py @@ -9,8 +9,7 @@ import pythoncom import win32api import win32com.client.connect -from win32com.axdebug.util import _wrap, _wrap_remove, trace -from win32com.server.util import unwrap +from win32com.axdebug.util import _wrap, trace from . import axdebug, gateways, stackframe @@ -53,12 +52,7 @@ def _dumpf(frame): addn = "(with trace!)" if frame.f_trace is None: addn = " **No Trace Set **" - return "Frame at %d, file %s, line: %d%s" % ( - id(frame), - frame.f_code.co_filename, - frame.f_lineno, - addn, - ) + return f"Frame at {id(frame)}, file {frame.f_code.co_filename}, line: {frame.f_lineno}{addn}" g_adb = None @@ -118,8 +112,8 @@ def __xxxxx__set_break(self, filename, lineno, cond=None): def stop_here(self, frame): traceenter("stop_here", _dumpf(frame), _dumpf(self.stopframe)) # As per bdb.stop_here, except for logicalbotframe - ## if self.stopframe is None: - ## return 1 + # if self.stopframe is None: + # return 1 if frame is self.stopframe: return 1 @@ -157,13 +151,13 @@ def dispatch_return(self, frame, arg): tracev("dispatch_return resetting sys.trace") sys.settrace(None) return - # self.bSetTrace = 0 + # self.bSetTrace = 0 self.currentframe = frame.f_back return bdb.Bdb.dispatch_return(self, frame, arg) def dispatch_line(self, frame): traceenter("dispatch_line", _dumpf(frame), _dumpf(self.botframe)) - # trace("logbotframe is", _dumpf(self.logicalbotframe), "botframe is", self.botframe) + # trace("logbotframe is", _dumpf(self.logicalbotframe), "botframe is", self.botframe) if frame is self.logicalbotframe: trace("dispatch_line", _dumpf(frame), "for bottom frame returing tracer") # The next code executed in the frame above may be a builtin (eg, apply()) @@ -195,13 +189,13 @@ def dispatch_call(self, frame, arg): trace( "dispatch_call has no document for", _dumpf(frame), "- skipping trace!" ) - ## sys.settrace(None) + # sys.settrace(None) return None return self.trace_dispatch - # rc = bdb.Bdb.dispatch_call(self, frame, arg) - # trace("dispatch_call", _dumpf(frame),"returned",rc) - # return rc + # rc = bdb.Bdb.dispatch_call(self, frame, arg) + # trace("dispatch_call", _dumpf(frame),"returned",rc) + # return rc def trace_dispatch(self, frame, event, arg): traceenter("trace_dispatch", _dumpf(frame), event, arg) @@ -213,8 +207,8 @@ def trace_dispatch(self, frame, event, arg): # # The user functions do bugger all! # - # def user_call(self, frame, argument_list): - # traceenter("user_call",_dumpf(frame)) + # def user_call(self, frame, argument_list): + # traceenter("user_call",_dumpf(frame)) def user_line(self, frame): traceenter("user_line", _dumpf(frame)) @@ -226,11 +220,11 @@ def user_line(self, frame): self._HandleBreakPoint(frame, None, breakReason) def user_return(self, frame, return_value): - # traceenter("user_return",_dumpf(frame),return_value) + # traceenter("user_return",_dumpf(frame),return_value) bdb.Bdb.user_return(self, frame, return_value) def user_exception(self, frame, exc_info): - # traceenter("user_exception") + # traceenter("user_exception") bdb.Bdb.user_exception(self, frame, exc_info) def _HandleBreakPoint(self, frame, tb, reason): @@ -281,11 +275,8 @@ def CloseApp(self): except pythoncom.com_error: trace( - "*** Could not RemoveStackFrameSniffer %d" - % (self.stackSnifferCookie) + f"*** Could not RemoveStackFrameSniffer {self.stackSnifferCookie}" ) - if self.stackSniffer: - _wrap_remove(self.stackSniffer) self.stackSnifferCookie = self.stackSniffer = None if self.appEventConnection is not None: @@ -298,7 +289,7 @@ def CloseApp(self): self.codeContainerProvider = None def AttachApp(self, debugApplication, codeContainerProvider): - # traceenter("AttachApp", debugApplication, codeContainerProvider) + # traceenter("AttachApp", debugApplication, codeContainerProvider) self.codeContainerProvider = codeContainerProvider self.debugApplication = debugApplication self.stackSniffer = _wrap( @@ -307,7 +298,7 @@ def AttachApp(self, debugApplication, codeContainerProvider): self.stackSnifferCookie = debugApplication.AddStackFrameSniffer( self.stackSniffer ) - # trace("StackFrameSniffer added (%d)" % self.stackSnifferCookie) + # trace(f"StackFrameSniffer added ({self.stackSnifferCookie})") # Connect to the application events. self.appEventConnection = win32com.client.connect.SimpleConnection( @@ -321,7 +312,7 @@ def ResetAXDebugging(self): return if len(self.recursiveData) == 0: - # print "ResetAXDebugging called for final time." + # print("ResetAXDebugging called for final time.") self.logicalbotframe = None self.debuggingThread = None self.currentframe = None @@ -427,14 +418,14 @@ def OnBreakFlagChange(self, abf, rdat): def _BreakFlagsChanged(self): traceenter( - "_BreakFlagsChanged to {} with our thread = {}, and debugging thread = {}".format( - self.breakFlags, self.debuggingThread, win32api.GetCurrentThreadId() - ) + f"_BreakFlagsChanged to {self.breakFlags} " + + f"with our thread = {self.debuggingThread}, " + + f"and debugging thread = {win32api.GetCurrentThreadId()}" ) trace("_BreakFlagsChanged has breaks", self.breaks) # If a request comes on our debugging thread, then do it now! - # if self.debuggingThread!=win32api.GetCurrentThreadId(): - # return + # if self.debuggingThread!=win32api.GetCurrentThreadId(): + # return if len(self.breaks) or self.breakFlags: if self.logicalbotframe: diff --git a/com/win32comext/axdebug/codecontainer.py b/com/win32comext/axdebug/codecontainer.py index be20a2d394..69a9f8e458 100644 --- a/com/win32comext/axdebug/codecontainer.py +++ b/com/win32comext/axdebug/codecontainer.py @@ -4,17 +4,16 @@ to color the text, and also how to translate lines into offsets, and back. """ +import os import sys import tokenize import win32api import winerror -from win32com.axdebug import axdebug +from win32com.axdebug import axdebug, contexts +from win32com.axdebug.util import _wrap from win32com.server.exception import Exception -from . import contexts -from .util import RaiseNotImpl, _wrap - _keywords = {} # set of Python keywords for name in """ and assert break class continue def del elif else except exec @@ -43,7 +42,7 @@ def __init__( self.codeContexts = {} self.site = site self.startLineNumber = startLineNumber - self.debugDocument = None + self.debugDocument = debugDocument def _Close(self): self.text = self.lines = self.lineOffsets = None @@ -78,9 +77,9 @@ def GetLineOfPosition(self, charPos): lastOffset = lineOffset lineNo = lineNo + 1 else: # for not broken. - # print "Cant find", charPos, "in", self.lineOffsets + # print("Cant find", charPos, "in", self.lineOffsets) raise Exception(scode=winerror.S_FALSE) - # print "GLOP ret=",lineNo, (charPos-lastOffset) + # print("GLOP ret=", lineNo, (charPos - lastOffset)) return lineNo, (charPos - lastOffset) def GetNextLine(self): @@ -187,13 +186,13 @@ def _MakeContextAtPosition(self, charPos): # Returns a DebugCodeContext. debugDocument can be None for smart hosts. def GetCodeContextAtPosition(self, charPos): - # trace("GetContextOfPos", charPos, maxChars) + # trace("GetContextOfPos", charPos, maxChars) # Convert to line number. lineNo, offset = self.GetLineOfPosition(charPos) charPos = self.GetPositionOfLine(lineNo) try: cc = self.codeContexts[charPos] - # trace(" GetContextOfPos using existing") + # trace(" GetContextOfPos using existing") except KeyError: cc = self._MakeContextAtPosition(charPos) self.codeContexts[charPos] = cc @@ -226,9 +225,9 @@ def GetText(self): try: self.text = open(fname, "r").read() except OSError as details: - self.text = "# Exception opening file\n# %s" % (repr(details)) + self.text = f"# Exception opening file\n# {repr(details)}" else: - self.text = "# No file available for module '%s'" % (self.module) + self.text = f"# No file available for module '{self.module}'" self._buildlines() return self.text @@ -247,17 +246,16 @@ def GetName(self, dnt): elif dnt == axdebug.DOCUMENTNAMETYPE_FILE_TAIL: return os.path.split(fname)[1] elif dnt == axdebug.DOCUMENTNAMETYPE_URL: - return "file:%s" % fname + return f"file:{fname}" else: raise Exception(scode=winerror.E_UNEXPECTED) if __name__ == "__main__": - sys.path.append(".") - import ttest + from Test import ttest sc = SourceModuleContainer(ttest) - # sc = SourceCodeContainer(open(sys.argv[1], "rb").read(), sys.argv[1]) + # sc = SourceCodeContainer(open(sys.argv[1], "rb").read(), sys.argv[1]) attrs = sc.GetSyntaxColorAttributes() attrlen = 0 for attr in attrs: @@ -267,10 +265,10 @@ def GetName(self, dnt): attrlen = attrlen + 1 text = sc.GetText() if attrlen != len(text): - print("Lengths dont match!!! (%d/%d)" % (attrlen, len(text))) + print(f"Lengths dont match!!! ({attrlen}/{len(text)})") - # print "Attributes:" - # print attrs + # print("Attributes:") + # print(attrs) print("GetLineOfPos=", sc.GetLineOfPosition(0)) print("GetLineOfPos=", sc.GetLineOfPosition(4)) print("GetLineOfPos=", sc.GetLineOfPosition(10)) diff --git a/com/win32comext/axdebug/contexts.py b/com/win32comext/axdebug/contexts.py index d1f5d4801e..8953f5ab9c 100644 --- a/com/win32comext/axdebug/contexts.py +++ b/com/win32comext/axdebug/contexts.py @@ -1,9 +1,6 @@ """ A module for managing the AXDebug I*Contexts """ -import pythoncom -import win32com.server.util - from . import adb, axdebug, gateways # Utility function for wrapping object created by this module. diff --git a/com/win32comext/axdebug/debugger.py b/com/win32comext/axdebug/debugger.py index 5738007903..65a682680c 100644 --- a/com/win32comext/axdebug/debugger.py +++ b/com/win32comext/axdebug/debugger.py @@ -2,18 +2,8 @@ import sys import pythoncom -import win32api -from win32com.axdebug import ( - adb, - axdebug, - codecontainer, - contexts, - documents, - expressions, - gateways, -) +from win32com.axdebug import adb, axdebug, codecontainer, documents, expressions from win32com.axdebug.util import _wrap -from win32com.axscript import axscript currentDebugger = None @@ -29,7 +19,7 @@ def __init__(self, module): self.cont = codecontainer.SourceModuleContainer(module) def __repr__(self): - return "" % (self.module) + return f"" def Attach(self, parentRealNode): self.realNode.Attach(parentRealNode) @@ -49,9 +39,9 @@ def BuildModule(module, built_nodes, rootNode, create_node_fn, create_node_args) ".pyd", ".dll", ] - # keep = keep and module.__name__=='__main__' + # keep = keep and module.__name__=='__main__' if module and keep: - # print "keeping", module.__name__ + # print("keeping", module.__name__) node = ModuleTreeNode(module) built_nodes[module] = node realNode = create_node_fn(*(node,) + create_node_args) @@ -91,18 +81,18 @@ def __init__(self, axdebugger): self.axdebugger.RefreshAllModules(self.nodes, self) def FromFileName(self, fname): - ### It appears we cant add modules during a debug session! - # if self.currentNumModules != len(sys.modules): - # self.axdebugger.RefreshAllModules(self.nodes, self) - # self.currentNumModules = len(sys.modules) - # for key in self.ccsAndNodes.keys(): - # print "File:", key + # It appears we cant add modules during a debug session! + # if self.currentNumModules != len(sys.modules): + # self.axdebugger.RefreshAllModules(self.nodes, self) + # self.currentNumModules = len(sys.modules) + # for key in self.ccsAndNodes.keys(): + # print("File:", key) return documents.CodeContainerProvider.FromFileName(self, fname) def Close(self): documents.CodeContainerProvider.Close(self) self.axdebugger = None - print("Closing %d nodes" % (len(self.nodes))) + print(f"Closing {len(self.nodes)} nodes") for node in self.nodes.values(): node.Close() self.nodes = {} @@ -169,7 +159,7 @@ def Break(self): # Get/create the debugger, and tell it to break. self.app.StartDebugSession() - # self.app.CauseBreak() + # self.app.CauseBreak() self.pydebugger.SetupAXDebugging(None, frame) self.pydebugger.set_trace() @@ -244,6 +234,5 @@ def test(): print("About to test the debugging interfaces!") test() print( - " %d/%d com objects still alive" - % (pythoncom._GetInterfaceCount(), pythoncom._GetGatewayCount()) + f" {pythoncom._GetInterfaceCount()}/{pythoncom._GetGatewayCount()} com objects still alive" ) diff --git a/com/win32comext/axdebug/documents.py b/com/win32comext/axdebug/documents.py index f5a3823b22..4b93e8c1d0 100644 --- a/com/win32comext/axdebug/documents.py +++ b/com/win32comext/axdebug/documents.py @@ -4,14 +4,13 @@ import pythoncom import win32api -from win32com.server.exception import Exception from win32com.server.util import unwrap from . import axdebug, gateways from .util import _wrap, trace # def trace(*args): -# pass +# pass def GetGoodFileName(fname): @@ -34,7 +33,7 @@ def GetDocument(self): return self.doc -class DebugDocumentText(gateways.DebugDocumentInfo, gateways.DebugDocumentText): +class DebugDocumentText(gateways.DebugDocumentText): _com_interfaces_ = ( gateways.DebugDocumentInfo._com_interfaces_ + gateways.DebugDocumentText._com_interfaces_ @@ -56,7 +55,7 @@ def __init__(self, codeContainer): def _Close(self): self.docContexts = None - # self.codeContainer._Close() + # self.codeContainer._Close() self.codeContainer = None # IDebugDocumentInfo @@ -72,7 +71,7 @@ def GetDocumentClassId(self): # IDebugDocumentText methods. # def GetDocumentAttributes def GetSize(self): - # trace("GetSize") + # trace("GetSize") return self.codeContainer.GetNumLines(), self.codeContainer.GetNumChars() def GetPositionOfLine(self, cLineNumber): @@ -84,7 +83,7 @@ def GetLineOfPosition(self, charPos): def GetText(self, charPos, maxChars, wantAttr): # Get all the attributes, else the tokenizer will get upset. # XXX - not yet! - # trace("GetText", charPos, maxChars, wantAttr) + # trace("GetText", charPos, maxChars, wantAttr) cont = self.codeContainer attr = cont.GetSyntaxColorAttributes() return cont.GetText(), attr @@ -121,8 +120,8 @@ def AddCodeContainer(self, cc, node=None): def FromFileName(self, fname): cc, node = self.ccsAndNodes.get(GetGoodFileName(fname), (None, None)) - # if cc is None: - # print "FromFileName for %s returning None" % fname + # if cc is None: + # print(f"FromFileName for {fname} returning None") return cc def Close(self): diff --git a/com/win32comext/axdebug/dump.py b/com/win32comext/axdebug/dump.py index c47654fb1c..61a1cfc7ab 100644 --- a/com/win32comext/axdebug/dump.py +++ b/com/win32comext/axdebug/dump.py @@ -26,13 +26,11 @@ def DumpDebugApplicationNode(node, level=0): if doc: doctext = doc.QueryInterface(axdebug.IID_IDebugDocumentText) numLines, numChars = doctext.GetSize() - # text, attr = doctext.GetText(0, 20, 1) + # text, attr = doctext.GetText(0, 20, 1) text, attr = doctext.GetText(0, numChars, 1) - print( - "%sText is %s, %d bytes long" % (spacer, repr(text[:40] + "..."), len(text)) - ) + print(f"{spacer}Text is {repr(text[:40] + '...')}, {len(text)} bytes long") else: - print("{}{}".format(spacer, "")) + print(f"{spacer*2}") for child in Enumerator(node.EnumChildren()): DumpDebugApplicationNode(child, level + 1) @@ -47,7 +45,7 @@ def dumpall(): ) e = Enumerator(dm.EnumApplications()) for app in e: - print("Application: %s" % app.GetName()) + print(f"Application: {app.GetName()}") node = ( app.GetRootNode() ) # of type PyIDebugApplicationNode->PyIDebugDocumentProvider->PyIDebugDocumentInfo diff --git a/com/win32comext/axdebug/expressions.py b/com/win32comext/axdebug/expressions.py index 8a95842dcb..d741e45a44 100644 --- a/com/win32comext/axdebug/expressions.py +++ b/com/win32comext/axdebug/expressions.py @@ -4,7 +4,6 @@ from pprint import pprint import winerror -from win32com.server.exception import COMException from . import axdebug, gateways from .util import RaiseNotImpl, _wrap @@ -32,7 +31,7 @@ def ParseLanguageText(self, code, radix, delim, flags): ) def GetLanguageInfo(self): - # print "GetLanguageInfo" + # print("GetLanguageInfo") return "Python", "{DF630910-1C1D-11d0-AE36-8C0F5E000000}" @@ -77,7 +76,7 @@ def QueryIsComplete(self): return self.isComplete def GetResultAsString(self): - # print "GetStrAsResult returning", self.result + # print("GetStrAsResult returning", self.result) return self.hresult, MakeNiceString(self.result) def GetResultAsDebugProperty(self): @@ -187,8 +186,8 @@ def GetPropertyInfo(self, dwFieldSpec, nRadix): dwFieldSpec, nRadix, self.hresult, - dictionary, - stackFrame, + self.dictionary, + self.stackFrame, ) def GetExtendedInfo(self): ### Note - not in the framework. diff --git a/com/win32comext/axdebug/stackframe.py b/com/win32comext/axdebug/stackframe.py index edc3fe8cb8..a5c888872c 100644 --- a/com/win32comext/axdebug/stackframe.py +++ b/com/win32comext/axdebug/stackframe.py @@ -4,13 +4,12 @@ """ import pythoncom -from win32com.server.exception import COMException from . import axdebug, expressions, gateways from .util import RaiseNotImpl, _wrap, trace # def trace(*args): -# pass +# pass class EnumDebugStackFrames(gateways.EnumDebugStackFrames): @@ -21,9 +20,9 @@ class EnumDebugStackFrames(gateways.EnumDebugStackFrames): def __init__(self, debugger): infos = [] frame = debugger.currentframe - # print "Stack check" + # print("Stack check") while frame: - # print " Checking frame", frame.f_code.co_filename, frame.f_lineno-1, frame.f_trace, + # print(" Checking frame", frame.f_code.co_filename, frame.f_lineno-1, frame.f_trace) # Get a DebugCodeContext for the stack frame. If we fail, then it # is not debuggable, and therefore not worth displaying. cc = debugger.codeContainerProvider.FromFileName(frame.f_code.co_filename) @@ -31,7 +30,7 @@ def __init__(self, debugger): try: address = frame.f_locals["__axstack_address__"] except KeyError: - # print "Couldnt find stack address for",frame.f_code.co_filename, frame.f_lineno-1 + # print("Couldnt find stack address for",frame.f_code.co_filename, frame.f_lineno-1) # Use this one, even tho it is wrong :-( address = axdebug.GetStackAddress() frameInfo = ( @@ -42,23 +41,23 @@ def __init__(self, debugger): None, ) infos.append(frameInfo) - # print "- Kept!" - # else: - # print "- rejected" + # print("- Kept!") + # else: + # print("- rejected") frame = frame.f_back gateways.EnumDebugStackFrames.__init__(self, infos, 0) - # def __del__(self): - # print "EnumDebugStackFrames dieing" + # def __del__(self): + # print("EnumDebugStackFrames dieing") def Next(self, count): return gateways.EnumDebugStackFrames.Next(self, count) - # def _query_interface_(self, iid): - # from win32com.util import IIDToInterfaceName - # print "EnumDebugStackFrames QI with %s (%s)" % (IIDToInterfaceName(iid), str(iid)) - # return 0 + # def _query_interface_(self, iid): + # from win32com.util import IIDToInterfaceName + # print(f"EnumDebugStackFrames QI with {IIDToInterfaceName(iid)} ({iid})") + # return 0 def _wrap(self, obj): # This enum returns a tuple, with 2 com objects in it. obFrame, min, lim, fFinal, obFinal = obj @@ -75,8 +74,8 @@ def __init__(self, frame, lineno, codeContainer): self.codeContainer = codeContainer self.expressionContext = None - # def __del__(self): - # print "DSF dieing" + # def __del__(self): + # print("DSF dieing") def _query_interface_(self, iid): if iid == axdebug.IID_IDebugExpressionContext: if self.expressionContext is None: @@ -85,8 +84,8 @@ def _query_interface_(self, iid): axdebug.IID_IDebugExpressionContext, ) return self.expressionContext - # from win32com.util import IIDToInterfaceName - # print "DebugStackFrame QI with %s (%s)" % (IIDToInterfaceName(iid), str(iid)) + # from win32com.util import IIDToInterfaceName + # print(f"DebugStackFrame QI with {IIDToInterfaceName(iid)} ({iid})") return 0 # @@ -133,8 +132,8 @@ def __init__(self, debugger): self.debugger = debugger trace("DebugStackFrameSniffer instantiated") - # def __del__(self): - # print "DSFS dieing" + # def __del__(self): + # print("DSFS dieing") def EnumStackFrames(self): trace("DebugStackFrameSniffer.EnumStackFrames called") return _wrap( diff --git a/com/win32comext/axdebug/util.py b/com/win32comext/axdebug/util.py index ff0af1720d..805d21b28b 100644 --- a/com/win32comext/axdebug/util.py +++ b/com/win32comext/axdebug/util.py @@ -34,8 +34,6 @@ def trace(*args): # (Now this is only true for Document objects, and Python # now does ensure this. -all_wrapped = {} - def _wrap_nodebug(object, iid): return win32com.server.util.wrap(object, iid) @@ -54,27 +52,9 @@ def _wrap_debug(object, iid): _wrap = _wrap_nodebug -def _wrap_remove(object, iid=None): - # Old - no longer used or necessary! - return - - -def _dump_wrapped(): - from win32com.server.util import unwrap - - print("Wrapped items:") - for key, items in all_wrapped.items(): - print(key, end=" ") - try: - ob = unwrap(key) - print(ob, sys.getrefcount(ob)) - except: - print("") - - def RaiseNotImpl(who=None): if who is not None: - print("********* Function %s Raising E_NOTIMPL ************" % (who)) + print(f"********* Function {who} Raising E_NOTIMPL ************") # Print a sort-of "traceback", dumping all the frames leading to here. try: @@ -82,7 +62,7 @@ def RaiseNotImpl(who=None): except: frame = sys.exc_info()[2].tb_frame while frame: - print("File: %s, Line: %d" % (frame.f_code.co_filename, frame.f_lineno)) + print(f"File: {frame.f_code.co_filename}, Line: {frame.f_lineno}") frame = frame.f_back # and raise the exception for COM @@ -97,12 +77,12 @@ def __init__(self, policyClass, object): win32com.server.policy.DispatcherTrace.__init__(self, policyClass, object) import win32traceutil # Sets up everything. - # print "Object with win32trace dispatcher created (object=%s)" % `object` + # print(f"Object with win32trace dispatcher created ({object})") def _QueryInterface_(self, iid): rc = win32com.server.policy.DispatcherBase._QueryInterface_(self, iid) - # if not rc: - # self._trace_("in _QueryInterface_ with unsupported IID %s (%s)\n" % (IIDToInterfaceName(iid),iid)) + # if not rc: + # self._trace_(f"in _QueryInterface_ with unsupported IID {IIDToInterfaceName(iid)} ({iid})\n") return rc def _Invoke_(self, dispid, lcid, wFlags, args): @@ -119,7 +99,7 @@ def _Invoke_(self, dispid, lcid, wFlags, args): rc = win32com.server.policy.DispatcherBase._Invoke_( self, dispid, lcid, wFlags, args ) - # print "Invoke of", dispid, "returning", rc + # print("Invoke of", dispid, "returning", rc) return rc except Exception: t, v, tb = sys.exc_info() @@ -131,7 +111,7 @@ def _Invoke_(self, dispid, lcid, wFlags, args): desc = "" print(f"*** Invoke of {dispid} raised COM exception 0x{scode:x}{desc}") except: - print("*** Invoke of %s failed:" % dispid) + print(f"*** Invoke of {dispid} failed:") typ, val, tb = sys.exc_info() import traceback diff --git a/com/win32comext/axscript/client/debug.py b/com/win32comext/axscript/client/debug.py index e2eec02911..b1d7dabec7 100644 --- a/com/win32comext/axscript/client/debug.py +++ b/com/win32comext/axscript/client/debug.py @@ -7,7 +7,7 @@ import winerror from win32com.axdebug import adb, axdebug, documents, gateways from win32com.axdebug.codecontainer import SourceCodeContainer -from win32com.axdebug.util import _wrap, _wrap_remove +from win32com.axdebug.util import _wrap from win32com.client.util import Enumerator from win32com.server.exception import COMException from win32com.util import IIDToInterfaceName @@ -86,9 +86,7 @@ def __init__(self, scriptEngine): def Close(self): # Called by the language engine when it receives a close request - if self.activeScriptDebug is not None: - _wrap_remove(self.activeScriptDebug) - self.activeScriptDebug = None + self.activeScriptDebug = None self.scriptEngine = None self.rootNode = None self.debugApplication = None diff --git a/com/win32comext/axscript/test/testHost4Dbg.py b/com/win32comext/axscript/test/testHost4Dbg.py index 9b38a9ef4a..f642ab0096 100644 --- a/com/win32comext/axscript/test/testHost4Dbg.py +++ b/com/win32comext/axscript/test/testHost4Dbg.py @@ -83,6 +83,5 @@ def TestEngine(): TestEngine() except: traceback.print_exc() - win32com.axdebug.util._dump_wrapped() sys.exc_type = sys.exc_value = sys.exc_traceback = None print(pythoncom._GetInterfaceCount(), "com objects still alive") From 309a8b061ae6b852539e089220a2462821c3cbb2 Mon Sep 17 00:00:00 2001 From: Avasam Date: Wed, 1 Nov 2023 15:36:52 -0400 Subject: [PATCH 16/22] Change `mbcs` encoding to `utf-8` in `com/win32com/client` (#2097) --- Pythonwin/pywin/__init__.py | 3 --- Pythonwin/pywin/tools/hierlist.py | 2 -- com/win32com/client/genpy.py | 4 ++-- 3 files changed, 2 insertions(+), 7 deletions(-) diff --git a/Pythonwin/pywin/__init__.py b/Pythonwin/pywin/__init__.py index 2e44fba5ca..43d5c446fd 100644 --- a/Pythonwin/pywin/__init__.py +++ b/Pythonwin/pywin/__init__.py @@ -3,8 +3,5 @@ # others are looking at it, but it will go away soon! is_platform_unicode = 0 -# Ditto default_platform_encoding - not referenced and will die. -default_platform_encoding = "mbcs" - # This one *is* real and used - but in practice can't be changed. default_scintilla_encoding = "utf-8" # Scintilla _only_ supports this ATM diff --git a/Pythonwin/pywin/tools/hierlist.py b/Pythonwin/pywin/tools/hierlist.py index 580d4dcc3f..cc76f1905a 100644 --- a/Pythonwin/pywin/tools/hierlist.py +++ b/Pythonwin/pywin/tools/hierlist.py @@ -175,8 +175,6 @@ def AddItem(self, parentHandle, item, hInsertAfter=commctrl.TVI_LAST): bitmapSel = self.GetSelectedBitmapColumn(item) if bitmapSel is None: bitmapSel = bitmapCol - ## if isinstance(text, str): - ## text = text.encode("mbcs") hitem = self.listControl.InsertItem( parentHandle, hInsertAfter, diff --git a/com/win32com/client/genpy.py b/com/win32com/client/genpy.py index 739f3ddd00..06f11889cd 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -1025,7 +1025,7 @@ def BuildOleItemsFromType(self): return oleItems, enumItems, recordItems, vtableItems - def open_writer(self, filename, encoding="mbcs"): + def open_writer(self, filename, encoding="utf-8"): # A place to put code to open a file with the appropriate encoding. # Does *not* set self.file - just opens and returns a file. # Actually returns a handle to a temp file - finish_writer then deletes @@ -1097,7 +1097,7 @@ def do_gen_file_header(self): # We assert this is it may indicate somewhere in pywin32 that needs # upgrading. assert self.file.encoding, self.file - encoding = self.file.encoding # or "mbcs" + encoding = self.file.encoding print(f"# -*- coding: {encoding} -*-", file=self.file) print(f"# Created by makepy.py version {makepy_version}", file=self.file) From d26c5c8dea56c54244b1210f3ffcb865d9634cec Mon Sep 17 00:00:00 2001 From: Avasam Date: Wed, 1 Nov 2023 15:37:32 -0400 Subject: [PATCH 17/22] Fix invalid and accidental escape sequences (#2112) --- Pythonwin/pywin/framework/scriptutils.py | 2 +- com/win32com/client/__init__.py | 2 +- .../authorization/demos/EditServiceSecurity.py | 2 +- win32/scripts/regsetup.py | 17 +++++++++-------- win32/test/test_clipboard.py | 2 +- win32/test/test_odbc.py | 2 +- 6 files changed, 14 insertions(+), 13 deletions(-) diff --git a/Pythonwin/pywin/framework/scriptutils.py b/Pythonwin/pywin/framework/scriptutils.py index 5fb6702f16..a04ed7bbee 100644 --- a/Pythonwin/pywin/framework/scriptutils.py +++ b/Pythonwin/pywin/framework/scriptutils.py @@ -98,7 +98,7 @@ def IsOnPythonPath(path): def GetPackageModuleName(fileName): - """Given a filename, return (module name, new path). + r"""Given a filename, return (module name, new path). eg - given "c:\a\b\c\my.py", return ("b.c.my",None) if "c:\a" is on sys.path. If no package found, will return ("my", "c:\a\b\c") """ diff --git a/com/win32com/client/__init__.py b/com/win32com/client/__init__.py index 9a74a4defc..6f8ad07088 100644 --- a/com/win32com/client/__init__.py +++ b/com/win32com/client/__init__.py @@ -55,7 +55,7 @@ def __WrapDispatch( def GetObject(Pathname=None, Class=None, clsctx=None): - """ + r""" Mimic VB's GetObject() function. ob = GetObject(Class = "ProgID") or GetObject(Class = clsid) will diff --git a/com/win32comext/authorization/demos/EditServiceSecurity.py b/com/win32comext/authorization/demos/EditServiceSecurity.py index 009f4245cb..f60f71a7c9 100644 --- a/com/win32comext/authorization/demos/EditServiceSecurity.py +++ b/com/win32comext/authorization/demos/EditServiceSecurity.py @@ -1,4 +1,4 @@ -""" +r""" Implements a permissions editor for services. Service can be specified as plain name for local machine, or as a remote service of the form \\machinename\service diff --git a/win32/scripts/regsetup.py b/win32/scripts/regsetup.py index fd0f636a06..0aca77188c 100644 --- a/win32/scripts/regsetup.py +++ b/win32/scripts/regsetup.py @@ -497,23 +497,24 @@ def RegisterShellInfo(searchPaths): of the registry. """ -examples = """\ +# Using raw string so that all paths meant to be copied read correctly inline and when printed +examples = r""" Examples: -"regsetup c:\\wierd\\spot\\1 c:\\wierd\\spot\\2" +"regsetup c:\wierd\spot\1 c:\wierd\spot\2" Attempts to setup the core Python. Looks in some standard places, as well as the 2 wierd spots to locate the core Python files (eg, Python.exe, pythonXX.dll, the standard library and Win32 Extensions. "regsetup -a myappname . .\subdir" -Registers a new Pythonpath entry named myappname, with "C:\\I\\AM\\HERE" and -"C:\\I\\AM\\HERE\subdir" added to the path (ie, all args are converted to +Registers a new Pythonpath entry named myappname, with "C:\I\AM\HERE" and +"C:\I\AM\HERE\subdir" added to the path (ie, all args are converted to absolute paths) -"regsetup -c c:\\my\\python\\files" -Unconditionally add "c:\\my\\python\\files" to the 'core' Python path. +"regsetup -c c:\my\python\files" +Unconditionally add "c:\my\python\files" to the 'core' Python path. -"regsetup -m some.pyd \\windows\\system" -Register the module some.pyd in \\windows\\system as a registered +"regsetup -m some.pyd \windows\system" +Register the module some.pyd in \windows\system as a registered module. This will allow some.pyd to be imported, even though the windows system directory is not (usually!) on the Python Path. diff --git a/win32/test/test_clipboard.py b/win32/test/test_clipboard.py index 8f74e8575e..3d6c1efc5a 100644 --- a/win32/test/test_clipboard.py +++ b/win32/test/test_clipboard.py @@ -67,7 +67,7 @@ def tearDown(self): CloseClipboard() def test_unicode(self): - val = "test-\a9har" + val = "test-\xa9har" SetClipboardData(win32con.CF_UNICODETEXT, val) self.assertEqual(GetClipboardData(win32con.CF_UNICODETEXT), val) diff --git a/win32/test/test_odbc.py b/win32/test/test_odbc.py index b40a3f6c51..ce0d0426a9 100644 --- a/win32/test/test_odbc.py +++ b/win32/test/test_odbc.py @@ -207,7 +207,7 @@ def testLongBinary(self): def testRaw(self): ## Test binary data - self._test_val("rawfield", memoryview(b"\1\2\3\4\0\5\6\7\8")) + self._test_val("rawfield", memoryview(b"\1\2\3\4\0\5\6\7")) def test_widechar(self): """Test a unicode character that would be mangled if bound as plain character. From 4025d7680552beb200688911e3ec87e11acf9365 Mon Sep 17 00:00:00 2001 From: Avasam Date: Wed, 1 Nov 2023 15:59:09 -0400 Subject: [PATCH 18/22] Update Python2 print commands left in comments and docs (#2128) --- Pythonwin/pywin/Demos/fontdemo.py | 7 ++- Pythonwin/pywin/Demos/ocx/webbrowser.py | 2 +- Pythonwin/pywin/Demos/splittst.py | 4 +- Pythonwin/pywin/Demos/threadedgui.py | 2 +- Pythonwin/pywin/debugger/debugger.py | 6 +-- .../pywin/framework/editor/ModuleBrowser.py | 2 +- .../framework/editor/color/coloreditor.py | 2 +- Pythonwin/pywin/framework/editor/editor.py | 2 +- Pythonwin/pywin/framework/editor/frame.py | 22 +++++----- Pythonwin/pywin/framework/editor/template.py | 6 +-- Pythonwin/pywin/framework/intpydde.py | 2 +- Pythonwin/pywin/framework/mdi_pychecker.py | 4 +- Pythonwin/pywin/framework/sgrepmdi.py | 4 +- Pythonwin/pywin/framework/toolmenu.py | 4 +- Pythonwin/pywin/mfc/object.py | 2 +- Pythonwin/pywin/scintilla/IDLEenvironment.py | 2 +- Pythonwin/pywin/scintilla/configui.py | 2 +- Pythonwin/pywin/scintilla/document.py | 2 +- Pythonwin/pywin/scintilla/formatter.py | 13 +++++- Pythonwin/pywin/scintilla/view.py | 13 +++++- Pythonwin/pywin/tools/hierlist.py | 8 ++-- Pythonwin/pywin/tools/regedit.py | 4 +- Pythonwin/win32util.cpp | 2 +- SWIG/swig_lib/timers.i | 2 +- adodbapi/quick_reference.md | 8 ++-- adodbapi/test/adodbapitest.py | 44 +++++++++++-------- adodbapi/test/test_adodbapi_dbapi20.py | 2 +- com/help/active_directory.html | 20 ++++----- com/help/adsi.html | 6 +-- com/help/mts.d | 6 +-- com/win32com/HTML/QuickStartClientCom.html | 4 +- com/win32com/HTML/QuickStartServerCom.html | 10 ++--- com/win32com/client/__init__.py | 6 +-- com/win32com/client/dynamic.py | 8 ++-- com/win32com/client/gencache.py | 16 +++---- com/win32com/client/genpy.py | 8 ++-- com/win32com/makegw/makegwparse.py | 11 ++++- com/win32com/server/util.py | 2 +- com/win32com/servers/dictionary.py | 2 +- com/win32com/test/testAccess.py | 4 +- com/win32com/test/testCollections.py | 8 ++-- com/win32com/test/testExchange.py | 4 +- com/win32com/test/testMarshal.py | 4 +- com/win32com/test/testPersist.py | 2 +- com/win32com/test/testROT.py | 2 +- com/win32com/test/util.py | 4 +- com/win32com/universal.py | 8 ++-- com/win32comext/axscript/client/debug.py | 2 +- com/win32comext/axscript/client/framework.py | 43 +++++++++++------- .../axscript/client/pyscript_rexec.py | 7 ++- .../axscript/demos/client/asp/caps.asp | 8 ++-- .../axscript/demos/client/ie/CHARTPY.HTM | 2 +- .../axscript/demos/client/ie/FOO.HTM | 2 +- .../axscript/demos/client/ie/calc.htm | 4 +- .../axscript/demos/client/ie/dbgtest.htm | 2 +- .../axscript/demos/client/ie/demo.htm | 6 +-- .../axscript/demos/client/ie/foo2.htm | 30 ++++++------- .../axscript/demos/client/ie/mousetrack.htm | 16 +++---- com/win32comext/axscript/test/leakTest.py | 10 ++--- com/win32comext/axscript/test/testHost4Dbg.py | 10 ++--- .../shell/demos/servers/empty_volume_cache.py | 4 +- .../shell/demos/servers/folder_view.py | 2 +- .../shell/demos/servers/shell_view.py | 8 ++-- isapi/samples/redirector.py | 2 +- isapi/samples/redirector_with_filter.py | 32 +++++++------- win32/Demos/OpenEncryptedFileRaw.py | 2 +- win32/Demos/cerapi.py | 4 +- win32/Demos/eventLogDemo.py | 2 +- win32/Demos/getfilever.py | 2 +- win32/Demos/rastest.py | 8 ++-- win32/Demos/security/get_policy_info.py | 4 +- win32/Demos/win32netdemo.py | 2 +- win32/Lib/pywin32_testutil.py | 3 +- win32/Lib/win32rcparser.py | 8 ++-- win32/Lib/win32traceutil.py | 2 +- win32/help/event.d | 23 +++++----- win32/help/file.d | 6 +-- win32/help/process_info.html | 10 ++--- win32/help/security.d | 8 ++-- win32/help/security_directories.html | 32 +++++++------- win32/help/win32net.html | 24 +++++----- win32/scripts/VersionStamp/bulkstamp.py | 2 +- win32/scripts/VersionStamp/vssutil.py | 7 ++- win32/scripts/regsetup.py | 2 +- win32/test/test_odbc.py | 2 +- win32/test/test_win32file.py | 2 +- win32/test/test_win32rcparser.py | 2 +- 87 files changed, 352 insertions(+), 303 deletions(-) diff --git a/Pythonwin/pywin/Demos/fontdemo.py b/Pythonwin/pywin/Demos/fontdemo.py index fc35f4ca38..4659f1c0ab 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/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/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..518e2a1528 100644 --- a/Pythonwin/pywin/framework/editor/color/coloreditor.py +++ b/Pythonwin/pywin/framework/editor/color/coloreditor.py @@ -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) 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 de43f349bc..bde43f775b 100644 --- a/Pythonwin/pywin/framework/mdi_pychecker.py +++ b/Pythonwin/pywin/framework/mdi_pychecker.py @@ -431,10 +431,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/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/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..126d6db9e5 100644 --- a/Pythonwin/pywin/scintilla/IDLEenvironment.py +++ b/Pythonwin/pywin/scintilla/IDLEenvironment.py @@ -550,7 +550,7 @@ def test(): TestCheck("2.0", e, 13) try: TestCheck("sel.first", e, 0) - print "*** sel.first worked with an empty selection" + print("*** sel.first worked with an empty selection") except TextError: pass e.SetSel((4,5)) diff --git a/Pythonwin/pywin/scintilla/configui.py b/Pythonwin/pywin/scintilla/configui.py index 8b6157b604..9a3aeb3afe 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/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/test/adodbapitest.py b/adodbapi/test/adodbapitest.py index d7a4f2c9bc..e27bcaede1 100644 --- a/adodbapi/test/adodbapitest.py +++ b/adodbapi/test/adodbapitest.py @@ -1387,13 +1387,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 +1405,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 +1457,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 +1467,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/test_adodbapi_dbapi20.py b/adodbapi/test/test_adodbapi_dbapi20.py index 6115138336..b90844bf6a 100644 --- a/adodbapi/test/test_adodbapi_dbapi20.py +++ b/adodbapi/test/test_adodbapi_dbapi20.py @@ -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/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/__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/dynamic.py b/com/win32com/client/dynamic.py index dc938e8cbe..4c38ba3b1b 100644 --- a/com/win32com/client/dynamic.py +++ b/com/win32com/client/dynamic.py @@ -234,7 +234,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 +330,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 +414,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..c7bbbca3cb 100644 --- a/com/win32com/client/gencache.py +++ b/com/win32com/client/gencache.py @@ -458,7 +458,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 +467,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 +525,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 +550,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 +598,7 @@ def EnsureModule( # remember and return versionRedirectMap[key] = ret return ret - # print "Rebuilding: ", major, minor + # print("Rebuilding: ", major, minor) module = MakeModuleForTypelib( typelibCLSID, lcid, 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/makegw/makegwparse.py b/com/win32com/makegw/makegwparse.py index ba32c7fa36..0090c558b7 100644 --- a/com/win32com/makegw/makegwparse.py +++ b/com/win32com/makegw/makegwparse.py @@ -37,7 +37,7 @@ class ArgFormatter: """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 +64,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. diff --git a/com/win32com/server/util.py b/com/win32com/server/util.py index c46dd375d9..853f03a2b1 100644 --- a/com/win32com/server/util.py +++ b/com/win32com/server/util.py @@ -144,7 +144,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..72b405937e 100644 --- a/com/win32com/servers/dictionary.py +++ b/com/win32com/servers/dictionary.py @@ -27,7 +27,7 @@ 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 """ 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/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/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..93f9d53741 100644 --- a/com/win32comext/axscript/client/framework.py +++ b/com/win32comext/axscript/client/framework.py @@ -168,7 +168,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 +207,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 +352,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 +516,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 +773,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 +1060,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 +1087,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_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 @@