From 94cf50f7e85bd28e6b119a83b1b7747fd1fe15d8 Mon Sep 17 00:00:00 2001 From: Avasam Date: Thu, 10 Aug 2023 15:33:03 -0400 Subject: [PATCH 1/3] Minimal run of pyupgrade --- .github/workflows/main.yml | 5 ++- AutoDuck/Dump2HHC.py | 2 +- AutoDuck/InsertExternalOverviews.py | 2 +- AutoDuck/TOCToHHK.py | 2 +- Pythonwin/Scintilla/src/LexGen.py | 6 ++-- Pythonwin/pywin/framework/app.py | 2 +- Pythonwin/pywin/framework/bitmap.py | 2 +- Pythonwin/pywin/framework/editor/document.py | 6 ++-- Pythonwin/pywin/framework/editor/editor.py | 2 +- Pythonwin/pywin/framework/mdi_pychecker.py | 4 +-- Pythonwin/pywin/framework/scriptutils.py | 8 ++--- Pythonwin/pywin/framework/sgrepmdi.py | 4 +-- Pythonwin/pywin/framework/winout.py | 2 +- Pythonwin/pywin/scintilla/config.py | 4 +-- Pythonwin/pywin/scintilla/document.py | 4 +-- Pythonwin/pywin/tools/__init__.py | 1 - com/win32com/client/gencache.py | 4 +-- com/win32com/client/genpy.py | 2 +- com/win32com/client/makepy.py | 2 +- com/win32com/demos/excelAddin.py | 2 +- com/win32com/demos/excelRTDServer.py | 8 ++--- com/win32com/demos/iebutton.py | 6 ++-- com/win32com/demos/ietoolbar.py | 6 ++-- com/win32com/demos/outlookAddin.py | 2 +- com/win32com/makegw/makegwparse.py | 4 +-- com/win32com/olectl.py | 2 +- com/win32com/test/testIterators.py | 2 +- com/win32com/test/util.py | 4 +-- com/win32comext/adsi/adsicon.py | 36 +++++++++---------- .../demos/EditServiceSecurity.py | 2 +- com/win32comext/axdebug/Test/host.py | 4 +-- com/win32comext/axdebug/codecontainer.py | 4 +-- com/win32comext/bits/test/show_all_jobs.py | 24 ++++++------- com/win32comext/bits/test/test_bits.py | 12 +++---- 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 +- format_all.bat | 7 ++++ pywin32_postinstall.py | 8 ++--- setup.py | 4 +-- win32/Demos/winprocess.py | 2 +- win32/Lib/pywin32_testutil.py | 6 ++-- win32/Lib/win32rcparser.py | 14 ++++---- win32/Lib/win32serviceutil.py | 2 +- win32/Lib/win32timezone.py | 12 +++---- win32/Lib/win32verstamp.py | 2 +- win32/Lib/winnt.py | 2 +- win32/scripts/VersionStamp/BrandProject.py | 2 +- win32/scripts/VersionStamp/bulkstamp.py | 2 +- win32/scripts/VersionStamp/vssutil.py | 2 +- win32/scripts/regsetup.py | 4 +-- win32/test/handles.py | 2 +- win32/test/test_odbc.py | 2 +- win32/test/test_win32file.py | 4 +-- 59 files changed, 137 insertions(+), 140 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 21a9962c6..2eca7c9a1 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -95,7 +95,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - run: pip install isort pycln + - run: pip install pyupgrade pycln isort + # Ignore adodbapi until this has been manually ran and merged in adodbapi code + # TODO: Progressively remove the keep-* flags and add --py38-plus + - run: pyupgrade --keep-percent-format --keep-mock --keep-runtime-typing $(git ls-files '**.py*' ':!:adodbapi/*') - run: pycln . --config=pycln.toml --check - run: isort . --diff --check-only - uses: psf/black@stable diff --git a/AutoDuck/Dump2HHC.py b/AutoDuck/Dump2HHC.py index d6071d31b..30c49fbd7 100644 --- a/AutoDuck/Dump2HHC.py +++ b/AutoDuck/Dump2HHC.py @@ -465,7 +465,7 @@ def main(): cats = parseCategories() for cat in cats: file = os.path.join(gen_dir, cat.dump_file) - input = open(file, "r") + input = open(file) parseTopics(cat, input) input.close() diff --git a/AutoDuck/InsertExternalOverviews.py b/AutoDuck/InsertExternalOverviews.py index c94ddef44..22d228310 100644 --- a/AutoDuck/InsertExternalOverviews.py +++ b/AutoDuck/InsertExternalOverviews.py @@ -51,7 +51,7 @@ def main(): print("Invalid args") sys.exit(1) file = sys.argv[1] - input = open(file, "r") + input = open(file) out = open(file + ".2", "w") doc = document_object.GetDocument() linksHTML = genLinksHTML(doc.links) diff --git a/AutoDuck/TOCToHHK.py b/AutoDuck/TOCToHHK.py index 235b78677..a91ec7547 100644 --- a/AutoDuck/TOCToHHK.py +++ b/AutoDuck/TOCToHHK.py @@ -11,7 +11,7 @@ def main(): file = sys.argv[1] output = sys.argv[2] - input = open(file, "r") + input = open(file) out = open(output, "w") line = input.readline() out.write( diff --git a/Pythonwin/Scintilla/src/LexGen.py b/Pythonwin/Scintilla/src/LexGen.py index c030921ce..08a0e7854 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() @@ -135,8 +135,8 @@ def Generate(inpath, outpath, commentPrefix, eolType, *lists): # print "generate '%s' -> '%s' (comment prefix: %r, eols: %r)"\ # % (inpath, outpath, commentPrefix, eolType) try: - infile = open(inpath, "r") - except IOError: + infile = open(inpath) + except OSError: print("Can not open", inpath) return original = infile.read() diff --git a/Pythonwin/pywin/framework/app.py b/Pythonwin/pywin/framework/app.py index 298a79b4f..409a10c3e 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 1501f72d8..1ec4d50f4 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 e66947b81..7f59173b6 100644 --- a/Pythonwin/pywin/framework/editor/document.py +++ b/Pythonwin/pywin/framework/editor/document.py @@ -78,11 +78,11 @@ def OnSaveDocument(self, fileName): # 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 (os.error, NameError, OSError): 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 ) diff --git a/Pythonwin/pywin/framework/editor/editor.py b/Pythonwin/pywin/framework/editor/editor.py index 2a61ea6c5..63df9cfcd 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/mdi_pychecker.py b/Pythonwin/pywin/framework/mdi_pychecker.py index 06fbcc82b..2b841befc 100644 --- a/Pythonwin/pywin/framework/mdi_pychecker.py +++ b/Pythonwin/pywin/framework/mdi_pychecker.py @@ -210,7 +210,7 @@ def OnOpenDocument(self, fnm): # and starting a new grep can communicate the default parameters to the # new grep. try: - params = open(fnm, "r").read() + params = open(fnm).read() except: params = None self.setInitParams(params) @@ -386,7 +386,7 @@ def _inactive_idleHandler(self, handler, count): if self.verbose: self.GetFirstView().Append("# .." + f + "\n") win32ui.SetStatusText("Searching " + f, 0) - lines = open(f, "r").readlines() + lines = open(f).readlines() for i in range(len(lines)): line = lines[i] if self.pat.search(line) is not None: diff --git a/Pythonwin/pywin/framework/scriptutils.py b/Pythonwin/pywin/framework/scriptutils.py index 5bb8544d3..1433e67a3 100644 --- a/Pythonwin/pywin/framework/scriptutils.py +++ b/Pythonwin/pywin/framework/scriptutils.py @@ -101,8 +101,8 @@ def IsOnPythonPath(path): def GetPackageModuleName(fileName): """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") + 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") """ path, fname = os.path.split(fileName) path = origPath = win32ui.FullPath(path) @@ -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: diff --git a/Pythonwin/pywin/framework/sgrepmdi.py b/Pythonwin/pywin/framework/sgrepmdi.py index 16bff7fa8..5a9260145 100644 --- a/Pythonwin/pywin/framework/sgrepmdi.py +++ b/Pythonwin/pywin/framework/sgrepmdi.py @@ -191,7 +191,7 @@ def OnOpenDocument(self, fnm): # and starting a new grep can communicate the default parameters to the # new grep. try: - params = open(fnm, "r").read() + params = open(fnm).read() except: params = None self.setInitParams(params) @@ -299,7 +299,7 @@ def SearchFile(self, handler, count): # while grep is running if os.path.isfile(f): win32ui.SetStatusText("Searching " + f, 0) - lines = open(f, "r").readlines() + lines = open(f).readlines() for i in range(len(lines)): line = lines[i] if self.pat.search(line) is not None: diff --git a/Pythonwin/pywin/framework/winout.py b/Pythonwin/pywin/framework/winout.py index 645dbca81..7badd3841 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 6f169eed3..acbacd62f 100644 --- a/Pythonwin/pywin/scintilla/config.py +++ b/Pythonwin/pywin/scintilla/config.py @@ -119,7 +119,7 @@ def __init__(self, f): return # We are ready to roll! finally: cf.close() - except (os.error, IOError, EOFError): + except (os.error, 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 7fb5e264a..f7f542d6c 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/Pythonwin/pywin/tools/__init__.py b/Pythonwin/pywin/tools/__init__.py index 8b1378917..e69de29bb 100644 --- a/Pythonwin/pywin/tools/__init__.py +++ b/Pythonwin/pywin/tools/__init__.py @@ -1 +0,0 @@ - diff --git a/com/win32com/client/gencache.py b/com/win32com/client/gencache.py index 99e9c6cbd..c509079f7 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 diff --git a/com/win32com/client/genpy.py b/com/win32com/client/genpy.py index c00a77e19..a2753b05d 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -1036,7 +1036,7 @@ def open_writer(self, filename, encoding="mbcs"): # don't step on each others' toes. # Could be a classmethod one day... temp_filename = self.get_temp_filename(filename) - return open(temp_filename, "wt", encoding=encoding) + return open(temp_filename, "w", encoding=encoding) def finish_writer(self, filename, f, worked): f.close() diff --git a/com/win32com/client/makepy.py b/com/win32com/client/makepy.py index 18974305b..2b1406c0e 100644 --- a/com/win32com/client/makepy.py +++ b/com/win32com/client/makepy.py @@ -425,7 +425,7 @@ def main(): path = os.path.dirname(outputName) if path != "" and not os.path.exists(path): os.makedirs(path) - f = open(outputName, "wt", encoding="mbcs") + f = open(outputName, "w", encoding="mbcs") else: f = None diff --git a/com/win32com/demos/excelAddin.py b/com/win32com/demos/excelAddin.py index 96f6cff8a..8229477a8 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/excelRTDServer.py b/com/win32com/demos/excelRTDServer.py index 6eda46953..6f512dbf9 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/demos/iebutton.py b/com/win32com/demos/iebutton.py index 0feb0e488..d870c21cd 100644 --- a/com/win32com/demos/iebutton.py +++ b/com/win32com/demos/iebutton.py @@ -1,5 +1,3 @@ -# -*- coding: latin-1 -*- - # PyWin32 Internet Explorer Button # # written by Leonard Ritter (paniq@gmx.net) @@ -157,7 +155,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 +178,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 b259c406d..22b69011b 100644 --- a/com/win32com/demos/ietoolbar.py +++ b/com/win32com/demos/ietoolbar.py @@ -1,5 +1,3 @@ -# -*- coding: latin-1 -*- - # PyWin32 Internet Explorer Toolbar # # written by Leonard Ritter (paniq@gmx.net) @@ -328,7 +326,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 +349,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 9433596d6..58f2f6987 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/makegw/makegwparse.py b/com/win32com/makegw/makegwparse.py index ffe69cb4c..178ab7adc 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/com/win32com/olectl.py b/com/win32com/olectl.py index 50ec6f746..f6be98bda 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/testIterators.py b/com/win32com/test/testIterators.py index 8eba364a7..bc310ce83 100644 --- a/com/win32com/test/testIterators.py +++ b/com/win32com/test/testIterators.py @@ -132,7 +132,7 @@ def suite(): and issubclass(item, unittest.TestCase) and item != _BaseTestCase ): - suite.addTest(unittest.makeSuite(item)) + suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(item)) return suite diff --git a/com/win32com/test/util.py b/com/win32com/test/util.py index d36a0da91..3a7cdd706 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 = [ @@ -104,7 +104,7 @@ def ExecuteShellCommand( output_name = tempfile.mktemp("win32com_test") cmd = cmd + ' > "%s" 2>&1' % output_name rc = os.system(cmd) - output = open(output_name, "r").read().strip() + output = open(output_name).read().strip() os.remove(output_name) class Failed(Exception): diff --git a/com/win32comext/adsi/adsicon.py b/com/win32comext/adsi/adsicon.py index 9944aefaf..73080790b 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/com/win32comext/authorization/demos/EditServiceSecurity.py b/com/win32comext/authorization/demos/EditServiceSecurity.py index 009f4245c..7f6233e31 100644 --- a/com/win32comext/authorization/demos/EditServiceSecurity.py +++ b/com/win32comext/authorization/demos/EditServiceSecurity.py @@ -1,7 +1,7 @@ """ 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 +or as a remote service of the form \\machinename\\service """ import os diff --git a/com/win32comext/axdebug/Test/host.py b/com/win32comext/axdebug/Test/host.py index 7704f4fb1..73ed6f31c 100644 --- a/com/win32comext/axdebug/Test/host.py +++ b/com/win32comext/axdebug/Test/host.py @@ -57,8 +57,8 @@ def _query_interface_(self, iid): def _GetCodeContainer(self): if self.codeContainer is None: try: - codeText = open(self.module.__file__, "rt").read() - except IOError as details: + codeText = open(self.module.__file__).read() + 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 44c5f0e79..ac99fe9e4 100644 --- a/com/win32comext/axdebug/codecontainer.py +++ b/com/win32comext/axdebug/codecontainer.py @@ -224,8 +224,8 @@ def GetText(self): fname = self.GetFileName() if fname: try: - self.text = open(fname, "r").read() - except IOError as details: + self.text = open(fname).read() + 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/bits/test/show_all_jobs.py b/com/win32comext/bits/test/show_all_jobs.py index 8ce230ce0..39daf544d 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 94bcbe4be..6ff7005fb 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/ifilter/demo/filterDemo.py b/com/win32comext/ifilter/demo/filterDemo.py index 1eb7a01c0..91b3c7c17 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 6c8625a44..ca0a2a10a 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 b92109d73..3db4ee8ca 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 e5871fd80..0b403b7fb 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 a10d150e9..6a0fb6a19 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 383270dff..6e25c34d4 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 57aa36110..605dbeed0 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 29b66ac57..2a1320b36 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/format_all.bat b/format_all.bat index 10b8aeddb..ef964b884 100644 --- a/format_all.bat +++ b/format_all.bat @@ -1,3 +1,10 @@ +@echo off +@REM findstr: Ignore adodbapi until this has been manually ran and merged in adodbapi code +for /f "delims=" %%F in ('dir /b /s ".\*.py" ^| findstr /v /i "adodbapi"') do ( + @REM TODO: Progressively remove the keep-* flags and add --py38-plus + pyupgrade --keep-percent-format --keep-mock --keep-runtime-typing %%F +) +@echo on pycln . --config=pycln.toml isort . black . diff --git a/pywin32_postinstall.py b/pywin32_postinstall.py index 5b6a6da74..2e674f915 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() @@ -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") diff --git a/setup.py b/setup.py index ecaa7a692..7309fc119 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 48f6fe719..b1567d438 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() diff --git a/win32/Lib/pywin32_testutil.py b/win32/Lib/pywin32_testutil.py index 63cd87ea2..41a971967 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/win32rcparser.py b/win32/Lib/win32rcparser.py index 1d90bfd71..92a19e710 100644 --- a/win32/Lib/win32rcparser.py +++ b/win32/Lib/win32rcparser.py @@ -584,21 +584,21 @@ def ParseStreams(rc_file, h_file): def Parse(rc_name, h_name=None): if h_name: - h_file = open(h_name, "r") + h_file = open(h_name) else: # See if same basename as the .rc h_name = rc_name[:-2] + "h" try: - h_file = open(h_name, "r") - except IOError: + h_file = open(h_name) + 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: + h_file = open(h_name) + except OSError: # .h files are optional anyway h_file = None - rc_file = open(rc_name, "r") + rc_file = open(rc_name) try: return ParseStreams(rc_file, h_file) finally: @@ -617,7 +617,7 @@ def GenerateFrozenResource(rc_name, output_name, h_name=None): rcp = Parse(rc_name, h_name) in_stat = os.stat(rc_name) - out = open(output_name, "wt") + out = open(output_name, "w") out.write("#%s\n" % output_name) out.write("#This is a generated file. Please edit %s instead.\n" % rc_name) out.write("__version__=%r\n" % __version__) diff --git a/win32/Lib/win32serviceutil.py b/win32/Lib/win32serviceutil.py index 82e0a4943..4778c630c 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 b65dabdfe..cb2c8589f 100644 --- a/win32/Lib/win32timezone.py +++ b/win32/Lib/win32timezone.py @@ -1,5 +1,3 @@ -# -*- coding: UTF-8 -*- - """ win32timezone: Module for handling datetime.tzinfo time zones using the windows @@ -337,7 +335,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 +367,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 +391,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 @@ -568,7 +566,7 @@ def _LoadDynamicInfoFromKey(self, key): """ try: info = key.subkey("Dynamic DST") - except WindowsError: + except OSError: return del info["FirstEntry"] del info["LastEntry"] @@ -824,7 +822,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 074eccb6e..64038cd23 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/Lib/winnt.py b/win32/Lib/winnt.py index a88627e0f..80fe348e7 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/scripts/VersionStamp/BrandProject.py b/win32/scripts/VersionStamp/BrandProject.py index cc78d8d91..6a0cf1716 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/VersionStamp/bulkstamp.py b/win32/scripts/VersionStamp/bulkstamp.py index 44f2a63e0..297f4adca 100644 --- a/win32/scripts/VersionStamp/bulkstamp.py +++ b/win32/scripts/VersionStamp/bulkstamp.py @@ -85,7 +85,7 @@ def load_descriptions(fname, vars): retvars = {} descriptions = {} - lines = open(fname, "r").readlines() + lines = open(fname).readlines() for i in range(len(lines)): line = lines[i].strip() diff --git a/win32/scripts/VersionStamp/vssutil.py b/win32/scripts/VersionStamp/vssutil.py index 6679ebc93..1e970d817 100644 --- a/win32/scripts/VersionStamp/vssutil.py +++ b/win32/scripts/VersionStamp/vssutil.py @@ -56,7 +56,7 @@ def SubstituteInString(inString, evalEnv): def SubstituteInFile(inName, outName, evalEnv): - inFile = open(inName, "r") + inFile = open(inName) try: outFile = open(outName, "w") try: diff --git a/win32/scripts/regsetup.py b/win32/scripts/regsetup.py index cf8c5e980..b0aa27c72 100644 --- a/win32/scripts/regsetup.py +++ b/win32/scripts/regsetup.py @@ -506,9 +506,9 @@ def RegisterShellInfo(searchPaths): 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" +"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 +"C:\\I\\AM\\HERE\\subdir" added to the path (ie, all args are converted to absolute paths) "regsetup -c c:\\my\\python\\files" diff --git a/win32/test/handles.py b/win32/test/handles.py index b1f2240ba..24aae279a 100644 --- a/win32/test/handles.py +++ b/win32/test/handles.py @@ -31,7 +31,7 @@ def f2(invalidate): try: f1(invalidate) except ZeroDivisionError as exc: - raise IOError("raise 2") + raise OSError("raise 2") self.assertRaises(IOError, f2, False) # Now do it again, but so the auto object destruction diff --git a/win32/test/test_odbc.py b/win32/test/test_odbc.py index 8cba6310f..1d2a9f1b2 100644 --- a/win32/test/test_odbc.py +++ b/win32/test/test_odbc.py @@ -206,7 +206,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\\8")) def test_widechar(self): """Test a unicode character that would be mangled if bound as plain character. diff --git a/win32/test/test_win32file.py b/win32/test/test_win32file.py index c57e94ad5..cf01da1d8 100644 --- a/win32/test/test_win32file.py +++ b/win32/test/test_win32file.py @@ -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 cc0f5ae9d28b0f9e099d22223943b217cdf4bb92 Mon Sep 17 00:00:00 2001 From: Avasam Date: Thu, 10 Aug 2023 16:09:43 -0400 Subject: [PATCH 2/3] Fix scripts --- .github/workflows/main.yml | 3 ++- format_all.bat | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 2eca7c9a1..158c8fdb6 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -97,8 +97,9 @@ jobs: - uses: actions/checkout@v3 - run: pip install pyupgrade pycln isort # Ignore adodbapi until this has been manually ran and merged in adodbapi code + # _dbgscript.py is non-UTF8 on purpose, which is not supported # TODO: Progressively remove the keep-* flags and add --py38-plus - - run: pyupgrade --keep-percent-format --keep-mock --keep-runtime-typing $(git ls-files '**.py*' ':!:adodbapi/*') + - run: pyupgrade --keep-percent-format --keep-mock --keep-runtime-typing $(git ls-files '**.py*' ':!:adodbapi/*' ':!:Pythonwin/pywin/test/_dbgscript.py') - run: pycln . --config=pycln.toml --check - run: isort . --diff --check-only - uses: psf/black@stable diff --git a/format_all.bat b/format_all.bat index ef964b884..527b74b22 100644 --- a/format_all.bat +++ b/format_all.bat @@ -1,6 +1,7 @@ @echo off -@REM findstr: Ignore adodbapi until this has been manually ran and merged in adodbapi code -for /f "delims=" %%F in ('dir /b /s ".\*.py" ^| findstr /v /i "adodbapi"') do ( +@REM Ignore adodbapi until this has been manually ran and merged in adodbapi code +@REM _dbgscript.py is non-UTF8 on purpose, which is not supported +for /f "delims=" %%F in ('git ls-files **.py* :!:adodbapi/* :!:Pythonwin/pywin/test/_dbgscript.py') do ( @REM TODO: Progressively remove the keep-* flags and add --py38-plus pyupgrade --keep-percent-format --keep-mock --keep-runtime-typing %%F ) From f4ae3d3e3c1b20a34cc2aa034eb023033438e71d Mon Sep 17 00:00:00 2001 From: Avasam Date: Tue, 22 Aug 2023 19:47:33 -0400 Subject: [PATCH 3/3] Run pyupgrade with --py37-plus --- .github/workflows/download-arm64-libs.py | 6 +++--- .github/workflows/main.yml | 4 ++-- com/win32com/test/testall.py | 2 +- format_all.bat | 4 ++-- pywin32_postinstall.py | 4 ++-- setup.py | 2 +- win32/Demos/EvtFormatMessage.py | 10 +++++----- win32/test/testall.py | 2 +- 8 files changed, 17 insertions(+), 17 deletions(-) diff --git a/.github/workflows/download-arm64-libs.py b/.github/workflows/download-arm64-libs.py index 63e48971a..21b23cc79 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/.github/workflows/main.yml b/.github/workflows/main.yml index 158c8fdb6..babbbfc13 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -98,8 +98,8 @@ jobs: - run: pip install pyupgrade pycln isort # Ignore adodbapi until this has been manually ran and merged in adodbapi code # _dbgscript.py is non-UTF8 on purpose, which is not supported - # TODO: Progressively remove the keep-* flags and add --py38-plus - - run: pyupgrade --keep-percent-format --keep-mock --keep-runtime-typing $(git ls-files '**.py*' ':!:adodbapi/*' ':!:Pythonwin/pywin/test/_dbgscript.py') + # TODO: Remove the --keep-percent-format flag and fix all printf-style string formatting + - run: pyupgrade --keep-percent-format --py37-plus $(git ls-files '**.py*' ':!:adodbapi/*' ':!:Pythonwin/pywin/test/_dbgscript.py') - run: pycln . --config=pycln.toml --check - run: isort . --diff --check-only - uses: psf/black@stable diff --git a/com/win32com/test/testall.py b/com/win32com/test/testall.py index 6ca312e34..abebaecea 100644 --- a/com/win32com/test/testall.py +++ b/com/win32com/test/testall.py @@ -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: diff --git a/format_all.bat b/format_all.bat index 527b74b22..e8b440d06 100644 --- a/format_all.bat +++ b/format_all.bat @@ -2,8 +2,8 @@ @REM Ignore adodbapi until this has been manually ran and merged in adodbapi code @REM _dbgscript.py is non-UTF8 on purpose, which is not supported for /f "delims=" %%F in ('git ls-files **.py* :!:adodbapi/* :!:Pythonwin/pywin/test/_dbgscript.py') do ( - @REM TODO: Progressively remove the keep-* flags and add --py38-plus - pyupgrade --keep-percent-format --keep-mock --keep-runtime-typing %%F + @REM TODO: Remove the --keep-percent-format flag and fix all printf-style string formatting + pyupgrade --keep-percent-format --py37-plus %%F ) @echo on pycln . --config=pycln.toml diff --git a/pywin32_postinstall.py b/pywin32_postinstall.py index 2e674f915..fed7bffe3 100644 --- a/pywin32_postinstall.py +++ b/pywin32_postinstall.py @@ -692,7 +692,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 +756,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/setup.py b/setup.py index 7309fc119..9e6bb37da 100644 --- a/setup.py +++ b/setup.py @@ -543,7 +543,7 @@ def _check_vc(self): # 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) + vcbase + fr"ATLMFC\lib\{self.plat_dir}\atls.lib" ) if atls_lib: self.library_dirs.append(os.path.dirname(atls_lib[0])) diff --git a/win32/Demos/EvtFormatMessage.py b/win32/Demos/EvtFormatMessage.py index 125438692..ecd5075a7 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/test/testall.py b/win32/test/testall.py index 85adf736e..373dd212b 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