From 30f43b8ec7e1bc3ef58cce4284f6a9d2224e73f4 Mon Sep 17 00:00:00 2001 From: Avasam Date: Wed, 7 Dec 2022 00:22:45 -0500 Subject: [PATCH 01/24] Cleanup unsupported python code --- Pythonwin/Scintilla/src/LexGen.py | 10 +- Pythonwin/pywin/debugger/debugger.py | 34 +++-- Pythonwin/pywin/framework/app.py | 38 +++--- Pythonwin/pywin/framework/editor/editor.py | 22 ++-- Pythonwin/pywin/framework/interact.py | 32 ++--- Pythonwin/pywin/framework/mdi_pychecker.py | 18 ++- Pythonwin/pywin/framework/scriptutils.py | 26 ++-- Pythonwin/pywin/framework/sgrepmdi.py | 17 +-- Pythonwin/pywin/framework/stdin.py | 17 ++- Pythonwin/pywin/framework/toolmenu.py | 19 ++- Pythonwin/pywin/framework/winout.py | 19 +-- Pythonwin/pywin/idle/AutoIndent.py | 23 ++-- Pythonwin/pywin/idle/FormatParagraph.py | 4 +- Pythonwin/pywin/idle/PyParse.py | 3 +- Pythonwin/pywin/mfc/activex.py | 13 +- Pythonwin/pywin/mfc/dialog.py | 3 +- Pythonwin/pywin/scintilla/control.py | 19 +-- Pythonwin/pywin/scintilla/document.py | 24 ++-- Pythonwin/pywin/scintilla/view.py | 31 +++-- Pythonwin/pywin/tools/browser.py | 17 ++- Pythonwin/pywin/tools/hierlist.py | 29 ++--- README.md | 6 +- adodbapi/__init__.py | 30 +++-- adodbapi/adodbapi.py | 100 ++++----------- adodbapi/apibase.py | 119 ++++-------------- adodbapi/is64bit.py | 10 +- adodbapi/quick_reference.md | 22 ++-- adodbapi/readme.txt | 17 ++- adodbapi/remote.py | 37 +++--- adodbapi/remote/server.py | 39 +++--- adodbapi/setup.py | 5 +- adodbapi/test/adodbapitest.py | 116 ++--------------- adodbapi/test/adodbapitestconfig.py | 28 ++--- adodbapi/test/dbapi20.py | 42 +++---- adodbapi/test/is64bit.py | 10 +- adodbapi/test/setuptestframework.py | 23 +--- com/win32com/client/__init__.py | 25 ++-- com/win32com/client/build.py | 15 +-- com/win32com/client/combrowse.py | 12 +- com/win32com/client/genpy.py | 46 +++---- com/win32com/client/makepy.py | 24 ++-- com/win32com/client/selecttlb.py | 8 +- com/win32com/demos/connect.py | 8 +- com/win32com/demos/excelRTDServer.py | 10 +- com/win32com/demos/iebutton.py | 23 ++-- com/win32com/demos/ietoolbar.py | 27 ++-- com/win32com/makegw/makegw.py | 3 +- com/win32com/makegw/makegwparse.py | 2 +- com/win32com/server/dispatcher.py | 10 +- com/win32com/server/register.py | 17 +-- com/win32com/storagecon.py | 2 +- com/win32com/test/testPersist.py | 28 ++--- com/win32com/test/testPippo.py | 8 +- com/win32com/test/testPyComTest.py | 61 ++------- com/win32com/test/testShell.py | 54 ++++---- com/win32com/test/testStreams.py | 17 ++- com/win32com/test/testall.py | 21 ++-- com/win32com/test/testvb.py | 57 +++++---- com/win32com/test/testvbscript_regexp.py | 9 +- com/win32com/test/util.py | 27 ++-- com/win32comext/axscript/client/debug.py | 22 ++-- com/win32comext/axscript/client/error.py | 32 ++--- com/win32comext/axscript/client/framework.py | 19 +-- com/win32comext/axscript/client/pyscript.py | 29 ++--- com/win32comext/axscript/test/leakTest.py | 22 ++-- com/win32comext/axscript/test/testHost.py | 14 +-- com/win32comext/mapi/mapiutil.py | 27 ++-- .../shell/demos/ITransferAdviseSink.py | 16 +-- .../shell/demos/servers/copy_hook.py | 1 + isapi/samples/redirector.py | 21 ++-- setup.py | 69 +++++----- win32/Demos/BackupRead_BackupWrite.py | 20 +-- .../Demos/CreateFileTransacted_MiniVersion.py | 16 ++- win32/Demos/OpenEncryptedFileRaw.py | 6 +- win32/Demos/eventLogDemo.py | 14 +-- win32/Demos/mmapfile_demo.py | 24 ++-- win32/Demos/security/sspi/socket_server.py | 16 ++- win32/Demos/service/pipeTestService.py | 11 +- win32/Demos/service/pipeTestServiceClient.py | 13 +- win32/Demos/win32clipboardDemo.py | 12 +- win32/Demos/win32fileDemo.py | 11 +- win32/Demos/win32gui_dialog.py | 18 +-- win32/Demos/win32gui_menu.py | 16 ++- win32/Demos/win32gui_taskbar.py | 15 ++- win32/Lib/dbi.py | 27 ---- win32/Lib/netbios.py | 20 +-- win32/Lib/pywin32_testutil.py | 38 +----- win32/Lib/pywintypes.py | 7 +- win32/Lib/sspi.py | 8 +- win32/Lib/win32gui_struct.py | 92 ++++---------- win32/Lib/win32timezone.py | 29 ++--- win32/Lib/win32verstamp.py | 15 +-- win32/Lib/winnt.py | 12 -- win32/test/handles.py | 10 +- win32/test/test_clipboard.py | 28 ++--- win32/test/test_exceptions.py | 21 ++-- win32/test/test_odbc.py | 24 ++-- win32/test/test_pywintypes.py | 24 ++-- win32/test/test_security.py | 16 ++- win32/test/test_sspi.py | 30 +++-- win32/test/test_win32api.py | 16 ++- win32/test/test_win32file.py | 66 +++++----- win32/test/test_win32inet.py | 14 +-- win32/test/test_win32pipe.py | 38 +++--- win32/test/test_win32timezone.py | 14 +-- win32/test/test_win32trace.py | 13 +- win32/test/test_win32wnet.py | 17 ++- win32/test/testall.py | 8 +- 108 files changed, 1031 insertions(+), 1556 deletions(-) delete mode 100644 win32/Lib/dbi.py diff --git a/Pythonwin/Scintilla/src/LexGen.py b/Pythonwin/Scintilla/src/LexGen.py index 360a6736d2..3ba2d2c2f7 100644 --- a/Pythonwin/Scintilla/src/LexGen.py +++ b/Pythonwin/Scintilla/src/LexGen.py @@ -4,7 +4,7 @@ # Regenerate the Scintilla and SciTE source files that list # all the lexers and all the properties files. # Should be run whenever a new lexer is added or removed. -# Requires Python 2.4 or later +# Requires Python 3.0 or later # Most files are regenerated in place with templates stored in comments. # The VS .NET project file is generated into a different file as the # VS .NET environment will not retain comments when modifying the file. @@ -16,10 +16,10 @@ # Does not regenerate the Visual C++ 6 project files but does the VS .NET # project file. +import glob +import os import string import sys -import os -import glob # EOL constants CR = "\r" @@ -200,7 +200,9 @@ def FindProperties(lexFile): def ciCompare(a, b): - return cmp(a.lower(), b.lower()) + a_lower = a.lower() + b_lower = b.lower() + return (a_lower > b_lower) - (a_lower < b_lower) def RegenerateAll(): diff --git a/Pythonwin/pywin/debugger/debugger.py b/Pythonwin/pywin/debugger/debugger.py index ab09853f55..53ebadf373 100644 --- a/Pythonwin/pywin/debugger/debugger.py +++ b/Pythonwin/pywin/debugger/debugger.py @@ -8,29 +8,26 @@ # >>> import pywin.debugger # >>> pywin.debugger.GetDebugger().run("command") -import pdb import bdb -import sys -import string import os +import pdb +import string +import sys +import traceback import types -import win32ui +import commctrl +import pywin.docking.DockingBar import win32api import win32con -import pywin.docking.DockingBar -from pywin.mfc import dialog, object, afxres, window -from pywin.framework import app, interact, editor, scriptutils -from pywin.framework.editor.color.coloreditor import MARKER_CURRENT, MARKER_BREAKPOINT +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.tools import browser, hierlist -import commctrl -import traceback # import win32traceutil -if win32ui.UNICODE: - LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITW -else: - LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITA +LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITW from .dbgcon import * @@ -699,13 +696,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 c782f92919..56fea1bb19 100644 --- a/Pythonwin/pywin/framework/app.py +++ b/Pythonwin/pywin/framework/app.py @@ -4,16 +4,17 @@ # # We also grab the FileOpen command, to invoke our Python editor " The PythonWin application code. Manages most aspects of MDI, etc " -import win32con -import win32api -import win32ui -import sys -import string import os -from pywin.mfc import window, dialog, afxres -from pywin.mfc.thread import WinApp +import string +import sys import traceback + import regutil +import win32api +import win32con +import win32ui +from pywin.mfc import afxres, dialog, window +from pywin.mfc.thread import WinApp from . import scriptutils @@ -397,8 +398,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() @@ -413,22 +414,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 + import code - sys.modules["builtins"].input = Win32RawInput + sys.modules["builtins"].input = Win32Input def HaveGoodGUI(): @@ -439,7 +428,8 @@ def HaveGoodGUI(): def CreateDefaultGUI(appClass=None): """Creates a default GUI environment""" if appClass is None: - from . import intpyapp # Bring in the default app - could be param'd later. + # Bring in the default app - could be param'd later. + from . import intpyapp appClass = intpyapp.InteractivePythonApp # Create and init the app. diff --git a/Pythonwin/pywin/framework/editor/editor.py b/Pythonwin/pywin/framework/editor/editor.py index c41a8b4b2a..fd80e5c719 100644 --- a/Pythonwin/pywin/framework/editor/editor.py +++ b/Pythonwin/pywin/framework/editor/editor.py @@ -17,26 +17,26 @@ # Note that it will _always_ prompt you if the file in the editor has been modified. -import win32ui -import win32api -import win32con -import regex +import os import re import string -import sys, os import traceback -from pywin.mfc import docview, dialog, afxres +import regex +import win32api +import win32con +import win32ui from pywin.framework.editor import ( - GetEditorOption, - SetEditorOption, GetEditorFontOption, + GetEditorOption, SetEditorFontOption, + SetEditorOption, defaultCharacterFormat, ) +from pywin.mfc import afxres, dialog, docview -patImport = regex.symcomp("import \(.*\)") -patIndent = regex.compile("^\\([ \t]*[~ \t]\\)") +patImport = regex.symcomp(r"import \(.*\)") +patIndent = regex.compile(r"^\\([ \t]*[~ \t]\\)") ID_LOCATE_FILE = 0xE200 ID_GOTO_LINE = 0xE2001 @@ -134,7 +134,7 @@ def TranslateLoadedData(self, data): win32ui.SetStatusText( "Translating from Unix file format - please wait...", 1 ) - return re.sub("\r*\n", "\r\n", data) + return re.sub(r"\r*\n", "\r\n", data) else: return data diff --git a/Pythonwin/pywin/framework/interact.py b/Pythonwin/pywin/framework/interact.py index ff0fa6623a..702e759354 100644 --- a/Pythonwin/pywin/framework/interact.py +++ b/Pythonwin/pywin/framework/interact.py @@ -3,23 +3,23 @@ ## Interactive Shell Window ## -import sys, os +import array import code +import os import string - -import win32ui -import win32api -import win32clipboard -import win32con +import sys import traceback -import afxres -import array -import __main__ -import pywin.scintilla.formatter +import __main__ +import afxres +import pywin.framework.app import pywin.scintilla.control +import pywin.scintilla.formatter import pywin.scintilla.IDLEenvironment -import pywin.framework.app +import win32api +import win32clipboard +import win32con +import win32ui ## sequential after ID_GOTO_LINE defined in editor.py ID_EDIT_COPY_CODE = 0xE2002 @@ -27,10 +27,10 @@ trace = pywin.scintilla.formatter.trace -from . import winout - import re +from . import winout + # from IDLE. _is_block_opener = re.compile(r":\s*(#.*)?$").search _is_block_closer = re.compile( @@ -47,7 +47,7 @@ re.VERBOSE, ).match -tracebackHeader = "Traceback (".encode("ascii") +tracebackHeader = b"Traceback (" sectionProfile = "Interactive Window" valueFormatTitle = "FormatTitle" @@ -138,7 +138,7 @@ def ColorizeInteractiveCode(self, cdoc, styleStart, stylePyStart): return state = styleStart # As per comments in Colorize(), we work with the raw utf8 - # bytes. To avoid too muych py3k pain, we treat each utf8 byte + # bytes. To avoid too much py3k pain, we treat each utf8 byte # as a latin-1 unicode character - we only use it to compare # against ascii chars anyway... chNext = cdoc[0:1].decode("latin-1") @@ -201,7 +201,7 @@ def ColorizeInteractiveCode(self, cdoc, styleStart, stylePyStart): # It is a PythonColorizer state - seek past the end of the line # and ask the Python colorizer to color that. end = startSeg - while end < lengthDoc and cdoc[end] not in "\r\n".encode("ascii"): + while end < lengthDoc and cdoc[end] not in b"\r\n": end = end + 1 self.ColorizePythonCode(cdoc[:end], startSeg, state) stylePyStart = self.GetStringStyle(end - 1) diff --git a/Pythonwin/pywin/framework/mdi_pychecker.py b/Pythonwin/pywin/framework/mdi_pychecker.py index f6853afb0f..67dc4ec220 100644 --- a/Pythonwin/pywin/framework/mdi_pychecker.py +++ b/Pythonwin/pywin/framework/mdi_pychecker.py @@ -33,11 +33,19 @@ ## ###################################################################### -import win32ui +import glob +import os +import re +import stat +import string +import sys +import time + import win32api -from pywin.mfc import docview, dialog, window import win32con -import sys, string, re, glob, os, stat, time +import win32ui +from pywin.mfc import dialog, docview, window + from . import scriptutils @@ -140,7 +148,7 @@ def __radd__(self, other): # Group(1) is the filename, group(2) is the lineno. -# regexGrepResult=regex.compile("^\\([a-zA-Z]:.*\\)(\\([0-9]+\\))") +# regexGrepResult=regex.compile(r"^\([a-zA-Z]:.*\)(\([0-9]+\))") # regexGrep=re.compile(r"^([a-zA-Z]:[^(]*)\((\d+)\)") regexGrep = re.compile(r"^(..[^\(:]+)?[\(:](\d+)[\):]:?\s*(.*)") @@ -538,7 +546,7 @@ def OnAddComment(self, cmd, code): errtext = m.group(3) if start != end and line_start == line_end: errtext = self.GetSelText() - errtext = repr(re.escape(errtext).replace("\ ", " ")) + errtext = repr(re.escape(errtext).replace(r"\ ", " ")) view.ReplaceSel(addspecific and cmnt % locals() or cmnt) return 0 diff --git a/Pythonwin/pywin/framework/scriptutils.py b/Pythonwin/pywin/framework/scriptutils.py index b1e5c2d0bc..5e9e54245e 100644 --- a/Pythonwin/pywin/framework/scriptutils.py +++ b/Pythonwin/pywin/framework/scriptutils.py @@ -1,18 +1,19 @@ """ Various utilities for running/importing a script """ +import bdb +import linecache +import os +import string import sys -import win32ui +import traceback + +import __main__ import win32api import win32con -import __main__ +import win32ui from pywin.mfc import dialog from pywin.mfc.docview import TreeView -import os -import string -import traceback -import linecache -import bdb from .cmdline import ParseArgs @@ -28,9 +29,9 @@ "\n" ) -byte_cr = "\r".encode("ascii") -byte_lf = "\n".encode("ascii") -byte_crlf = "\r\n".encode("ascii") +byte_cr = b"\r" +byte_lf = b"\n" +byte_crlf = b"\r\n" # A dialog box for the "Run Script" command. class DlgRunScript(dialog.Dialog): @@ -302,7 +303,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: @@ -435,8 +436,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/sgrepmdi.py b/Pythonwin/pywin/framework/sgrepmdi.py index 52d8a6f64b..5403c379bf 100644 --- a/Pythonwin/pywin/framework/sgrepmdi.py +++ b/Pythonwin/pywin/framework/sgrepmdi.py @@ -18,16 +18,17 @@ # Hats off to Mark Hammond for providing an environment where I could cobble # something like this together in a couple evenings! -import win32ui -import win32api -from pywin.mfc import docview, dialog, window -import win32con -import string -import re import glob import os +import re import stat -import glob +import string + +import win32api +import win32con +import win32ui +from pywin.mfc import dialog, docview, window + from . import scriptutils @@ -130,7 +131,7 @@ def __radd__(self, other): # Group(1) is the filename, group(2) is the lineno. -# regexGrepResult=regex.compile("^\\([a-zA-Z]:.*\\)(\\([0-9]+\\))") +# regexGrepResult=regex.compile(r"^\([a-zA-Z]:.*\)(\([0-9]+\))") regexGrep = re.compile(r"^([a-zA-Z]:[^(]*)\(([0-9]+)\)") diff --git a/Pythonwin/pywin/framework/stdin.py b/Pythonwin/pywin/framework/stdin.py index 2f3adcb6b5..868d719adf 100644 --- a/Pythonwin/pywin/framework/stdin.py +++ b/Pythonwin/pywin/framework/stdin.py @@ -5,7 +5,7 @@ # any purpose. """Provides a class Stdin which can be used to emulate the regular old sys.stdin for the PythonWin interactive window. Right now it just pops -up a raw_input() dialog. With luck, someone will integrate it into the +up a input() dialog. With luck, someone will integrate it into the actual PythonWin interactive window someday. WARNING: Importing this file automatically replaces sys.stdin with an @@ -18,15 +18,12 @@ """ import sys -try: - get_input_line = raw_input # py2x -except NameError: - get_input_line = input # py3k +get_input_line = input class Stdin: def __init__(self): - self.real_file = sys.stdin # NOTE: Likely to be None in py3k + self.real_file = sys.stdin # NOTE: Likely to be None self.buffer = "" self.closed = False @@ -142,8 +139,8 @@ def readlines(self, *sizehint): Sell you soul to the devil, baby """ - def fake_raw_input(prompt=None): - """Replacement for raw_input() which pulls lines out of global test_input. + def fake_input(prompt=None): + """Replacement for input() which pulls lines out of global test_input. For testing only! """ global test_input @@ -157,7 +154,7 @@ def fake_raw_input(prompt=None): raise EOFError() return result - get_input_line = fake_raw_input + get_input_line = fake_input # Some completely inadequate tests, just to make sure the code's not totally broken try: @@ -169,7 +166,7 @@ def fake_raw_input(prompt=None): print(x.readline(3)) print(x.readlines()) finally: - get_input_line = raw_input + get_input_line = input else: import sys diff --git a/Pythonwin/pywin/framework/toolmenu.py b/Pythonwin/pywin/framework/toolmenu.py index bd4c7138f0..88dc5ddc48 100644 --- a/Pythonwin/pywin/framework/toolmenu.py +++ b/Pythonwin/pywin/framework/toolmenu.py @@ -1,11 +1,13 @@ # toolmenu.py -import win32ui -import win32con +import string +import sys + import win32api +import win32con +import win32ui + from . import app -import sys -import string tools = {} idPos = 100 @@ -109,13 +111,13 @@ def SetToolsMenu(menu, menuPos=None): def HandleToolCommand(cmd, code): - import traceback import re + import traceback global tools (menuString, pyCmd, desc) = tools[cmd] win32ui.SetStatusText("Executing tool %s" % desc, 1) - pyCmd = re.sub("\\\\n", "\n", pyCmd) + pyCmd = re.sub(r"\\n", "\n", pyCmd) win32ui.DoWaitCursor(1) oldFlag = None try: @@ -148,10 +150,7 @@ def HandleToolCommand(cmd, code): import commctrl from pywin.mfc import dialog -if win32ui.UNICODE: - LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITW -else: - LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITA +LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITW class ToolMenuPropPage(dialog.PropertyPage): diff --git a/Pythonwin/pywin/framework/winout.py b/Pythonwin/pywin/framework/winout.py index ca23e51423..deaa0cef48 100644 --- a/Pythonwin/pywin/framework/winout.py +++ b/Pythonwin/pywin/framework/winout.py @@ -20,11 +20,15 @@ # This module is thread safe - output can originate from any thread. If any thread # other than the main thread attempts to print, it is always queued until next idle time -import sys, string, re -from pywin.mfc import docview -from pywin.framework import app, window -import win32ui, win32api, win32con import queue +import re +import string + +import win32api +import win32con +import win32ui +from pywin.framework import app, window +from pywin.mfc import docview debug = lambda msg: None @@ -43,8 +47,8 @@ class flags: # WindowOutputDocumentParent=docview.RichEditDoc # WindowOutputDocumentParent=docview.Document import pywin.scintilla.document -from pywin.scintilla import scintillacon from pywin import default_scintilla_encoding +from pywin.scintilla import scintillacon WindowOutputDocumentParent = pywin.scintilla.document.CScintillaDocument @@ -98,7 +102,7 @@ def OnDestroy(self, message): class WindowOutputViewImpl: def __init__(self): - self.patErrorMessage = re.compile('\W*File "(.*)", line ([0-9]+)') + self.patErrorMessage = re.compile(r'\W*File "(.*)", line ([0-9]+)') self.template = self.GetDocument().GetDocTemplate() def HookHandlers(self): @@ -144,7 +148,8 @@ def HandleSpecialLine(self): # An OLE Exception - pull apart the exception # and try and locate a help file. try: - import win32api, win32con + import win32api + import win32con det = eval(line[line.find(":") + 1 :].strip()) win32ui.SetStatusText("Opening help file on OLE error...") diff --git a/Pythonwin/pywin/idle/AutoIndent.py b/Pythonwin/pywin/idle/AutoIndent.py index cc1adf5543..6dafa9e9e2 100644 --- a/Pythonwin/pywin/idle/AutoIndent.py +++ b/Pythonwin/pywin/idle/AutoIndent.py @@ -1,17 +1,14 @@ -import sys -import string, tokenize -from . import PyParse +import string +import tokenize + from pywin import default_scintilla_encoding -if sys.version_info < (3,): - # in py2k, tokenize() takes a 'token eater' callback, while - # generate_tokens is a generator that works with str objects. - token_generator = tokenize.generate_tokens -else: - # in py3k tokenize() is the generator working with 'byte' objects, and - # token_generator is the 'undocumented b/w compat' function that - # theoretically works with str objects - but actually seems to fail) - token_generator = tokenize.tokenize +from . import PyParse + +# tokenize() is the generator working with 'byte' objects, and +# token_generator is the 'undocumented b/w compat' function that +# theoretically works with str objects - but actually seems to fail) +token_generator = tokenize.tokenize class AutoIndent: @@ -516,7 +513,7 @@ def readline(self): val = "" else: val = self.text.get(mark, mark + " lineend+1c") - # hrm - not sure this is correct in py3k - the source code may have + # hrm - not sure this is correct - the source code may have # an encoding declared, but the data will *always* be in # default_scintilla_encoding - so if anyone looks at the encoding decl # in the source they will be wrong. I think. Maybe. Or something... diff --git a/Pythonwin/pywin/idle/FormatParagraph.py b/Pythonwin/pywin/idle/FormatParagraph.py index 2ed4a2c226..2443cc1465 100644 --- a/Pythonwin/pywin/idle/FormatParagraph.py +++ b/Pythonwin/pywin/idle/FormatParagraph.py @@ -14,8 +14,8 @@ # spaces, they will not be considered part of the same block. # * Fancy comments, like this bulleted list, arent handled :-) -import string import re +import string class FormatParagraph: @@ -135,7 +135,7 @@ def reformat_paragraph(data, limit=70): partial = indent1 while i < n and not is_all_white(lines[i]): # XXX Should take double space after period (etc.) into account - words = re.split("(\s+)", lines[i]) + words = re.split(r"(\s+)", lines[i]) for j in range(0, len(words), 2): word = words[j] if not word: diff --git a/Pythonwin/pywin/idle/PyParse.py b/Pythonwin/pywin/idle/PyParse.py index b4da7150cf..abebbca63f 100644 --- a/Pythonwin/pywin/idle/PyParse.py +++ b/Pythonwin/pywin/idle/PyParse.py @@ -1,5 +1,5 @@ -import string import re +import string import sys # Reason last stmt is continued (or C_NONE if it's not). @@ -122,6 +122,7 @@ def dump(*stuff): _tran[ord(ch)] = ")" for ch in "\"'\\\n#": _tran[ord(ch)] = ch +# TODO # We are called with unicode strings, and str.translate is one of the few # py2k functions which can't 'do the right thing' - so take care to ensure # _tran is full of unicode... diff --git a/Pythonwin/pywin/mfc/activex.py b/Pythonwin/pywin/mfc/activex.py index 19a11330e7..a9828e78dc 100644 --- a/Pythonwin/pywin/mfc/activex.py +++ b/Pythonwin/pywin/mfc/activex.py @@ -1,14 +1,9 @@ """Support for ActiveX control hosting in Pythonwin. """ -import win32ui, win32uiole -from . import window +import win32ui +import win32uiole -# XXX - we are still "classic style" classes in py2x, so we need can't yet -# use 'type()' everywhere - revisit soon, as py2x will move to new-style too... -try: - from types import ClassType as new_type -except ImportError: - new_type = type # py3k +from . import window class Control(window.Wnd): @@ -76,7 +71,7 @@ def MakeControlClass(controlClass, name=None): """ if name is None: name = controlClass.__name__ - return new_type("OCX" + name, (Control, controlClass), {}) + return type("OCX" + name, (Control, controlClass), {}) def MakeControlInstance(controlClass, name=None): diff --git a/Pythonwin/pywin/mfc/dialog.py b/Pythonwin/pywin/mfc/dialog.py index 2a9dc73478..1a547bec36 100644 --- a/Pythonwin/pywin/mfc/dialog.py +++ b/Pythonwin/pywin/mfc/dialog.py @@ -4,8 +4,8 @@ # dialog.py # Python class for Dialog Boxes in PythonWin. -import win32ui import win32con +import win32ui # sob - 2to3 doesn't see this as a relative import :( from pywin.mfc import window @@ -90,6 +90,7 @@ def items(self): def values(self): return list(self.data.values()) + # TODO # XXX - needs py3k work! def has_key(self, key): return key in self.data diff --git a/Pythonwin/pywin/scintilla/control.py b/Pythonwin/pywin/scintilla/control.py index f4952f8482..a786147bc2 100644 --- a/Pythonwin/pywin/scintilla/control.py +++ b/Pythonwin/pywin/scintilla/control.py @@ -4,15 +4,17 @@ # a "standard" MFC edit control (eg, control.GetTextLength(), control.GetSel() # plus many Scintilla specific features (eg control.SCIAddStyledText()) -from pywin.mfc import window -from pywin import default_scintilla_encoding -import win32con -import win32ui -import win32api import array -import struct -import string import os +import string +import struct + +import win32api +import win32con +import win32ui +from pywin import default_scintilla_encoding +from pywin.mfc import window + from . import scintillacon # Load Scintilla.dll to get access to the control. @@ -36,8 +38,7 @@ # Still not there - lets see if Windows can find it by searching? dllid = win32api.LoadLibrary("Scintilla.DLL") -# null_byte is str in py2k, bytes on py3k -null_byte = "\0".encode("ascii") +null_byte = b"\0" ## These are from Richedit.h - need to add to win32con or commctrl EM_GETTEXTRANGE = 1099 diff --git a/Pythonwin/pywin/scintilla/document.py b/Pythonwin/pywin/scintilla/document.py index df026bb3ca..1a114173b1 100644 --- a/Pythonwin/pywin/scintilla/document.py +++ b/Pythonwin/pywin/scintilla/document.py @@ -1,19 +1,21 @@ +import codecs +import os +import re +import string + +import win32con import win32ui -from pywin.mfc import docview from pywin import default_scintilla_encoding +from pywin.mfc import docview + from . import scintillacon -import win32con -import string -import os -import codecs -import re -crlf_bytes = "\r\n".encode("ascii") -lf_bytes = "\n".encode("ascii") +crlf_bytes = b"\r\n" +lf_bytes = b"\n" # re from pep263 - but we use it both on bytes and strings. -re_encoding_bytes = re.compile("coding[:=]\s*([-\w.]+)".encode("ascii")) -re_encoding_text = re.compile("coding[:=]\s*([-\w.]+)") +re_encoding_bytes = re.compile(rb"coding[:=]\s*([-\w.]+)") +re_encoding_text = re.compile(r"coding[:=]\s*([-\w.]+)") ParentScintillaDocument = docview.Document @@ -167,7 +169,7 @@ def _SaveTextToFile(self, view, filename, encoding=None): source_encoding = self.source_encoding else: # no BOM - look for an encoding. - bits = re.split("[\r\n]+", s, 3) + bits = re.split(r"[\r\n]+", s, 3) for look in bits[:-1]: match = re_encoding_text.search(look) if match is not None: diff --git a/Pythonwin/pywin/scintilla/view.py b/Pythonwin/pywin/scintilla/view.py index 5591327324..910161bad4 100644 --- a/Pythonwin/pywin/scintilla/view.py +++ b/Pythonwin/pywin/scintilla/view.py @@ -1,23 +1,20 @@ # A general purpose MFC CCtrlView view that uses Scintilla. -from . import control -from . import IDLEenvironment # IDLE emulation. -from pywin.mfc import docview -from pywin.mfc import dialog -from . import scintillacon -import win32con -import win32ui -import afxres -import string import array +import os +import re +import string +import struct import sys -import types + import __main__ # for attribute lookup -from . import bindings -from . import keycodes -import struct -import re -import os +import afxres +import win32con +import win32ui +from pywin.mfc import dialog, docview + +from . import IDLEenvironment # IDLE emulation. +from . import bindings, control, keycodes, scintillacon PRINTDLGORD = 1538 IDC_PRINT_MAG_EDIT = 1010 @@ -25,7 +22,7 @@ wordbreaks = "._" + string.ascii_uppercase + string.ascii_lowercase + string.digits -patImport = re.compile("import (?P.*)") +patImport = re.compile(r"import (?P.*)") _event_commands = [ # File menu @@ -536,7 +533,7 @@ def list2dict(l): endpos = self.LineIndex(maxline) text = self.GetTextRange(self.LineIndex(minline), endpos) try: - l = re.findall(r"\b" + left + "\.\w+", text) + l = re.findall(r"\b" + left + r"\.\w+", text) except re.error: # parens etc may make an invalid RE, but this code wouldnt # benefit even if the RE did work :-) diff --git a/Pythonwin/pywin/tools/browser.py b/Pythonwin/pywin/tools/browser.py index 82ec508ec8..1733f0ab97 100644 --- a/Pythonwin/pywin/tools/browser.py +++ b/Pythonwin/pywin/tools/browser.py @@ -7,6 +7,7 @@ # >>> browser.Browse(your_module) import sys import types + import __main__ import win32ui from pywin.mfc import dialog @@ -245,13 +246,8 @@ def GetSubList(self): 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 + code = self.myobject.__code__ + globs = self.myobject.__globals__ ret.append(MakeHLI(code, "Code")) ret.append(MakeHLI(globs, "Globals")) self.InsertDocString(ret) @@ -367,7 +363,7 @@ def OnInitDialog(self): t, v, tb = sys.exc_info() strval = "Exception getting object value\n\n%s:%s" % (t, v) tb = None - strval = re.sub("\n", "\r\n", strval) + strval = re.sub(r"\n", "\r\n", strval) self.edit.ReplaceSel(strval) @@ -376,10 +372,11 @@ def ShowObject(object, title): dlg.DoModal() +import commctrl +import win32api + # And some mods for a sizable dialog from Sam Rushing! import win32con -import win32api -import commctrl class dynamic_browser(dialog.Dialog): diff --git a/Pythonwin/pywin/tools/hierlist.py b/Pythonwin/pywin/tools/hierlist.py index 780b295003..fc591666e1 100644 --- a/Pythonwin/pywin/tools/hierlist.py +++ b/Pythonwin/pywin/tools/hierlist.py @@ -13,14 +13,13 @@ # choice. However, you should investigate using the tree control directly # to provide maximum flexibility (but with extra work). -import sys -import win32ui -import win32con +import commctrl import win32api +import win32con +import win32ui +from pywin.mfc import dialog, docview, object, window from win32api import RGB -from pywin.mfc import object, window, docview, dialog -import commctrl # helper to get the text of an arbitary item def GetItemText(item): @@ -105,14 +104,8 @@ def HierInit(self, parent, listControl=None): # Used when window first exists. self.listControl.SetImageList(self.imageList, commctrl.LVSIL_NORMAL) # self.list.AttachObject(self) - ## ??? Need a better way to do this - either some way to detect if it's compiled with UNICODE - ## defined, and/or a way to switch the constants based on UNICODE ??? - if sys.version_info[0] < 3: - parent.HookNotify(self.OnTreeItemExpanding, commctrl.TVN_ITEMEXPANDINGA) - parent.HookNotify(self.OnTreeItemSelChanged, commctrl.TVN_SELCHANGEDA) - else: - parent.HookNotify(self.OnTreeItemExpanding, commctrl.TVN_ITEMEXPANDINGW) - parent.HookNotify(self.OnTreeItemSelChanged, commctrl.TVN_SELCHANGEDW) + parent.HookNotify(self.OnTreeItemExpanding, commctrl.TVN_ITEMEXPANDINGW) + parent.HookNotify(self.OnTreeItemSelChanged, commctrl.TVN_SELCHANGEDW) parent.HookNotify(self.OnTreeItemDoubleClick, commctrl.NM_DBLCLK) self.notify_parent = parent @@ -128,12 +121,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() @@ -356,11 +345,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/README.md b/README.md index 233c050093..f260155a12 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ This is the readme for the Python for Win32 (pywin32) extensions, which provides See [CHANGES.txt](https://github.com/mhammond/pywin32/blob/master/CHANGES.txt) for recent notable changes. -Only Python 3 is supported. If you want Python 2 support, you want build `228`. +Only Python 3.7+ is supported. If you want Python 2 support, you want build `228`. ## Docs @@ -33,6 +33,7 @@ closed. For such issues, please email the note that you must be subscribed to the list before posting. ## Binaries + [Binary releases are deprecated.](https://mhammond.github.io/pywin32_installers.html) While they are still provided, [find them here](https://github.com/mhammond/pywin32/releases) @@ -56,6 +57,7 @@ For unreleased changes, you can download builds made by [github actions](https:/ choose any "workflow" from the `main` branch and download its "artifacts") ### `The specified procedure could not be found` / `Entry-point not found` Errors? + A very common report is that people install pywin32, but many imports fail with errors similar to the above. @@ -101,7 +103,7 @@ be able to build most extensions and list any extensions that could not be built due to missing libraries - if the build actually fails with your configuration, please [open an issue](https://github.com/mhammond/pywin32/issues). -You will need to install pywin32 (using pip) before building from source, or +You will need to install pywin32 (using pip) before building from source, or use `python setup.py install --skip-verstamp`, because the default build process uses a win32api call.. ## Release process diff --git a/adodbapi/__init__.py b/adodbapi/__init__.py index e108ef905c..787f2161f3 100644 --- a/adodbapi/__init__.py +++ b/adodbapi/__init__.py @@ -3,30 +3,34 @@ Copyright (C) 2002 Henrik Ekelund, version 2.1 by Vernon Cole * http://sourceforge.net/projects/adodbapi """ -import sys import time -from .apibase import apilevel, threadsafety, paramstyle +from .adodbapi import Connection, Cursor, __version__, connect, dateconverter from .apibase import ( - Warning, - Error, - InterfaceError, + BINARY, + DATETIME, + NUMBER, + ROWID, + STRING, DatabaseError, DataError, - OperationalError, + Error, + FetchFailedError, IntegrityError, -) -from .apibase import ( + InterfaceError, InternalError, - ProgrammingError, NotSupportedError, - FetchFailedError, + OperationalError, + ProgrammingError, + Warning, + apilevel, + paramstyle, + threadsafety, ) -from .apibase import NUMBER, STRING, BINARY, DATETIME, ROWID - -from .adodbapi import connect, Connection, __version__, dateconverter, Cursor +# ----------------------------------------------------------- +# conversion functions mandated by PEP 249 def Binary(aString): """This function constructs an object capable of holding a binary (long) string value.""" return bytes(aString) diff --git a/adodbapi/adodbapi.py b/adodbapi/adodbapi.py index 165ae28f95..4a7276b5ff 100644 --- a/adodbapi/adodbapi.py +++ b/adodbapi/adodbapi.py @@ -23,23 +23,21 @@ DB-API 2.0 specification: http://www.python.org/dev/peps/pep-0249/ -This module source should run correctly in CPython versions 2.7 and later, -or IronPython version 2.7 and later, -or, after running through 2to3.py, CPython 3.4 or later. +This module source should run correctly in CPython 3.4 or later. """ -__version__ = "2.6.2.0" +__version__ = "3.7.0.0" version = "adodbapi v" + __version__ -import sys import copy import decimal import os +import sys import weakref -from . import process_connect_string from . import ado_consts as adc from . import apibase as api +from . import process_connect_string try: verbose = int(os.environ["ADODBAPI_VERBOSE"]) @@ -48,49 +46,29 @@ if verbose: print(version) -# --- define objects to smooth out IronPython <-> CPython differences onWin32 = False # assume the worst -if api.onIronPython: - from System import Activator, Type, DBNull, DateTime, Array, Byte - from System import Decimal as SystemDecimal - from clr import Reference - - def Dispatch(dispatch): - type = Type.GetTypeFromProgID(dispatch) - return Activator.CreateInstance(type) - - def getIndexedValue(obj, index): - return obj.Item[index] +try: + import pythoncom + import pywintypes + import win32com.client -else: # try pywin32 - try: - import win32com.client - import pythoncom - import pywintypes + onWin32 = True +except ImportError: + import warnings - onWin32 = True + warnings.warn("pywin32 package required for adodbapi.", ImportWarning) - def Dispatch(dispatch): - return win32com.client.Dispatch(dispatch) - except ImportError: - import warnings +def Dispatch(dispatch): + return win32com.client.Dispatch(dispatch) - warnings.warn( - "pywin32 package (or IronPython) required for adodbapi.", ImportWarning - ) - def getIndexedValue(obj, index): - return obj(index) +def getIndexedValue(obj, index): + return obj(index) from collections.abc import Mapping -# --- define objects to smooth out Python3000 <-> Python 2.x differences -unicodeType = str -longType = int -StringTypes = str -maxint = sys.maxsize # ----------------- The .connect method ----------------- def make_COM_connecter(): @@ -192,7 +170,7 @@ def _configure_parameter(p, value, adotype, settings_known): p.Size = len(value) p.AppendChunk(value) - elif isinstance(value, StringTypes): # v2.1 Jevon + elif isinstance(value, str): # v2.1 Jevon L = len(value) if adotype in api.adoStringTypes: # v2.2.1 Cole if settings_known: @@ -204,12 +182,7 @@ def _configure_parameter(p, value, adotype, settings_known): p.Size = L # v2.1 Jevon elif isinstance(value, decimal.Decimal): - if api.onIronPython: - s = str(value) - p.Value = s - p.Size = len(s) - else: - p.Value = value + p.Value = value exponent = value.as_tuple()[2] digit_count = len(value.as_tuple()[1]) p.Precision = digit_count @@ -232,10 +205,6 @@ def _configure_parameter(p, value, adotype, settings_known): p.Value = s p.Size = len(s) - elif api.onIronPython and isinstance(value, longType): # Iron Python Long - s = str(value) # feature workaround for IPy 2.0 - p.Value = s - elif adotype == adc.adEmpty: # ADO will not let you specify a null column p.Type = ( adc.adInteger @@ -248,7 +217,7 @@ def _configure_parameter(p, value, adotype, settings_known): # # # # # ----- the Class that defines a connection ----- # # # # # -class Connection(object): +class Connection: # include connection attributes as class attributes required by api definition. Warning = api.Warning Error = api.Error @@ -559,7 +528,7 @@ def get_table_names(self): # # # # # ----- the Class that defines a cursor ----- # # # # # -class Cursor(object): +class Cursor: ## ** api required attributes: ## description... ## This read-only attribute is a sequence of 7-item sequences. @@ -647,7 +616,7 @@ def build_column_info(self, recordset): self.numberOfColumns = 0 return self.rs = recordset # v2.1.1 bkline - self.recordset_format = api.RS_ARRAY if api.onIronPython else api.RS_WIN_32 + self.recordset_format = api.RS_WIN_32 self.numberOfColumns = recordset.Fields.Count try: varCon = self.connection.variantConversions @@ -784,12 +753,7 @@ def _execute_command(self): print('Executing command="%s"' % self.commandText) try: # ----- the actual SQL is executed here --- - if api.onIronPython: - ra = Reference[int]() - recordset = self.cmd.Execute(ra) - count = ra.Value - else: # pywin32 - recordset, count = self.cmd.Execute() + recordset, count = self.cmd.Execute() # ----- ------------------------------- --- except (Exception) as e: _message = "" @@ -1174,21 +1138,11 @@ def nextset(self): ) return None - if api.onIronPython: - try: - recordset = self.rs.NextRecordset() - except TypeError: - recordset = None - except api.Error as exc: - self._raiseCursorError(api.NotSupportedError, exc.args) - else: # pywin32 - try: # [begin 2.1 ekelund] - rsTuple = self.rs.NextRecordset() # - except pywintypes.com_error as exc: # return appropriate error - self._raiseCursorError( - api.NotSupportedError, exc.args - ) # [end 2.1 ekelund] - recordset = rsTuple[0] + try: # [begin 2.1 ekelund] + rsTuple = self.rs.NextRecordset() # + except pywintypes.com_error as exc: # return appropriate error + self._raiseCursorError(api.NotSupportedError, exc.args) # [end 2.1 ekelund] + recordset = rsTuple[0] if recordset is None: return None self.build_column_info(recordset) diff --git a/adodbapi/apibase.py b/adodbapi/apibase.py index 10e127b554..46be10285f 100644 --- a/adodbapi/apibase.py +++ b/adodbapi/apibase.py @@ -5,40 +5,17 @@ * http://sourceforge.net/projects/adodbapi """ -import sys -import time import datetime import decimal import numbers +import sys +import time # noinspection PyUnresolvedReferences from . import ado_consts as adc verbose = False # debugging flag -onIronPython = sys.platform == "cli" -if onIronPython: # we need type definitions for odd data we may need to convert - # noinspection PyUnresolvedReferences - from System import DBNull, DateTime - - NullTypes = (type(None), DBNull) -else: - DateTime = type(NotImplemented) # should never be seen on win32 - NullTypes = type(None) - -# --- define objects to smooth out Python3 <-> Python 2.x differences -unicodeType = str -longType = int -StringTypes = str -makeByteBuffer = bytes -memoryViewType = memoryview -_BaseException = Exception - -try: # jdhardy -- handle bytes under IronPython & Py3 - bytes -except NameError: - bytes = str # define it for old Pythons - # ------- Error handlers ------ def standardErrorHandler(connection, cursor, errorclass, errorvalue): err = (errorclass, errorvalue) @@ -54,8 +31,7 @@ def standardErrorHandler(connection, cursor, errorclass, errorvalue): raise errorclass(errorvalue) -# Note: _BaseException is defined differently between Python 2.x and 3.x -class Error(_BaseException): +class Error(Exception): pass # Exception that is the base class of all other error # exceptions. You can use this to catch all errors with one # single 'except' statement. Warnings are not considered @@ -64,7 +40,7 @@ class Error(_BaseException): # module exceptions). -class Warning(_BaseException): +class Warning(Exception): pass @@ -161,10 +137,10 @@ class FetchFailedError(OperationalError): # # def Binary(aString): # """This function constructs an object capable of holding a binary (long) string value. """ -# b = makeByteBuffer(aString) +# b = bytes(aString) # return b # ----- Time converters ---------------------------------------------- -class TimeConverter(object): # this is a generic time converter skeleton +class TimeConverter: # this is a generic time converter skeleton def __init__(self): # the details will be filled in by instances self._ordinal_1899_12_31 = datetime.date(1899, 12, 31).toordinal() - 1 # Use cls.types to compare if an input parameter is a datetime @@ -190,11 +166,8 @@ def COMDate(self, obj): except: # might be a tuple try: return self.ComDateFromTuple(obj) - except: # try an mxdate - try: - return obj.COMDate() - except: - raise ValueError('Cannot convert "%s" to COMdate.' % repr(obj)) + except: + raise ValueError('Cannot convert "%s" to COMdate.' % repr(obj)) def ComDateFromTuple(self, t, microseconds=0): d = datetime.date(t[0], t[1], t[2]) @@ -228,48 +201,13 @@ def DateObjectToIsoFormatString(self, obj): if isinstance(obj, datetime.date): s = obj.isoformat() + " 00:00:00" # return exact midnight else: - try: # maybe it has a strftime method, like mx - s = obj.strftime("%Y-%m-%d %H:%M:%S") - except AttributeError: - try: # but may be time.struct_time - s = time.strftime("%Y-%m-%d %H:%M:%S", obj) - except: - raise ValueError('Cannot convert "%s" to isoformat' % repr(obj)) + try: # maybe time.struct_time + s = time.strftime("%Y-%m-%d %H:%M:%S", obj) + except: + raise ValueError('Cannot convert "%s" to isoformat' % repr(obj)) return s -# -- Optional: if mx extensions are installed you may use mxDateTime ---- -try: - import mx.DateTime - - mxDateTime = True -except: - mxDateTime = False -if mxDateTime: - - class mxDateTimeConverter(TimeConverter): # used optionally if installed - def __init__(self): - TimeConverter.__init__(self) - self.types.add(type(mx.DateTime)) - - def DateObjectFromCOMDate(self, comDate): - return mx.DateTime.DateTimeFromCOMDate(comDate) - - def Date(self, year, month, day): - return mx.DateTime.Date(year, month, day) - - def Time(self, hour, minute, second): - return mx.DateTime.Time(hour, minute, second) - - def Timestamp(self, year, month, day, hour, minute, second): - return mx.DateTime.Timestamp(year, month, day, hour, minute, second) - -else: - - class mxDateTimeConverter(TimeConverter): - pass # if no mx is installed - - class pythonDateTimeConverter(TimeConverter): # standard since Python 2.3 def __init__(self): TimeConverter.__init__(self) @@ -281,8 +219,6 @@ def DateObjectFromCOMDate(self, comDate): new = datetime.datetime.combine(datetime.datetime.fromordinal(odn), tim) return new # return comDate.replace(tzinfo=None) # make non aware - elif isinstance(comDate, DateTime): - fComDate = comDate.ToOADate() # ironPython clr Date/Time else: fComDate = float(comDate) # ComDate is number of days since 1899-12-31 integerPart = int(fComDate) @@ -314,8 +250,6 @@ def DateObjectFromCOMDate(self, comDate): "Returns ticks since 1970" if isinstance(comDate, datetime.datetime): return comDate.timetuple() - elif isinstance(comDate, DateTime): # ironPython clr date/time - fcomDate = comDate.ToOADate() else: fcomDate = float(comDate) secondsperday = 86400 # 24*60*60 @@ -391,7 +325,7 @@ def Timestamp(self, year, month, day, hour, minute, second): ) # this class is a trick to determine whether a type is a member of a related group of types. see PEP notes -class DBAPITypeObject(object): +class DBAPITypeObject: def __init__(self, valuesTuple): self.values = frozenset(valuesTuple) @@ -423,7 +357,7 @@ def __ne__(self, other): # ------- utilities for translating python data types to ADO data types --------------------------------- typeMap = { - memoryViewType: adc.adVarBinary, + memoryview: adc.adVarBinary, float: adc.adDouble, type(None): adc.adEmpty, str: adc.adBSTR, @@ -446,7 +380,7 @@ def pyTypeToADOType(d): ): # maybe it is one of our supported Date/Time types return adc.adDate # otherwise, attempt to discern the type by probing the data object itself -- to handle duck typing - if isinstance(d, StringTypes): + if isinstance(d, str): return adc.adBSTR if isinstance(d, numbers.Integral): return adc.adBigInt @@ -460,17 +394,13 @@ def pyTypeToADOType(d): # ------------------------------------------------------------------------ # variant type : function converting variant to Python value def variantConvertDate(v): - from . import dateconverter # this function only called when adodbapi is running + # this function only called when adodbapi is running + from . import dateconverter return dateconverter.DateObjectFromCOMDate(v) def cvtString(variant): # use to get old action of adodbapi v1 if desired - if onIronPython: - try: - return variant.ToString() - except: - pass return str(variant) @@ -520,19 +450,12 @@ def identity(x): def cvtUnusual(variant): if verbose > 1: sys.stderr.write("Conversion called for Unusual data=%s\n" % repr(variant)) - if isinstance(variant, DateTime): # COMdate or System.Date - from .adodbapi import ( - dateconverter, - ) # this will only be called when adodbapi is in use, and very rarely - - return dateconverter.DateObjectFromCOMDate(variant) return variant # cannot find conversion function -- just give the data to the user def convert_to_python(variant, func): # convert DB value into Python value - if isinstance(variant, NullTypes): # IronPython Null or None - return None - return func(variant) # call the appropriate conversion function + # call the appropriate conversion function + return None if variant is None else func(variant) class MultiMap(dict): # builds a dictionary from {(sequence,of,keys) : function} @@ -575,7 +498,7 @@ def __setitem__(self, adoType, cvtFn): RS_WIN_32, RS_ARRAY, RS_REMOTE = list(range(1, 4)) -class SQLrow(object): # a single database row +class SQLrow: # a single database row # class to emulate a sequence, so that a column may be retrieved by either number or name def __init__(self, rows, index): # "rows" is an _SQLrows object, index is which row self.rows = rows # parent 'fetch' container object @@ -651,7 +574,7 @@ def __str__(self): # create a pretty human readable representation # # # # -class SQLrows(object): +class SQLrows: # class to emulate a sequence for multiple rows using a container object def __init__(self, ado_results, numberOfRows, cursor): self.ado_results = ado_results # raw result of SQL get diff --git a/adodbapi/is64bit.py b/adodbapi/is64bit.py index 911c61931e..e198e9cba8 100644 --- a/adodbapi/is64bit.py +++ b/adodbapi/is64bit.py @@ -3,15 +3,7 @@ def Python(): - if sys.platform == "cli": # IronPython - import System - - return System.IntPtr.Size == 8 - else: - try: - return sys.maxsize > 2147483647 - except AttributeError: - return sys.maxint > 2147483647 + return sys.maxsize > 2147483647 def os(): diff --git a/adodbapi/quick_reference.md b/adodbapi/quick_reference.md index e4bc9f9cfe..8ee5326968 100644 --- a/adodbapi/quick_reference.md +++ b/adodbapi/quick_reference.md @@ -107,27 +107,19 @@ access api specification is found at: The PEP requires several module level attributes. Older versions of adodbapi (which was once all one big file) defined a hundred or two. I hate that, but can\'t break old code, so I decided to fix the problem -for Python 3. If using Python3 the programmer must take the time to pick +for Python 3. The programmer must take the time to pick up the symbols she needs from apibase and ado\_consts. Part of the adodbapi package\'s \_\_init\_\_.py looks something like this: ```python -if sys.version_info < (3,0): # in Python 2, define all symbols, just like before - from apibase import * # using this is bad - from ado_consts import * # using this is worse -else: - # but if the user is running Python 3, then keep the dictionary clean - from apibase import apilevel, threadsafety, paramstyle - from apibase import Warning, Error, InterfaceError, DatabaseError, DataError - from apibase import OperationalError, IntegrityError - from apibase import InternalError, ProgrammingError, NotSupportedError - from apibase import NUMBER, STRING, BINARY, DATETIME, ROWID - -from adodbapi import connect, Connection, __version__ -version = 'adodbapi v' + __version__ +from .apibase import BINARY, DATETIME, NUMBER, ROWID, STRING, DatabaseError, DataError, Error, FetchFailedError, IntegrityError, InterfaceError, InternalError, NotSupportedError, OperationalError, ProgrammingError, Warning, apilevel, paramstyle, threadsafety + +from .adodbapi import Connection, Cursor, __version__, connect, dateconverter +version = "adodbapi v" + __version__ ``` + Please, use only those last four symbols from adodbapi. All others should be imported directly from their own sub-modules. My tests and examples all follow that rule. @@ -781,7 +773,7 @@ Running the tests The test folder contains a set of unittest programs. Setting them up can be a bit complex, because you need several database servers to do a complete test, and each one has a different configuration. Scripts in -this folder try to work in Python 2.7 or Python 3.5(+) +this folder try to work in Python 3.5(+) - dbapi20.py diff --git a/adodbapi/readme.txt b/adodbapi/readme.txt index 02bb620f4d..d251411036 100644 --- a/adodbapi/readme.txt +++ b/adodbapi/readme.txt @@ -2,7 +2,7 @@ Project ------- adodbapi -A Python DB-API 2.0 (PEP-249) module that makes it easy to use Microsoft ADO +A Python DB-API 2.0 (PEP-249) module that makes it easy to use Microsoft ADO for connecting with databases and other data sources using either CPython or IronPython. @@ -10,9 +10,9 @@ Home page: Features: * 100% DB-API 2.0 (PEP-249) compliant (including most extensions and recommendations). -* Includes pyunit testcases that describe how to use the module. -* Fully implemented in Python. -- runs in Python 2.5+ Python 3.0+ and IronPython 2.6+ -* Licensed under the LGPL license, which means that it can be used freely even in commercial programs subject to certain restrictions. +* Includes pyunit testcases that describe how to use the module. +* Fully implemented in Python. -- runs in Python 3.0+ +* Licensed under the LGPL license, which means that it can be used freely even in commercial programs subject to certain restrictions. * The user can choose between paramstyles: 'qmark' 'named' 'format' 'pyformat' 'dynamic' * Supports data retrieval by column name e.g.: for row in myCurser.execute("select name,age from students"): @@ -20,10 +20,9 @@ Features: * Supports user-definable system-to-Python data conversion functions (selected by ADO data type, or by column) Prerequisites: -* C Python 2.7 or 3.5 or higher +* C Python 3.5 or higher and pywin32 (Mark Hammond's python for windows extensions.) -or - Iron Python 2.7 or higher. (works in IPy2.0 for all data types except BUFFER) + Installation: * (C-Python on Windows): Install pywin32 ("pip install pywin32") which includes adodbapi. @@ -33,7 +32,7 @@ Installation: NOTE: ........... If you do not like the new default operation of returning Numeric columns as decimal.Decimal, -you can select other options by the user defined conversion feature. +you can select other options by the user defined conversion feature. Try: adodbapi.apibase.variantConversions[adodbapi.ado_consts.adNumeric] = adodbapi.apibase.cvtString or: @@ -86,7 +85,7 @@ and look at the test cases in adodbapi/test directory. Mailing lists ------------- -The adodbapi mailing lists have been deactivated. Submit comments to the +The adodbapi mailing lists have been deactivated. Submit comments to the pywin32 or IronPython mailing lists. -- the bug tracker on sourceforge.net/projects/adodbapi may be checked, (infrequently). -- please use: https://github.com/mhammond/pywin32/issues diff --git a/adodbapi/remote.py b/adodbapi/remote.py index 2b98badb98..455e2fe7e4 100644 --- a/adodbapi/remote.py +++ b/adodbapi/remote.py @@ -22,25 +22,23 @@ DB-API 2.0 specification: http://www.python.org/dev/peps/pep-0249/ -This module source should run correctly in CPython versions 2.5 and later, -or IronPython version 2.7 and later, -or, after running through 2to3.py, CPython 3.0 or later. +This module source should run correctly in CPython 3.0 or later. """ -__version__ = "2.6.0.4" +__version__ = "3.7.0.0" version = "adodbapi.remote v" + __version__ +import array +import datetime import os import sys -import array import time -import datetime # Pyro4 is required for server and remote operation --> https://pypi.python.org/pypi/Pyro4/ try: import Pyro4 except ImportError: - print('* * * Sorry, server operation requires Pyro4. Please "pip import" it.') + print('* * * Sorry, server operation requires Pyro4. Please "pip install" it.') exit(11) import adodbapi @@ -48,8 +46,6 @@ import adodbapi.process_connect_string from adodbapi.apibase import ProgrammingError -_BaseException = api._BaseException - sys.excepthook = Pyro4.util.excepthook Pyro4.config.PREFER_IP_VERSION = 0 # allow system to prefer IPv6 Pyro4.config.COMMTIMEOUT = 40.0 # a bit longer than the default SQL server Gtimeout @@ -62,16 +58,11 @@ if verbose: print(version) -# --- define objects to smooth out Python3 <-> Python 2.x differences -unicodeType = str # this line will be altered by 2to3.py to '= str' -longType = int # this line will be altered by 2to3.py to '= int' -StringTypes = str -makeByteBuffer = bytes -memoryViewType = memoryview - # ----------------------------------------------------------- # conversion functions mandated by PEP 249 -Binary = makeByteBuffer # override the function from apibase.py +def Binary(aString): + """This function constructs an object capable of holding a binary (long) string value.""" + return bytes(aString) def Date(year, month, day): @@ -168,7 +159,7 @@ def connect(*args, **kwargs): # --> a remote db-api connection object raise api.DatabaseError( "Pyro error creating connection to/thru=%s" % repr(kwargs) ) - except _BaseException as e: + except Exception as e: raise api.DatabaseError( "Error creating remote connection to=%s, e=%s, %s" % (repr(kwargs), repr(e), sys.exc_info()[2]) @@ -188,7 +179,7 @@ def fix_uri(uri, kwargs): # # # # # ----- the Class that defines a connection ----- # # # # # -class Connection(object): +class Connection: # include connection attributes required by api definition. Warning = api.Warning Error = api.Error @@ -368,7 +359,7 @@ def fixpickle(x): # for 'named' paramstyle user will pass a mapping newargs = {} for arg, val in list(x.items()): - if isinstance(val, memoryViewType): + if isinstance(val, memoryview): newval = array.array("B") newval.fromstring(val) newargs[arg] = newval @@ -378,7 +369,7 @@ def fixpickle(x): # if not a mapping, then a sequence newargs = [] for arg in x: - if isinstance(arg, memoryViewType): + if isinstance(arg, memoryview): newarg = array.array("B") newarg.fromstring(arg) newargs.append(newarg) @@ -387,7 +378,7 @@ def fixpickle(x): return newargs -class Cursor(object): +class Cursor: def __init__(self, connection): self.command = None self.errorhandler = None ## was: connection.errorhandler @@ -569,7 +560,7 @@ def callproc(self, procname, parameters=None): def fetchone(self): try: f1 = self.proxy.crsr_fetchone(self.id) - except _BaseException as e: + except Exception as e: self._raiseCursorError(api.DatabaseError, e) else: if f1 is None: diff --git a/adodbapi/remote/server.py b/adodbapi/remote/server.py index 15727b0a47..36b217448d 100644 --- a/adodbapi/remote/server.py +++ b/adodbapi/remote/server.py @@ -19,38 +19,33 @@ DB-API 2.0 specification: http://www.python.org/dev/peps/pep-0249/ -This module source should run correctly in CPython versions 2.6 and later, -or IronPython version 2.6 and later, -or, after running through 2to3.py, CPython 3.2 or later. +This module source should run correctly in CPython 3.2 or later. """ -__version__ = "2.6.2.0" +__version__ = "3.7.0.0" version = "adodbapi.server v" + __version__ PYRO_HOST = "::0" # '::0' or '0.0.0.0' means any network -PYRO_PORT = 9099 # may be altered below for Python 3 based servers +PYRO_PORT = 9099 # may be altered below for Python based servers PYRO_COMMTIMEOUT = 40 # to be larger than the default database timeout SERVICE_NAME = "ado.connection" +import array +import datetime import os import sys import time -import array -import datetime # Pyro4 is required for server and remote operation --> https://pypi.python.org/pypi/Pyro4/ try: import Pyro4 except ImportError: - print('* * * Sorry, server operation requires Pyro4. Please "pip import" it.') + print('* * * Sorry, server operation requires Pyro4. Please "pip install" it.') exit(11) -import adodbapi.apibase as api import adodbapi +import adodbapi.apibase as api import adodbapi.process_connect_string -makeByteBuffer = bytes -_BaseException = Exception -Binary = bytes try: pyro_host = os.environ["PYRO_HOST"] except: @@ -64,25 +59,25 @@ if arg.lower().startswith("host"): try: pyro_host = arg.split("=")[1] - except _BaseException: + except Exception: raise TypeError('Must supply value for argument="%s"' % arg) if arg.lower().startswith("port"): try: pyro_port = int(arg.split("=")[1]) - except _BaseException: + except Exception: raise TypeError('Must supply numeric value for argument="%s"' % arg) if arg.lower().startswith("timeout"): try: PYRO_COMMTIMEOUT = int(arg.split("=")[1]) - except _BaseException: + except Exception: raise TypeError('Must supply numeric value for argument="%s"' % arg) if arg.lower().startswith("--verbose"): try: verbose = int(arg.split("=")[1]) - except _BaseException: + except Exception: raise TypeError('Must supply numeric value for argument="%s"' % arg) adodbapi.adodbapi.verbose = verbose else: @@ -97,7 +92,7 @@ Pyro4.config.PREFER_IP_VERSION = 0 # allow system to prefer IPv6 Pyro4.config.SERIALIZERS_ACCEPTED = set( ["serpent", "pickle"] -) # change when Py2.5 retired +) # TODO: change when Py2.5 retired connection_list = [] CONNECTION_TIMEOUT = datetime.timedelta(minutes=30) @@ -119,7 +114,7 @@ def unfixpickle(x): newargs = {} for arg, val in list(x.items()): if isinstance(arg, type(array.array("B"))): - newargs[arg] = Binary(val) + newargs[arg] = bytes(val) else: newargs[arg] = val return newargs @@ -127,13 +122,13 @@ def unfixpickle(x): newargs = [] for arg in x: if isinstance(arg, type(array.array("B"))): - newargs.append(Binary(arg)) + newargs.append(bytes(arg)) else: newargs.append(arg) return newargs -class ServerConnection(object): +class ServerConnection: def __init__(self): self.server_connection = None self.cursors = {} @@ -312,14 +307,14 @@ def suicide(self): print("Shutdown request received") -class ConnectionDispatcher(object): +class ConnectionDispatcher: def make_connection(self): new_connection = ServerConnection() pyro_uri = self._pyroDaemon.register(new_connection) return pyro_uri -class Heartbeat_Timer(object): +class Heartbeat_Timer: def __init__(self, interval, work_function, tick_result_function): self.interval = interval self.last_tick = datetime.datetime.now() diff --git a/adodbapi/setup.py b/adodbapi/setup.py index 87e71ed6f1..bd85486d2b 100644 --- a/adodbapi/setup.py +++ b/adodbapi/setup.py @@ -1,7 +1,6 @@ """adodbapi -- a pure Python PEP 249 DB-API package using Microsoft ADO Adodbapi can be run on CPython 3.5 and later. -or IronPython version 2.6 and later (in theory, possibly no longer in practice!) """ CLASSIFIERS = """\ Development Status :: 5 - Production/Stable @@ -39,13 +38,11 @@ break a.close() -import sys - def setup_package(): - from distutils.core import setup from distutils.command.build_py import build_py + from distutils.core import setup setup( cmdclass={"build_py": build_py}, diff --git a/adodbapi/test/adodbapitest.py b/adodbapi/test/adodbapitest.py index e60014c662..09bdf9e418 100644 --- a/adodbapi/test/adodbapitest.py +++ b/adodbapi/test/adodbapitest.py @@ -21,13 +21,13 @@ Updates by Vernon Cole """ -import unittest -import sys +import copy import datetime import decimal -import copy import random import string +import sys +import unittest try: import win32com.client @@ -45,7 +45,6 @@ import adodbapi import adodbapi.apibase as api - try: import adodbapi.ado_consts as ado_consts except ImportError: # we are doing a shortcut import as a module -- so @@ -55,13 +54,6 @@ from adodbapi import ado_consts -def str2bytes(sval): - return sval.encode("latin1") - - -long = int - - def randomstring(length): return "".join([random.choice(string.ascii_letters) for n in range(32)]) @@ -217,49 +209,6 @@ def testUserDefinedConversions(self): pass self.helpRollbackTblTemp() - def testUserDefinedConversionForExactNumericTypes(self): - # variantConversions is a dictionary of conversion functions - # held internally in adodbapi.apibase - # - # !!! this test intentionally alters the value of what should be constant in the module - # !!! no new code should use this example, to is only a test to see that the - # !!! deprecated way of doing this still works. (use connection.variantConversions) - # - if not self.remote and sys.version_info < (3, 0): ### Py3 need different test - oldconverter = adodbapi.variantConversions[ - ado_consts.adNumeric - ] # keep old function to restore later - # By default decimal and "numbers" are returned as decimals. - # Instead, make numbers return as floats - try: - adodbapi.variantConversions[ado_consts.adNumeric] = adodbapi.cvtFloat - self.helpTestDataType( - "decimal(18,2)", "NUMBER", 3.45, compareAlmostEqual=1 - ) - self.helpTestDataType( - "numeric(18,2)", "NUMBER", 3.45, compareAlmostEqual=1 - ) - # now return strings - adodbapi.variantConversions[ado_consts.adNumeric] = adodbapi.cvtString - self.helpTestDataType("numeric(18,2)", "NUMBER", "3.45") - # now a completly weird user defined convertion - adodbapi.variantConversions[ado_consts.adNumeric] = ( - lambda x: "!!This function returns a funny unicode string %s!!" % x - ) - self.helpTestDataType( - "numeric(18,2)", - "NUMBER", - "3.45", - allowedReturnValues=[ - "!!This function returns a funny unicode string 3.45!!" - ], - ) - finally: - # now reset the converter to its original function - adodbapi.variantConversions[ - ado_consts.adNumeric - ] = oldconverter # Restore the original convertion function - def helpTestDataType( self, sqlDataTypeString, @@ -520,7 +469,7 @@ def testDataTypeDate(self): ) def testDataTypeBinary(self): - binfld = str2bytes("\x07\x00\xE2\x40*") + binfld = b"\x07\x00\xE2\x40*" arv = [binfld, adodbapi.Binary(binfld), bytes(binfld)] if self.getEngine() == "PostgreSQL": self.helpTestDataType( @@ -1526,37 +1475,6 @@ def testIsoFormat(self): self.assertEqual(str(iso[:10]), "2003-05-02") -if config.doMxDateTimeTest: - import mx.DateTime - - -class TestMXDateTimeConverter(TimeConverterInterfaceTest): - def setUp(self): - self.tc = api.mxDateTimeConverter() - - def testCOMDate(self): - t = mx.DateTime.DateTime(2002, 6, 28, 18, 15, 2) - cmd = self.tc.COMDate(t) - assert cmd == t.COMDate() - - def testDateObjectFromCOMDate(self): - cmd = self.tc.DateObjectFromCOMDate(37435.7604282) - t = mx.DateTime.DateTime(2002, 6, 28, 18, 15, 0) - t2 = mx.DateTime.DateTime(2002, 6, 28, 18, 15, 2) - assert t2 > cmd > t - - def testDate(self): - assert mx.DateTime.Date(1980, 11, 4) == self.tc.Date(1980, 11, 4) - - def testTime(self): - assert mx.DateTime.Time(13, 11, 4) == self.tc.Time(13, 11, 4) - - def testTimestamp(self): - t = mx.DateTime.DateTime(2002, 6, 28, 18, 15, 1) - obj = self.tc.Timestamp(2002, 6, 28, 18, 15, 1) - assert t == obj - - import time @@ -1644,11 +1562,8 @@ def testTimestamp(self): suites = [] suites.append(unittest.makeSuite(TestPythonDateTimeConverter, "test")) -if config.doMxDateTimeTest: - suites.append(unittest.makeSuite(TestMXDateTimeConverter, "test")) if config.doTimeTest: suites.append(unittest.makeSuite(TestPythonTimeConverter, "test")) - if config.doAccessTest: suites.append(unittest.makeSuite(TestADOwithAccessDB, "test")) if config.doSqlServerTest: @@ -1659,7 +1574,7 @@ def testTimestamp(self): suites.append(unittest.makeSuite(TestADOwithPostgres, "test")) -class cleanup_manager(object): +class cleanup_manager: def __enter__(self): pass @@ -1678,16 +1593,11 @@ def __exit__(self, exc_type, exc_val, exc_tb): tag = "datetime" unittest.TextTestRunner().run(mysuite) - if config.iterateOverTimeTests: - for test, dateconverter, tag in ( - (config.doTimeTest, api.pythonTimeConverter, "pythontime"), - (config.doMxDateTimeTest, api.mxDateTimeConverter, "mx"), - ): - if test: - mysuite = copy.deepcopy( - suite - ) # work around a side effect of unittest.TextTestRunner - adodbapi.adodbapi.dateconverter = dateconverter() - print("Changed dateconverter to ") - print(adodbapi.adodbapi.dateconverter) - unittest.TextTestRunner().run(mysuite) + if config.doTimeTest: + mysuite = copy.deepcopy( + suite + ) # work around a side effect of unittest.TextTestRunner + adodbapi.adodbapi.dateconverter = api.pythonTimeConverter() + print("Changed dateconverter to ") + print(adodbapi.adodbapi.dateconverter) + unittest.TextTestRunner().run(mysuite) diff --git a/adodbapi/test/adodbapitestconfig.py b/adodbapi/test/adodbapitestconfig.py index c2a41898ef..e3ec196ced 100644 --- a/adodbapi/test/adodbapitestconfig.py +++ b/adodbapi/test/adodbapitestconfig.py @@ -12,8 +12,8 @@ # # -- the things you need to change are below it. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # import platform -import sys import random +import sys import is64bit import setuptestframework @@ -32,14 +32,14 @@ if "--help" in sys.argv: print( """Valid command-line switches are: - --package - create a temporary test package, run 2to3 if needed. + --package - create a temporary test package --all - run all possible tests - --time - loop over time format tests (including mxdatetime if present) + --time - do time format test --nojet - do not test against an ACCESS database file --mssql - test against Microsoft SQL server --pg - test against PostgreSQL --mysql - test against MariaDB - --remote= - test unsing remote server at= (experimental) + --remote= - test using remote server at= (experimental) """ ) exit() @@ -77,13 +77,8 @@ # function to clean up the temporary folder -- calling program must run this function before exit. cleanup = setuptestframework.getcleanupfunction() -try: - import adodbapi # will (hopefully) be imported using the "pth" discovered above -except SyntaxError: - print( - '\n* * * Are you trying to run Python2 code using Python3? Re-run this test using the "--package" switch.' - ) - sys.exit(11) +import adodbapi # will (hopefully) be imported using the "pth" discovered above + try: print(adodbapi.version) # show version except: @@ -106,21 +101,12 @@ doSqlServerTest = "--mssql" in sys.argv or doAllTests doMySqlTest = "--mysql" in sys.argv or doAllTests doPostgresTest = "--pg" in sys.argv or doAllTests -iterateOverTimeTests = ("--time" in sys.argv or doAllTests) and onWindows +doTimeTest = ("--time" in sys.argv or doAllTests) and onWindows # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # start your environment setup here v v v SQL_HOST_NODE = "testsql.2txt.us,1430" -try: # If mx extensions are installed, use mxDateTime - import mx.DateTime - - doMxDateTimeTest = True -except: - doMxDateTimeTest = False # Requires eGenixMXExtensions - -doTimeTest = True # obsolete python time format - if doAccessTest: if proxy_host: # determine the (probably remote) database file folder c = {"macro_find_temp_test_path": ["mdb", mdb_name], "proxy_host": proxy_host} diff --git a/adodbapi/test/dbapi20.py b/adodbapi/test/dbapi20.py index 0fef68a18c..3d6a8216ff 100644 --- a/adodbapi/test/dbapi20.py +++ b/adodbapi/test/dbapi20.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -""" Python DB API 2.0 driver compliance unit test suite. - +""" Python DB API 2.0 driver compliance unit test suite. + This software is Public Domain and may be used without restrictions. "Now we have booze and barflies entering the discussion, plus rumours of @@ -11,29 +11,23 @@ -- Ian Bicking """ -__version__ = "$Revision: 1.15.0 $"[11:-2] +__version__ = "$Revision: 1.16.0 $"[11:-2] __author__ = "Stuart Bishop " -import unittest import time -import sys - -if sys.version[0] >= "3": # python 3.x - _BaseException = Exception - - def _failUnless(self, expr, msg=None): - self.assertTrue(expr, msg) +import unittest -else: # python 2.x - from exceptions import Exception as _BaseException - def _failUnless(self, expr, msg=None): - self.failUnless(expr, msg) ## deprecated since Python 2.6 +def _failUnless(self, expr, msg=None): + self.assertTrue(expr, msg) # set this to "True" to follow API 2.0 to the letter TEST_FOR_NON_IDEMPOTENT_CLOSE = False +# Revision 1.16 2022/12/07 22:00:00 Avasam +# Drop support for EOL Python 3.6 and below + # Revision 1.15 2019/11/22 00:50:00 kf7xm # Make Turn off IDEMPOTENT_CLOSE a proper skipTest @@ -94,10 +88,6 @@ def _failUnless(self, expr, msg=None): # nothing # - Fix bugs in test_setoutputsize_basic and test_setinputsizes # -def str2bytes(sval): - if sys.version_info < (3, 0) and isinstance(sval, str): - sval = sval.decode("latin1") - return sval.encode("latin1") # python 3 make unicode into bytes class DatabaseAPI20Test(unittest.TestCase): @@ -169,7 +159,7 @@ def tearDown(self): pass finally: con.close() - except _BaseException: + except Exception: pass def _connect(self): @@ -215,12 +205,8 @@ def test_paramstyle(self): def test_Exceptions(self): # Make sure required exceptions exist, and are in the # defined heirarchy. - if sys.version[0] == "3": # under Python 3 StardardError no longer exists - self.assertTrue(issubclass(self.driver.Warning, Exception)) - self.assertTrue(issubclass(self.driver.Error, Exception)) - else: - self.failUnless(issubclass(self.driver.Warning, Exception)) - self.failUnless(issubclass(self.driver.Error, Exception)) + self.assertTrue(issubclass(self.driver.Warning, Exception)) + self.assertTrue(issubclass(self.driver.Error, Exception)) _failUnless(self, issubclass(self.driver.InterfaceError, self.driver.Error)) _failUnless(self, issubclass(self.driver.DatabaseError, self.driver.Error)) @@ -909,8 +895,8 @@ def test_Timestamp(self): # self.assertEqual(str(t1),str(t2)) def test_Binary(self): - b = self.driver.Binary(str2bytes("Something")) - b = self.driver.Binary(str2bytes("")) + b = self.driver.Binary(b"Something") + b = self.driver.Binary(b"") def test_STRING(self): _failUnless( diff --git a/adodbapi/test/is64bit.py b/adodbapi/test/is64bit.py index ed390fad00..2cc56ed929 100644 --- a/adodbapi/test/is64bit.py +++ b/adodbapi/test/is64bit.py @@ -3,15 +3,7 @@ def Python(): - if sys.platform == "cli": # IronPython - import System - - return System.IntPtr.Size == 8 - else: - try: - return sys.maxsize > 2147483647 - except AttributeError: - return sys.maxint > 2147483647 + return sys.maxsize > 2147483647 def os(): diff --git a/adodbapi/test/setuptestframework.py b/adodbapi/test/setuptestframework.py index 2f3f7d2dbf..39c14a494c 100644 --- a/adodbapi/test/setuptestframework.py +++ b/adodbapi/test/setuptestframework.py @@ -1,10 +1,9 @@ -#!/usr/bin/python2 +#!/usr/bin/python3 # Configure this in order to run the testcases. -"setuptestframework.py v 2.6.0.8" +"setuptestframework.py v 3.7.0.0" import os -import sys -import tempfile import shutil +import tempfile try: OSErrors = (WindowsError, OSError) @@ -59,13 +58,7 @@ def makeadopackage(testfolder): for f in os.listdir(adoPath): if f.endswith(".py"): shutil.copy(os.path.join(adoPath, f), newpackage) - if sys.version_info >= (3, 0): # only when running Py3.n - save = sys.stdout - sys.stdout = None - from lib2to3.main import main # use 2to3 to make test package - main("lib2to3.fixes", args=["-n", "-w", newpackage]) - sys.stdout = save return testfolder else: raise EnvironmentError("Connot find source of adodbapi to test.") @@ -81,16 +74,12 @@ def makemdb(testfolder, mdb_name): print("using JET database=", _accessdatasource) else: try: - from win32com.client.gencache import EnsureDispatch from win32com.client import constants + from win32com.client.gencache import EnsureDispatch win32 = True - except ImportError: # perhaps we are running IronPython - win32 = False # iron Python - try: - from System import Activator, Type - except: - pass + except ImportError: # perhaps we are not running CPython + win32 = False # Create a brand-new database - what is the story with these? dbe = None diff --git a/com/win32com/client/__init__.py b/com/win32com/client/__init__.py index 4970ec03d2..bd045b6753 100644 --- a/com/win32com/client/__init__.py +++ b/com/win32com/client/__init__.py @@ -6,12 +6,13 @@ # dispatch object, the known class will be used. This contrasts # with dynamic.Dispatch behaviour, where dynamic objects are always used. -import pythoncom -from . import dynamic -from . import gencache import sys + +import pythoncom import pywintypes +from . import dynamic, gencache + _PyIDispatchType = pythoncom.TypeIIDs[pythoncom.IID_IDispatch] @@ -330,16 +331,10 @@ class object that derives from three classes: # If the clsid was an object, get the clsid clsid = disp_class.CLSID # Create a new class that derives from 3 classes - the dispatch class, the event sink class and the user class. - # XXX - we are still "classic style" classes in py2x, so we need can't yet - # use 'type()' everywhere - revisit soon, as py2x will move to new-style too... - try: - from types import ClassType as new_type - except ImportError: - new_type = type # py3k events_class = getevents(clsid) if events_class is None: raise ValueError("This COM object does not support events.") - result_class = new_type( + result_class = type( "COMEventClass", (disp_class, events_class, user_event_class), {"__setattr__": _event_setattr_}, @@ -399,14 +394,10 @@ def WithEvents(disp, user_event_class): clsid = disp_class.CLSID # Create a new class that derives from 2 classes - the event sink # class and the user class. - try: - from types import ClassType as new_type - except ImportError: - new_type = type # py3k events_class = getevents(clsid) if events_class is None: raise ValueError("This COM object does not support events.") - result_class = new_type("COMEventClass", (events_class, user_event_class), {}) + result_class = type("COMEventClass", (events_class, user_event_class), {}) instance = result_class(disp) # This only calls the first base class __init__. if hasattr(user_event_class, "__init__"): user_event_class.__init__(instance) @@ -484,7 +475,7 @@ def Record(name, object): # XXX - to do - probably should allow "object" to already be a module object. from . import gencache - object = gencache.EnsureDispatch(object) + object = gencache.EnsureDispatch module = sys.modules[object.__class__.__module__] # to allow us to work correctly with "demand generated" code, # we must use the typelib CLSID to obtain the module @@ -690,7 +681,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 6d77b33a50..e40b8897db 100644 --- a/com/win32com/client/build.py +++ b/com/win32com/client/build.py @@ -16,21 +16,19 @@ # # OleItem, DispatchItem, MapEntry, BuildCallList() is used by makepy -import sys +import datetime import string from keyword import iskeyword import pythoncom -from pywintypes import TimeType import winerror -import datetime +from pywintypes import TimeType + # It isn't really clear what the quoting rules are in a C/IDL string and # 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) @@ -628,8 +626,8 @@ 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 + # TODO: "strides" would be handy here but don't exist in 2.2 for i in range(0, len(names), 5): names[i] = names[i] + "\n\t\t\t" return "," + ", ".join(names) @@ -664,7 +662,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: @@ -766,7 +764,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 dd95bfe883..93a24f4f91 100644 --- a/com/win32com/client/combrowse.py +++ b/com/win32com/client/combrowse.py @@ -22,12 +22,14 @@ work. """ -import win32con -import win32api, win32ui import sys + import pythoncom -from win32com.client import util +import win32api +import win32con +import win32ui from pywin.tools import browser +from win32com.client import util class HLIRoot(browser.HLIPythonObject): @@ -43,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 8f1d24f40c..0c75172c8b 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -16,9 +16,10 @@ import os import sys import time -import win32com import pythoncom +import win32com + from . import build error = "makepy.error" @@ -33,22 +34,22 @@ # does not use this map at runtime - all Alias/Enum have already # been translated. mapVTToTypeString = { - pythoncom.VT_I2: "types.IntType", - pythoncom.VT_I4: "types.IntType", - pythoncom.VT_R4: "types.FloatType", - pythoncom.VT_R8: "types.FloatType", - pythoncom.VT_BSTR: "types.StringType", - pythoncom.VT_BOOL: "types.IntType", - pythoncom.VT_VARIANT: "types.TypeType", - pythoncom.VT_I1: "types.IntType", - pythoncom.VT_UI1: "types.IntType", - pythoncom.VT_UI2: "types.IntType", - pythoncom.VT_UI4: "types.IntType", - pythoncom.VT_I8: "types.LongType", - pythoncom.VT_UI8: "types.LongType", - pythoncom.VT_INT: "types.IntType", - pythoncom.VT_DATE: "pythoncom.PyTimeType", - pythoncom.VT_UINT: "types.IntType", + pythoncom.VT_I2: "int", + pythoncom.VT_I4: "int", + pythoncom.VT_R4: "float", + pythoncom.VT_R8: "float", + pythoncom.VT_BSTR: "string", + pythoncom.VT_BOOL: "int", + pythoncom.VT_VARIANT: "type", + pythoncom.VT_I1: "int", + pythoncom.VT_UI1: "int", + pythoncom.VT_UI2: "int", + pythoncom.VT_UI4: "int", + pythoncom.VT_I8: "lint", + pythoncom.VT_UI8: "lint", + pythoncom.VT_INT: "int", + pythoncom.VT_DATE: "pythoncom.PyTimeType", # FIXME: Type does not exist anywhere; pywintypes.TimeType ? + pythoncom.VT_UINT: "int", } # Given a propget function's arg desc, return the default parameters for all @@ -105,16 +106,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 diff --git a/com/win32com/client/makepy.py b/com/win32com/client/makepy.py index 9c3b99600e..610178a0f7 100644 --- a/com/win32com/client/makepy.py +++ b/com/win32com/client/makepy.py @@ -66,13 +66,14 @@ """ -import sys, os, importlib, pythoncom -from win32com.client import genpy, selecttlb, gencache -from win32com.client import Dispatch +import importlib +import os +import sys -bForDemandDefault = 0 # Default value of bForDemand - toggle this to change the world - see also gencache.py +import pythoncom +from win32com.client import Dispatch, gencache, genpy, selecttlb -error = "makepy.error" +bForDemandDefault = 0 # Default value of bForDemand - toggle this to change the world - see also gencache.py def usage(): @@ -151,8 +152,9 @@ def LogWarning(self, desc): class GUIProgress(SimpleProgress): def __init__(self, verboseLevel): - # Import some modules we need to we can trap failure now. - import win32ui, pywin + # Import some modules we need so we can trap failure now. + import pywin + import win32ui SimpleProgress.__init__(self, verboseLevel) self.dialog = None @@ -406,7 +408,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() @@ -426,12 +428,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 f9f0b1ce37..1337bc468b 100644 --- a/com/win32com/client/selecttlb.py +++ b/com/win32com/client/selecttlb.py @@ -1,7 +1,9 @@ """Utilities for selecting and enumerating the Type Libraries installed on the system """ -import win32api, win32con, pythoncom +import pythoncom +import win32api +import win32con class TypelibSpec: @@ -25,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(), @@ -40,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 4e42961e61..7f5afb7947 100644 --- a/com/win32com/demos/connect.py +++ b/com/win32com/demos/connect.py @@ -6,10 +6,9 @@ # is cheated on - so this is still working as a fully-fledged server. import pythoncom -import win32com.server.util import win32com.server.connect +import win32com.server.util from win32com.server.exception import Exception -from pywin32_testutil import str2bytes # This is the IID of the Events interface both Client and Server support. IID_IConnectDemoEvents = pythoncom.MakeIID("{A4988850-49C3-11d0-AE5D-52342E000000}") @@ -75,7 +74,8 @@ def CheckEvent(server, client, val, verbose): # In the real world, it is likely that the code controlling the server # will be in the same class as that getting the notifications. def test(verbose=0): - import win32com.client.dynamic, win32com.client.connect + import win32com.client.connect + import win32com.client.dynamic import win32com.server.policy server = win32com.client.dynamic.Dispatch( @@ -85,7 +85,7 @@ def test(verbose=0): client = ConnectableClient() connection.Connect(server, client, IID_IConnectDemoEvents) CheckEvent(server, client, "Hello", verbose) - CheckEvent(server, client, str2bytes("Here is a null>\x00<"), verbose) + CheckEvent(server, client, b"Here is a null>\x00<", verbose) CheckEvent(server, client, "Here is a null>\x00<", verbose) val = "test-\xe0\xf2" # 2 extended characters. CheckEvent(server, client, val, verbose) diff --git a/com/win32com/demos/excelRTDServer.py b/com/win32com/demos/excelRTDServer.py index f8ae7c0f58..6eda469530 100644 --- a/com/win32com/demos/excelRTDServer.py +++ b/com/win32com/demos/excelRTDServer.py @@ -30,15 +30,15 @@ # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. +import datetime # For the example classes... +import threading + import pythoncom import win32com.client from win32com import universal from win32com.client import gencache from win32com.server.exception import COMException -import threading -import datetime # For the example classes... - # Typelib info for version 10 - aka Excel XP. # This is the minimum version of excel that we can work with as this is when # Microsoft introduced these interfaces. @@ -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 f7ff5feb1d..4b1890f9dc 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) """ @@ -24,15 +24,17 @@ Contribtions to this sample to make it a little "friendlier" welcome! """ -# imports section -import sys, os -from win32com import universal -from win32com.client import gencache, DispatchWithEvents, Dispatch -from win32com.client import constants, getevents -import win32com.server.register -import win32com +import os + import pythoncom import win32api +import win32com +import win32com.server.register +from win32com import universal +from win32com.client import Dispatch, DispatchWithEvents, constants, gencache, getevents + +# imports section + # This demo uses 'print' - use win32traceutil to see it if we have no # console. @@ -41,9 +43,10 @@ except win32api.error: import win32traceutil -from win32com.axcontrol import axcontrol +import array +import struct -import array, struct +from win32com.axcontrol import axcontrol # ensure we know the ms internet controls typelib so we have access to IWebBrowser2 later on win32com.client.gencache.EnsureModule("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1) diff --git a/com/win32com/demos/ietoolbar.py b/com/win32com/demos/ietoolbar.py index b06dd0efe4..309fa1a6b5 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) """ @@ -15,18 +15,19 @@ to catch WM_COMMAND messages. """ +import os + # imports section -import sys, os -from win32com import universal -from win32com.client import gencache, DispatchWithEvents, Dispatch -from win32com.client import constants, getevents -import win32com -import pythoncom +import sys import winreg +import pythoncom +import win32com +from win32com import universal +from win32com.axcontrol import axcontrol +from win32com.client import Dispatch, DispatchWithEvents, constants, gencache, getevents from win32com.shell import shell from win32com.shell.shellcon import * -from win32com.axcontrol import axcontrol try: # try to get styles (winxp) @@ -34,11 +35,13 @@ except: # import default module (win2k and lower) import win32gui -import win32ui -import win32con -import commctrl -import array, struct +import array +import struct + +import commctrl +import win32con +import win32ui # ensure we know the ms internet controls typelib so we have access to IWebBrowser2 later on win32com.client.gencache.EnsureModule("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1) diff --git a/com/win32com/makegw/makegw.py b/com/win32com/makegw/makegw.py index 067d444f14..6074900d5f 100644 --- a/com/win32com/makegw/makegw.py +++ b/com/win32com/makegw/makegw.py @@ -47,6 +47,7 @@ """ import re + from . import makegwparse @@ -196,7 +197,7 @@ def _write_ifc_cpp(f, interface): % (interface.__dict__) ) - ptr = re.sub("[a-z]", "", interface.name) + ptr = re.sub(r"[a-z]", "", interface.name) strdict = {"interfacename": interface.name, "ptr": ptr} for method in interface.methods: strdict["method"] = method.name diff --git a/com/win32com/makegw/makegwparse.py b/com/win32com/makegw/makegwparse.py index 59512f4873..ffe69cb4c7 100644 --- a/com/win32com/makegw/makegwparse.py +++ b/com/win32com/makegw/makegwparse.py @@ -928,7 +928,7 @@ class Interface: # name base # -------- -------- - regex = re.compile("(interface|) ([^ ]*) : public (.*)$") + regex = re.compile(r"(interface|) ([^ ]*) : public (.*)$") def __init__(self, mo): self.methods = [] diff --git a/com/win32com/server/dispatcher.py b/com/win32com/server/dispatcher.py index f6d58b9ac2..1abe9cd88b 100644 --- a/com/win32com/server/dispatcher.py +++ b/com/win32com/server/dispatcher.py @@ -2,13 +2,16 @@ Please see policy.py for a discussion on dispatchers and policies """ -import pythoncom, traceback, win32api +import traceback from sys import exc_info +import pythoncom +import win32api +import win32com + # from win32com.server.exception import IsCOMServerException from win32com.util import IIDToInterfaceName -import win32com class DispatcherBase: @@ -240,9 +243,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 e56db20fd9..476cc98798 100644 --- a/com/win32com/server/register.py +++ b/com/win32com/server/register.py @@ -6,12 +6,13 @@ construct the necessary Python object, and dispatch COM events. """ +import os import sys + +import pythoncom import win32api import win32con -import pythoncom import winerror -import os CATID_PythonCOMServer = "{B3EF80D0-68E2-11D0-A689-00C04FD658FF}" @@ -93,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" @@ -534,12 +535,14 @@ def UnregisterInfoClasses(*classes, **flags): # Attempt to 're-execute' our current process with elevation. def ReExecuteElevated(flags): - from win32com.shell.shell import ShellExecuteEx - from win32com.shell import shellcon - import win32process, win32event - import winxpgui # we've already checked we are running XP above import tempfile + import win32event + import win32process + import winxpgui # we've already checked we are running XP above + from win32com.shell import shellcon + from win32com.shell.shell import ShellExecuteEx + if not flags["quiet"]: print("Requesting elevation and retrying...") new_params = " ".join(['"' + a + '"' for a in sys.argv]) diff --git a/com/win32com/storagecon.py b/com/win32com/storagecon.py index 3ed5290238..10ee65de43 100644 --- a/com/win32com/storagecon.py +++ b/com/win32com/storagecon.py @@ -1,6 +1,6 @@ """Constants related to IStorage and related interfaces -This file was generated by h2py from d:\msdev\include\objbase.h +This file was generated by h2py from d:\\msdev\\include\\objbase.h then hand edited, a few extra constants added, etc. """ diff --git a/com/win32com/test/testPersist.py b/com/win32com/test/testPersist.py index 10fae96f16..d37e8a5d1d 100644 --- a/com/win32com/test/testPersist.py +++ b/com/win32com/test/testPersist.py @@ -1,25 +1,25 @@ -import pythoncom -import win32com.server.util +import os +import string import time +import traceback -import win32com, sys, string, win32api, traceback -import win32com.client.dynamic -import win32com.client import pythoncom -from win32com.axcontrol import axcontrol +import pywintypes +import win32api +import win32com +import win32com.client +import win32com.client.dynamic +import win32com.server.util +import win32ui from pywintypes import Unicode from win32com import storagecon +from win32com.axcontrol import axcontrol from win32com.test.util import CheckClean -import pywintypes -import win32ui -import win32api, os - -from pywin32_testutil import str2bytes - S_OK = 0 import datetime + import win32timezone now = win32timezone.now() @@ -38,7 +38,7 @@ class LockBytes: _com_interfaces_ = [pythoncom.IID_ILockBytes] def __init__(self, data=""): - self.data = str2bytes(data) + self.data = data.encode("latin1") self.ctime = now self.mtime = now self.atime = now @@ -71,7 +71,7 @@ def Flush(self, whatsthis=0): def SetSize(self, size): print("Set Size" + str(size)) if size > len(self.data): - self.data = self.data + str2bytes("\000" * (size - len(self.data))) + self.data = self.data + b"\000" * (size - len(self.data)) else: self.data = self.data[0:size] return S_OK diff --git a/com/win32com/test/testPippo.py b/com/win32com/test/testPippo.py index d2d38b1bdc..414483b53e 100644 --- a/com/win32com/test/testPippo.py +++ b/com/win32com/test/testPippo.py @@ -1,5 +1,6 @@ import sys import unittest + import pythoncom from win32com.client import Dispatch from win32com.client.gencache import EnsureDispatch @@ -7,8 +8,8 @@ class PippoTester(unittest.TestCase): def setUp(self): - from win32com.test.util import RegisterPythonServer from win32com.test import pippo_server + from win32com.test.util import RegisterPythonServer RegisterPythonServer(pippo_server.__file__, "Python.Test.Pippo") # create it. @@ -51,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 9350b03972..0e93f14366 100644 --- a/com/win32com/test/testPyComTest.py +++ b/com/win32com/test/testPyComTest.py @@ -4,19 +4,20 @@ import sys sys.coinit_flags = 0 # Must be free-threaded! -import win32api, pythoncom, time -import pywintypes +import datetime +import decimal import os -import winerror +import time + +import pythoncom +import pywintypes +import win32api import win32com import win32com.client.connect -from win32com.test.util import CheckClean -from win32com.client import constants, DispatchBaseClass, CastTo, VARIANT -from win32com.test.util import RegisterPythonServer -from pywin32_testutil import str2memory -import datetime -import decimal import win32timezone +import winerror +from win32com.client import VARIANT, CastTo, DispatchBaseClass, constants +from win32com.test.util import CheckClean, 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++" @@ -125,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 type(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): @@ -227,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) @@ -262,7 +231,7 @@ def TestCommon(o, is_generated): ) # and binary - TestApplyResult(o.SetBinSafeArray, (str2memory("foo\0bar"),), 7) + TestApplyResult(o.SetBinSafeArray, (memoryview(b"foo\0bar"),), 7) progress("Checking properties") o.LongProp = 3 @@ -531,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/testShell.py b/com/win32com/test/testShell.py index 8874597eb5..48937c523b 100644 --- a/com/win32com/test/testShell.py +++ b/com/win32com/test/testShell.py @@ -1,25 +1,19 @@ -import sys, os -import struct -import unittest import copy import datetime -import win32timezone - -try: - sys_maxsize = sys.maxsize # 2.6 and later - maxsize != maxint on 64bits -except AttributeError: - sys_maxsize = sys.maxint +import os +import struct +import sys +import unittest -import win32con import pythoncom import pywintypes +import win32com.test.util +import win32con +import win32timezone from win32com.shell import shell from win32com.shell.shellcon import * from win32com.storagecon import * -import win32com.test.util -from pywin32_testutil import str2bytes - class ShellTester(win32com.test.util.TestCase): def testShellLink(self): @@ -88,25 +82,23 @@ def _rtCIDA(self, parent, kids): self.assertEqual(cida_str_rt, cida_str) def testPIDL(self): - # A PIDL of "\1" is: cb pidl cb - expect = str2bytes("\03\00" "\1" "\0\0") - self.assertEqual(shell.PIDLAsString([str2bytes("\1")]), expect) - self._rtPIDL([str2bytes("\0")]) - self._rtPIDL([str2bytes("\1"), str2bytes("\2"), str2bytes("\3")]) - self._rtPIDL([str2bytes("\0") * 2048] * 2048) + # A PIDL of "\1" is: cb pidl cb + expect = b"\03\00" b"\1" b"\0\0" + self.assertEqual(shell.PIDLAsString([b"\1"]), expect) + self._rtPIDL([b"\0"]) + self._rtPIDL([b"\1", b"\2", b"\3"]) + self._rtPIDL([b"\0" * 2048] * 2048) # PIDL must be a list self.assertRaises(TypeError, shell.PIDLAsString, "foo") def testCIDA(self): - self._rtCIDA([str2bytes("\0")], [[str2bytes("\0")]]) - self._rtCIDA([str2bytes("\1")], [[str2bytes("\2")]]) - self._rtCIDA( - [str2bytes("\0")], [[str2bytes("\0")], [str2bytes("\1")], [str2bytes("\2")]] - ) + self._rtCIDA([b"\0"], [[b"\0"]]) + self._rtCIDA([b"\1"], [[b"\2"]]) + self._rtCIDA([b"\0"], [[b"\0"], [b"\1"], [b"\2"]]) def testBadShortPIDL(self): - # A too-short child element: cb pidl cb - pidl = str2bytes("\01\00" "\1") + # A too-short child element: cb pidl cb + pidl = b"\01\00" b"\1" self.assertRaises(ValueError, shell.StringAsPIDL, pidl) # ack - tried to test too long PIDLs, but a len of 0xFFFF may not @@ -172,7 +164,7 @@ def testComplex(self): ftCreationTime=ctime, ftLastAccessTime=atime, ftLastWriteTime=wtime, - nFileSize=sys_maxsize + 1, + nFileSize=sys.maxsize + 1, ) self._testRT(d) @@ -188,7 +180,7 @@ def testUnicode(self): ftCreationTime=ctime, ftLastAccessTime=atime, ftLastWriteTime=wtime, - nFileSize=sys_maxsize + 1, + nFileSize=sys.maxsize + 1, ), dict( cFileName="foo2.txt", @@ -198,7 +190,7 @@ def testUnicode(self): ftCreationTime=ctime, ftLastAccessTime=atime, ftLastWriteTime=wtime, - nFileSize=sys_maxsize + 1, + nFileSize=sys.maxsize + 1, ), dict( cFileName="foo\xa9.txt", @@ -208,7 +200,7 @@ def testUnicode(self): ftCreationTime=ctime, ftLastAccessTime=atime, ftLastWriteTime=wtime, - nFileSize=sys_maxsize + 1, + nFileSize=sys.maxsize + 1, ), ] s = shell.FILEGROUPDESCRIPTORAsString(d, 1) @@ -225,7 +217,7 @@ def setUp(self): self.src_name = os.path.join(tempfile.gettempdir(), "pywin32_testshell") self.dest_name = os.path.join(tempfile.gettempdir(), "pywin32_testshell_dest") - self.test_data = str2bytes("Hello from\0Python") + self.test_data = b"Hello from\0Python" f = open(self.src_name, "wb") f.write(self.test_data) f.close() diff --git a/com/win32com/test/testStreams.py b/com/win32com/test/testStreams.py index 6d3201db45..b43da524f3 100644 --- a/com/win32com/test/testStreams.py +++ b/com/win32com/test/testStreams.py @@ -1,10 +1,9 @@ +import unittest + import pythoncom import win32com.server.util import win32com.test.util -import unittest -from pywin32_testutil import str2bytes - class Persists: _public_methods_ = [ @@ -18,7 +17,7 @@ class Persists: _com_interfaces_ = [pythoncom.IID_IPersistStreamInit] def __init__(self): - self.data = str2bytes("abcdefg") + self.data = b"abcdefg" self.dirty = 1 def GetClassID(self): @@ -82,7 +81,7 @@ class BadStream(Stream): """ def Read(self, amount): - return str2bytes("x") * (amount + 1) + return b"x" * (amount + 1) class StreamTest(win32com.test.util.TestCase): @@ -98,7 +97,7 @@ def _readWrite(self, data, write_stream, read_stream=None): self.assertEqual(data[1:-1], got) def testit(self): - mydata = str2bytes("abcdefghijklmnopqrstuvwxyz") + mydata = b"abcdefghijklmnopqrstuvwxyz" # First test the objects just as Python objects... s = Stream(mydata) @@ -118,7 +117,7 @@ def testit(self): self._readWrite(mydata, s2, s) self._readWrite(mydata, s2, s2) - self._readWrite(str2bytes("string with\0a NULL"), s2, s2) + self._readWrite(b"string with\0a NULL", s2, s2) # reset the stream s.Write(mydata) p2.Load(s2) @@ -126,9 +125,9 @@ def testit(self): self.assertEqual(s.data, mydata) def testseek(self): - s = Stream(str2bytes("yo")) + 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/testall.py b/com/win32com/test/testall.py index d06a328b84..3538a45bd6 100644 --- a/com/win32com/test/testall.py +++ b/com/win32com/test/testall.py @@ -1,5 +1,10 @@ -import sys, os, string, re -import getopt, traceback, unittest +import getopt +import os +import re +import string +import sys +import traceback +import unittest try: this_file = __file__ @@ -20,13 +25,13 @@ import pythoncom import win32com.client from win32com.test.util import ( - CheckClean, - TestCase, CapturingFunctionTestCase, + CheckClean, + RegisterPythonServer, ShellTestCase, + TestCase, TestLoader, TestRunner, - RegisterPythonServer, ) verbosity = 1 # default unittest verbosity. @@ -43,7 +48,9 @@ def GenerateAndRunOldStyle(): def CleanGenerated(): - import win32com, shutil + import shutil + + import win32com if os.path.isdir(win32com.__gen_path__): if verbosity > 1: @@ -57,7 +64,7 @@ def CleanGenerated(): def RemoveRefCountOutput(data): while 1: last_line_pos = data.rfind("\n") - if not re.match("\[\d+ refs\]", data[last_line_pos + 1 :]): + if not re.match(r"\[\d+ refs\]", data[last_line_pos + 1 :]): break if last_line_pos < 0: # All the output diff --git a/com/win32com/test/testvb.py b/com/win32com/test/testvb.py index be7e967b59..e88f06fe0a 100644 --- a/com/win32com/test/testvb.py +++ b/com/win32com/test/testvb.py @@ -3,14 +3,15 @@ # This requires the PythonCOM VB Test Harness. # -import sys +import traceback + +import pythoncom +import win32com.client +import win32com.client.dynamic +import win32com.client.gencache import winerror -import pythoncom, win32com.client, win32com.client.dynamic, win32com.client.gencache from win32com.server.util import NewCollection, wrap from win32com.test import util -from pywin32_testutil import str2memory - -import traceback # for debugging useDispatcher = None @@ -82,8 +83,8 @@ def TestVB(vbtest, bUseGenerated): vbtest.VariantProperty = 10 if vbtest.VariantProperty != 10: raise error("Could not set the variant integer property correctly.") - vbtest.VariantProperty = str2memory("raw\0data") - if vbtest.VariantProperty != str2memory("raw\0data"): + vbtest.VariantProperty = memoryview(b"raw\0data") + if vbtest.VariantProperty != memoryview(b"raw\0data"): raise error("Could not set the variant buffer property correctly.") vbtest.StringProperty = "Hello from Python" if vbtest.StringProperty != "Hello from Python": @@ -421,17 +422,16 @@ def TestStructs(vbtest): # Now do some object equality tests. assert s == s assert s != 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 @@ -525,17 +525,16 @@ def TestObjectSemantics(ob): assert None != ob._oleobj_ assert ob != 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/testvbscript_regexp.py b/com/win32com/test/testvbscript_regexp.py index 2b06f2f472..a6c09ae8a7 100644 --- a/com/win32com/test/testvbscript_regexp.py +++ b/com/win32com/test/testvbscript_regexp.py @@ -1,7 +1,8 @@ import unittest -from win32com.client.gencache import EnsureDispatch -from win32com.client.dynamic import DumbDispatch + import win32com.test.util +from win32com.client.dynamic import DumbDispatch +from win32com.client.gencache import EnsureDispatch class RegexTest(win32com.test.util.TestCase): @@ -12,8 +13,8 @@ def _CheckMatches(self, match, expected): self.assertEqual(list(found), list(expected)) def _TestVBScriptRegex(self, re): - StringToSearch = "Python python pYthon Python" - re.Pattern = "Python" + StringToSearch = r"Python python pYthon Python" + re.Pattern = r"Python" re.Global = True re.IgnoreCase = True diff --git a/com/win32com/test/util.py b/com/win32com/test/util.py index f11fc5ba38..ce071202b5 100644 --- a/com/win32com/test/util.py +++ b/com/win32com/test/util.py @@ -1,28 +1,25 @@ -import sys, os -import win32api -import tempfile -import unittest import gc -import pywintypes -import pythoncom -import winerror -from pythoncom import _GetInterfaceCount, _GetGatewayCount -import win32com +import io as StringIO import logging +import os +import sys +import tempfile +import unittest import winreg -import io as StringIO +import pythoncom import pywin32_testutil -from pywin32_testutil import TestLoader, TestResult, TestRunner, LeakTestCase +import pywintypes +import win32api +import win32com +import winerror +from pythoncom import _GetGatewayCount, _GetInterfaceCount +from pywin32_testutil import LeakTestCase, TestLoader, TestResult, TestRunner 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/axscript/client/debug.py b/com/win32comext/axscript/client/debug.py index 338cbb8f91..7a5aa2e074 100644 --- a/com/win32comext/axscript/client/debug.py +++ b/com/win32comext/axscript/client/debug.py @@ -1,17 +1,19 @@ -import traceback, sys, string +import os +import string +import sys +import traceback -import win32com.server.util -from win32com.util import IIDToInterfaceName -from win32com.client.util import Enumerator -from win32com.server.exception import COMException import pythoncom -from .framework import trace -from win32com.axdebug import axdebug, gateways, contexts, stackframe, documents, adb +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.codecontainer import SourceCodeContainer from win32com.axdebug.util import _wrap, _wrap_remove -import win32com.client.connect -import win32api, winerror -import os +from win32com.client.util import Enumerator +from win32com.server.exception import COMException +from win32com.util import IIDToInterfaceName try: os.environ["DEBUG_AXDEBUG"] diff --git a/com/win32comext/axscript/client/error.py b/com/win32comext/axscript/client/error.py index 7de9a3b115..95b333bc0c 100644 --- a/com/win32comext/axscript/client/error.py +++ b/com/win32comext/axscript/client/error.py @@ -2,16 +2,17 @@ This contains the core exceptions that the implementations should raise as well as the IActiveScriptError interface code. - + """ -import sys, traceback -from win32com.axscript import axscript -import winerror +import re +import traceback + +import pythoncom import win32com.server.exception import win32com.server.util -import pythoncom -import re +import winerror +from win32com.axscript import axscript debugging = 0 @@ -23,11 +24,11 @@ def FormatForAX(text): def ExpandTabs(text): - return re.sub("\t", " ", text) + return re.sub(r"\t", " ", text) def AddCR(text): - return re.sub("\n", "\r\n", text) + return re.sub(r"\n", "\r\n", text) class IActiveScriptError: @@ -189,21 +190,6 @@ def _BuildFromOther(self, site, exc_type, value, tb): else: bits.extend(traceback.format_exception_only(exc_type, value)) - # XXX - this utf8 encoding seems bogus. From well before py3k, - # we had the comment: - # > all items in the list are utf8 courtesy of Python magically - # > converting unicode to utf8 before compilation. - # but that is likely just confusion from early unicode days; - # Python isn't doing it, pywin32 probably was, so 'mbcs' would - # be the default encoding. We should never hit this these days - # anyway, but on py3k, we *never* will, and str objects there - # don't have a decode method... - if sys.version_info < (3,): - for i in range(len(bits)): - if type(bits[i]) is str: - # assert type(bits[i]) is str, type(bits[i]) - bits[i] = bits[i].decode("utf8") - self.description = ExpandTabs("".join(bits)) # Clear tracebacks etc. tb = tb_top = tb_look = None diff --git a/com/win32comext/axscript/client/framework.py b/com/win32comext/axscript/client/framework.py index 67e952edc1..a90fda649b 100644 --- a/com/win32comext/axscript/client/framework.py +++ b/com/win32comext/axscript/client/framework.py @@ -6,23 +6,23 @@ There are classes defined for the engine itself, and for ScriptItems """ +import re import sys -from win32com.axscript import axscript -import win32com.server.util - -import win32com.client.connect # Need simple connection point support +import types -import win32api, winerror import pythoncom -import types -import re +import win32api +import win32com.client.connect # Need simple connection point support +import win32com.server.util +import winerror +from win32com.axscript import axscript def RemoveCR(text): # No longer just "RemoveCR" - should be renamed to # FixNewlines, or something. Idea is to fix arbitary newlines into # something Python can compile... - return re.sub("(\r\n)|\r|(\n\r)", "\n", text) + return re.sub(r"(\r\n)|\r|(\n\r)", "\n", text) SCRIPTTEXT_FORCEEXECUTION = -2147483648 # 0x80000000 @@ -30,6 +30,7 @@ def RemoveCR(text): SCRIPTTEXT_ISPERSISTENT = 0x00000040 from win32com.server.exception import Exception, IsCOMServerException + from . import error # ax.client.error state_map = { @@ -725,6 +726,7 @@ def SetScriptSite(self, site): try: import win32com.axdebug.axdebug # see if the core exists. + from . import debug self.debugManager = debug.DebugManager(self) @@ -1054,7 +1056,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 - pass # Ignore all errors here - E_NOTIMPL likely from scriptlets. finally: self.EnableInterrupts() diff --git a/com/win32comext/axscript/client/pyscript.py b/com/win32comext/axscript/client/pyscript.py index 212c2375bc..20f47bbf0b 100644 --- a/com/win32comext/axscript/client/pyscript.py +++ b/com/win32comext/axscript/client/pyscript.py @@ -7,25 +7,24 @@ command line. """ -import winerror -import win32com -import win32api -import pythoncom -import sys -import traceback import re +import traceback + +import pythoncom +import win32api +import win32com import win32com.client.dynamic -from win32com.axscript.client import framework, scriptdispatch -from win32com.axscript import axscript import win32com.server.register - +import winerror +from win32com.axscript import axscript +from win32com.axscript.client import framework, scriptdispatch from win32com.axscript.client.framework import ( - RaiseAssert, - trace, - Exception, SCRIPTTEXT_FORCEEXECUTION, SCRIPTTEXT_ISEXPRESSION, SCRIPTTEXT_ISPERSISTENT, + Exception, + RaiseAssert, + trace, ) PyScript_CLSID = "{DF630910-1C1D-11d0-AE36-8C0F5E000000}" @@ -39,11 +38,11 @@ def debug_attr_print(*args): def ExpandTabs(text): - return re.sub("\t", " ", text) + return re.sub(r"\t", " ", text) def AddCR(text): - return re.sub("\n", "\r\n", text) + return re.sub(r"\n", "\r\n", text) class AXScriptCodeBlock(framework.AXScriptCodeBlock): @@ -434,8 +433,6 @@ def DllRegisterServer(): def Register(klass=PyScript): - import sys - ret = win32com.server.register.UseCommandLine( klass, finalize_register=DllRegisterServer ) diff --git a/com/win32comext/axscript/test/leakTest.py b/com/win32comext/axscript/test/leakTest.py index 7fda3c7617..5022ab1a89 100644 --- a/com/win32comext/axscript/test/leakTest.py +++ b/com/win32comext/axscript/test/leakTest.py @@ -1,10 +1,11 @@ import sys -from win32com.axscript.server.error import Exception -from win32com.axscript import axscript -from win32com.axscript.server import axsite + import pythoncom -from win32com.server import util, connect import win32com.server.policy +from win32com.axscript import axscript +from win32com.axscript.server import axsite +from win32com.axscript.server.error import Exception +from win32com.server import connect, util class MySite(axsite.AXSite): @@ -78,7 +79,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 @@ -86,16 +87,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 f2e41671c7..d3e6bb5f66 100644 --- a/com/win32comext/axscript/test/testHost.py +++ b/com/win32comext/axscript/test/testHost.py @@ -1,16 +1,16 @@ import sys +import unittest + import pythoncom -from win32com.axscript.server.error import Exception +import win32com.server.policy +import win32com.test.util from win32com.axscript import axscript from win32com.axscript.server import axsite -from win32com.server import util, connect -import win32com.server.policy +from win32com.axscript.server.error import Exception from win32com.client.dynamic import Dispatch +from win32com.server import connect, util from win32com.server.exception import COMException -import unittest -import win32com.test.util - verbose = "-v" in sys.argv @@ -133,7 +133,7 @@ def testcollection(): test.fail("Didn't get the collection") pass """ - +# TODO # 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! diff --git a/com/win32comext/mapi/mapiutil.py b/com/win32comext/mapi/mapiutil.py index 8cbdcbc083..39f35729bd 100644 --- a/com/win32comext/mapi/mapiutil.py +++ b/com/win32comext/mapi/mapiutil.py @@ -1,10 +1,7 @@ # General utilities for MAPI and MAPI objects. -# We used to use these old names from the 'types' module... -TupleType = tuple -ListType = list -IntType = int -from pywintypes import TimeType import pythoncom +from pywintypes import TimeType + from . import mapi, mapitags prTable = {} @@ -103,13 +100,13 @@ def GetProperties(obj, propList): If the property fetch fails, the result is None. """ bRetList = 1 - if type(propList) not in [TupleType, ListType]: + if type(propList) not in [tuple, list]: bRetList = 0 propList = (propList,) realPropList = [] rc = [] for prop in propList: - if type(prop) != IntType: # Integer + if type(prop) != int: props = ((mapi.PS_PUBLIC_STRINGS, prop),) propIds = obj.GetIDsFromNames(props, 0) prop = mapitags.PROP_TAG( @@ -145,19 +142,17 @@ def GetAllProperties(obj, make_tag_names=True): _MapiTypeMap = { - type(0.0): mapitags.PT_DOUBLE, - type(0): mapitags.PT_I4, - type("".encode("ascii")): mapitags.PT_STRING8, # bytes - type(""): mapitags.PT_UNICODE, # str + float: mapitags.PT_DOUBLE, + int: mapitags.PT_I4, + bytes: mapitags.PT_STRING8, + str: mapitags.PT_UNICODE, type(None): mapitags.PT_UNSPECIFIED, - # In Python 2.2.2, bool isn't a distinct type (type(1==1) is type(0)). - # (markh thinks the above is trying to say that in 2020, we probably *do* - # want bool in this map? :) + bool: mapitags.PT_BOOLEAN, } def SetPropertyValue(obj, prop, val): - if type(prop) != IntType: + if type(prop) != int: props = ((mapi.PS_PUBLIC_STRINGS, prop),) propIds = obj.GetIDsFromNames(props, mapi.MAPI_CREATE) if val == (1 == 1) or val == (1 == 0): @@ -202,7 +197,7 @@ def SetProperties(msg, propDict): type_val = type(val) if type_val == str: tagType = mapitags.PT_UNICODE - elif type_val == IntType: + elif type_val == int: tagType = mapitags.PT_I4 elif type_val == TimeType: tagType = mapitags.PT_SYSTIME diff --git a/com/win32comext/shell/demos/ITransferAdviseSink.py b/com/win32comext/shell/demos/ITransferAdviseSink.py index 65363e61f5..fc766fb0b2 100644 --- a/com/win32comext/shell/demos/ITransferAdviseSink.py +++ b/com/win32comext/shell/demos/ITransferAdviseSink.py @@ -1,27 +1,13 @@ # ITransferAdviseSink implementation template import pythoncom -from win32com.shell import shell, shellcon 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_") ) - -def decode_flags(flags): - if flags == 0: - return "TSF_NORMAL" - flag_txt = "" - for k, v in tsf_flags: - if flags & v: - if flag_txt: - flag_txt = flag_txt + "|" + k - else: - flag_txt = k - return flag_txt - - TRANSFER_ADVISE_STATES = {} for k, v in list(shellcon.__dict__.items()): if k.startswith("TS_"): diff --git a/com/win32comext/shell/demos/servers/copy_hook.py b/com/win32comext/shell/demos/servers/copy_hook.py index 889780ecb6..d46a7d59ca 100644 --- a/com/win32comext/shell/demos/servers/copy_hook.py +++ b/com/win32comext/shell/demos/servers/copy_hook.py @@ -12,6 +12,7 @@ import win32con import winerror + # Our shell extension. class ShellExtension: _reg_progid_ = "Python.ShellExtension.CopyHook" diff --git a/isapi/samples/redirector.py b/isapi/samples/redirector.py index 1f9b644bb6..bab44f877a 100644 --- a/isapi/samples/redirector.py +++ b/isapi/samples/redirector.py @@ -16,17 +16,14 @@ # an example. If this sample is run on IIS5 or earlier it simply ignores # any excludes. -from isapi import isapicon, threaded_extension import sys import traceback +from urllib.request import urlopen -try: - from urllib.request import urlopen -except ImportError: - # py3k spelling... - from urllib.request import urlopen import win32api +from isapi import isapicon, threaded_extension + # sys.isapidllhandle will exist when we are loaded by the IIS framework. # In this case we redirect our output to the win32traceutil collector. if hasattr(sys, "isapidllhandle"): @@ -83,14 +80,10 @@ def Dispatch(self, ecb): fp = urlopen(new_url) headers = fp.info() # subtle py3k breakage: in py3k, str(headers) has normalized \r\n - # back to \n and also stuck an extra \n term. py2k leaves the - # \r\n from the server in tact and finishes with a single term. - if sys.version_info < (3, 0): - header_text = str(headers) + "\r\n" - else: - # take *all* trailing \n off, replace remaining with - # \r\n, then add the 2 trailing \r\n. - header_text = str(headers).rstrip("\n").replace("\n", "\r\n") + "\r\n\r\n" + # back to \n and also stuck an extra \n term. + # take *all* trailing \n off, replace remaining with + # \r\n, then add the 2 trailing \r\n. + header_text = str(headers).rstrip("\n").replace("\n", "\r\n") + "\r\n\r\n" ecb.SendResponseHeaders("200 OK", header_text, False) ecb.WriteClient(fp.read()) ecb.DoneWithSession() diff --git a/setup.py b/setup.py index 537a881973..e26335da93 100644 --- a/setup.py +++ b/setup.py @@ -22,38 +22,36 @@ build_env.md, which is getting out of date but might help getting everything required for an official build - see README.md for that process. """ +import glob + # Originally by Thomas Heller, started in 2000 or so. import os -import sys -import glob -import re -from tempfile import gettempdir import platform +import re import shutil import subprocess - +import sys import winreg +from distutils import log +from distutils.command.build import build +from distutils.command.install import install +from distutils.command.install_data import install_data +from distutils.command.install_lib import install_lib +from distutils.core import Extension +from tempfile import gettempdir # The rest of our imports. from setuptools import setup -from distutils.core import Extension -from distutils.command.install import install -from distutils.command.install_lib import install_lib from setuptools.command.build_ext import build_ext -from distutils.command.build import build -from distutils.command.install_data import install_data - -from distutils import log - # some modules need a static CRT to avoid problems caused by them having a # manifest. static_crt_modules = ["winxpgui"] +import distutils.util from distutils.dep_util import newer_group from distutils.filelist import FileList -import distutils.util build_id_patch = build_id if not "." in build_id_patch: @@ -814,6 +812,7 @@ def swig_sources(self, sources, ext=None): new_sources = [] swig_sources = [] swig_targets = {} + # TODO # XXX this drops generated C/C++ files into the source tree, which # is fine for developers who want to distribute the generated # source -- but there should be an option to put SWIG output in @@ -879,6 +878,7 @@ def swig_sources(self, sources, ext=None): # A class deriving from other than the default swig_cmd.extend(["-com_interface_parent", interface_parent]) + # TODO # This 'newer' check helps python 2.2 builds, which otherwise # *always* regenerate the .cpp files, meaning every future # build for any platform sees these as dirty. @@ -2144,7 +2144,7 @@ def convert_data_files(files): flist.findall(os.path.dirname(file)) flist.include_pattern(os.path.basename(file), anchor=0) # We never want CVS - flist.exclude_pattern(re.compile(".*\\\\CVS\\\\"), is_regex=1, anchor=0) + 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: @@ -2409,23 +2409,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 8b923eaccf..86aebcc34f 100644 --- a/win32/Demos/BackupRead_BackupWrite.py +++ b/win32/Demos/BackupRead_BackupWrite.py @@ -1,10 +1,16 @@ ## demonstrates using BackupRead and BackupWrite to copy all of a file's data streams -import win32file, win32api, win32con, win32security, ntsecuritycon +import struct +import traceback + +import ntsecuritycon +import pythoncom +import pywintypes +import win32api +import win32con +import win32file +import win32security from win32com import storagecon -import pythoncom, pywintypes -import struct, traceback -from pywin32_testutil import str2bytes, ob2memory all_sd_info = ( win32security.DACL_SECURITY_INFORMATION @@ -98,7 +104,7 @@ ) print("Written:", bytes_written, "Context:", outctxt) win32file.BackupRead(h, 0, buf, True, True, ctxt) -win32file.BackupWrite(outh, 0, str2bytes(""), True, True, outctxt) +win32file.BackupWrite(outh, 0, b"", True, True, outctxt) win32file.CloseHandle(h) win32file.CloseHandle(outh) @@ -110,7 +116,7 @@ open(tempfile + ":anotherstream").read() == open(outfile + ":anotherstream").read() ), "anotherstream contents differ !" assert ( - ob2memory(win32security.GetFileSecurity(tempfile, all_sd_info))[:] - == ob2memory(win32security.GetFileSecurity(outfile, all_sd_info))[:] + memoryview(win32security.GetFileSecurity(tempfile, all_sd_info))[:] + == memoryview(win32security.GetFileSecurity(outfile, all_sd_info))[:] ), "Security descriptors are different !" ## also should check Summary Info programatically diff --git a/win32/Demos/CreateFileTransacted_MiniVersion.py b/win32/Demos/CreateFileTransacted_MiniVersion.py index 0d1384e39d..6ad5868a23 100644 --- a/win32/Demos/CreateFileTransacted_MiniVersion.py +++ b/win32/Demos/CreateFileTransacted_MiniVersion.py @@ -4,11 +4,15 @@ miniversion (effectively a savepoint within a transaction). """ -import win32file, win32api, win32transaction, winerror -import win32con, winioctlcon -import struct import os -from pywin32_testutil import str2bytes # py3k-friendly helper +import struct + +import win32api +import win32con +import win32file +import win32transaction +import winerror +import winioctlcon def demo(): @@ -44,14 +48,14 @@ def demo(): Transaction=trans, ) - win32file.WriteFile(hfile, str2bytes("This is first miniversion.\n")) + win32file.WriteFile(hfile, b"This is first miniversion.\n") buf = win32file.DeviceIoControl( hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION, None, buf_size, None ) struct_ver, struct_len, base_ver, ver_1 = struct.unpack(buf_fmt, buf) win32file.SetFilePointer(hfile, 0, win32con.FILE_BEGIN) - win32file.WriteFile(hfile, str2bytes("This is second miniversion!\n")) + win32file.WriteFile(hfile, b"This is second miniversion!\n") buf = win32file.DeviceIoControl( hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION, None, buf_size, None ) diff --git a/win32/Demos/OpenEncryptedFileRaw.py b/win32/Demos/OpenEncryptedFileRaw.py index 775d06e53f..c9e2d54d87 100644 --- a/win32/Demos/OpenEncryptedFileRaw.py +++ b/win32/Demos/OpenEncryptedFileRaw.py @@ -1,12 +1,14 @@ -import win32file, win32api, winerror import os +import win32api +import win32file +import winerror + 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/eventLogDemo.py b/win32/Demos/eventLogDemo.py index c49fc16a03..28c4f424a6 100644 --- a/win32/Demos/eventLogDemo.py +++ b/win32/Demos/eventLogDemo.py @@ -1,9 +1,8 @@ -import win32evtlog import win32api import win32con -import win32security # To translate NT Sids to account names. - +import win32evtlog import win32evtlogutil +import win32security # To translate NT Sids to account names. def ReadLog(computer, logType="Application", dumpEachRecord=0): @@ -77,7 +76,8 @@ def test(): print("This sample only runs on NT") return - import sys, getopt + import getopt + import sys opts, args = getopt.getopt(sys.argv[1:], "rwh?c:t:v") computer = None @@ -113,7 +113,7 @@ def test(): logType, 2, strings=["The message text for event 2", "Another insert"], - data="Raw\0Data".encode("ascii"), + data=b"Raw\0Data", sid=my_sid, ) win32evtlogutil.ReportEvent( @@ -121,7 +121,7 @@ def test(): 1, eventType=win32evtlog.EVENTLOG_WARNING_TYPE, strings=["A warning", "An even more dire warning"], - data="Raw\0Data".encode("ascii"), + data=b"Raw\0Data", sid=my_sid, ) win32evtlogutil.ReportEvent( @@ -129,7 +129,7 @@ def test(): 1, eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE, strings=["An info", "Too much info"], - data="Raw\0Data".encode("ascii"), + data=b"Raw\0Data", sid=my_sid, ) print("Successfully wrote 3 records to the log") diff --git a/win32/Demos/mmapfile_demo.py b/win32/Demos/mmapfile_demo.py index 31ab03a093..ff3ac8f136 100644 --- a/win32/Demos/mmapfile_demo.py +++ b/win32/Demos/mmapfile_demo.py @@ -1,7 +1,9 @@ -import win32api, mmapfile +import os +import tempfile + +import mmapfile +import win32api import winerror -import tempfile, os -from pywin32_testutil import str2bytes system_info = win32api.GetSystemInfo() page_size = system_info[1] @@ -14,16 +16,16 @@ m1 = mmapfile.mmapfile(File=fname, Name=mapping_name, MaximumSize=fsize) m1.seek(100) -m1.write_byte(str2bytes("?")) +m1.write_byte(b"?") m1.seek(-1, 1) -assert m1.read_byte() == str2bytes("?") +assert m1.read_byte() == b"?" ## A reopened named mapping should have exact same size as original mapping m2 = mmapfile.mmapfile(Name=mapping_name, File=None, MaximumSize=fsize * 2) assert m2.size() == m1.size() m1.seek(0, 0) -m1.write(fsize * str2bytes("s")) -assert m2.read(fsize) == fsize * str2bytes("s") +m1.write(fsize * b"s") +assert m2.read(fsize) == fsize * b"s" move_src = 100 move_dest = 500 @@ -31,17 +33,17 @@ m2.seek(move_src, 0) assert m2.tell() == move_src -m2.write(str2bytes("m") * move_size) +m2.write(b"m" * move_size) m2.move(move_dest, move_src, move_size) m2.seek(move_dest, 0) -assert m2.read(move_size) == str2bytes("m") * move_size +assert m2.read(move_size) == b"m" * move_size ## m2.write('x'* (fsize+1)) m2.close() m1.resize(fsize * 2) assert m1.size() == fsize * 2 m1.seek(fsize) -m1.write(str2bytes("w") * fsize) +m1.write(b"w" * fsize) m1.flush() m1.close() os.remove(fname) @@ -51,7 +53,7 @@ ## need 10 GB free on drive where your temp folder lives fname_large = tempfile.mktemp() mapping_name = "Pywin32_large_mmap" -offsetdata = str2bytes("This is start of offset") +offsetdata = b"This is start of offset" ## Deliberately use odd numbers to test rounding logic fsize = (1024 * 1024 * 1024 * 10) + 333 diff --git a/win32/Demos/security/sspi/socket_server.py b/win32/Demos/security/sspi/socket_server.py index 0f848aa779..5ca44729ec 100644 --- a/win32/Demos/security/sspi/socket_server.py +++ b/win32/Demos/security/sspi/socket_server.py @@ -9,7 +9,7 @@ Running either the client or server as a different user can be informative. A command-line such as the following may be useful: -`runas /user:{user} {fqp}\python.exe {fqp}\socket_server.py --wait client|server` +`runas /user:{user} {fqp}\\python.exe {fqp}\\socket_server.py --wait client|server` {fqp} should specify the relevant fully-qualified path names. @@ -19,18 +19,16 @@ See the SSPI documentation for more details. """ - -import sys -import struct -import socketserver -import win32api import http.client +import optparse # sorry, this demo needs 2.3+ +import socketserver +import struct import traceback +import sspi +import sspicon +import win32api import win32security -import sspi, sspicon - -import optparse # sorry, this demo needs 2.3+ options = None # set to optparse object. diff --git a/win32/Demos/service/pipeTestService.py b/win32/Demos/service/pipeTestService.py index 9030f81345..3d93739672 100644 --- a/win32/Demos/service/pipeTestService.py +++ b/win32/Demos/service/pipeTestService.py @@ -71,7 +71,7 @@ def DoProcessClient(self, pipeHandle, tid): try: # Create a loop, reading large data. If we knew the data stream was # was small, a simple ReadFile would do. - d = "".encode("ascii") # ensure bytes on py2k and py3k... + d = b"" hr = winerror.ERROR_MORE_DATA while hr == winerror.ERROR_MORE_DATA: hr, thisd = ReadFile(pipeHandle, 256) @@ -86,10 +86,11 @@ def DoProcessClient(self, pipeHandle, tid): # pipe, but for the sake of this demo we dont (if only to see what errors # we can get when our clients break at strange times :-) if ok: - msg = ( - "%s (on thread %d) sent me %s" - % (GetNamedPipeHandleState(pipeHandle, False, True)[4], tid, d) - ).encode("ascii") + msg = b"%s (on thread %d) sent me %s" % ( + GetNamedPipeHandleState(pipeHandle, False, True)[4], + tid, + d, + ) WriteFile(pipeHandle, msg) finally: ApplyIgnoreError(DisconnectNamedPipe, (pipeHandle,)) diff --git a/win32/Demos/service/pipeTestServiceClient.py b/win32/Demos/service/pipeTestServiceClient.py index 7d6295faf8..b4e7948cc7 100644 --- a/win32/Demos/service/pipeTestServiceClient.py +++ b/win32/Demos/service/pipeTestServiceClient.py @@ -6,13 +6,15 @@ # Eg: pipeTestServiceClient.py -s server_name Hi There # Should work. -from win32pipe import * -from win32file import * -from win32event import * +import os +import traceback + import pywintypes import win32api import winerror -import sys, os, traceback +from win32event import * +from win32file import * +from win32pipe import * verbose = 0 @@ -107,7 +109,8 @@ def stressTestClient(server, numThreads, numMessages): def main(): - import sys, getopt + import getopt + import sys server = "." thread_count = 0 diff --git a/win32/Demos/win32clipboardDemo.py b/win32/Demos/win32clipboardDemo.py index f9b2945355..ba7f88795c 100644 --- a/win32/Demos/win32clipboardDemo.py +++ b/win32/Demos/win32clipboardDemo.py @@ -1,10 +1,8 @@ # win32clipboardDemo.py # # Demo/test of the win32clipboard module. -from win32clipboard import * -from pywin32_testutil import str2bytes # py3k-friendly helper import win32con -import types +from win32clipboard import * if not __debug__: print("WARNING: The test code in this module uses assert") @@ -32,7 +30,7 @@ def TestText(): OpenClipboard() try: text = "Hello from Python" - text_bytes = str2bytes(text) + text_bytes = text.encode("latin1") SetClipboardText(text) got = GetClipboardData(win32con.CF_TEXT) # CF_TEXT always gives us 'bytes' back . @@ -54,7 +52,7 @@ def TestText(): # Unicode tests EmptyClipboard() text = "Hello from Python unicode" - text_bytes = str2bytes(text) + text_bytes = text.encode("latin1") # Now set the Unicode value SetClipboardData(win32con.CF_UNICODETEXT, text) # Get it in Unicode. @@ -111,8 +109,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/win32fileDemo.py b/win32/Demos/win32fileDemo.py index bb7f05b1a0..4467d02fea 100644 --- a/win32/Demos/win32fileDemo.py +++ b/win32/Demos/win32fileDemo.py @@ -1,10 +1,15 @@ # This is a "demo" of win32file - it used to be more a test case than a # demo, so has been moved to the test directory. -# Please contribute your favourite simple little demo. -import win32file, win32api, win32con import os +import win32api +import win32con + +# Please contribute your favourite simple little demo. +import win32file + + # A very simple demo - note that this does no more than you can do with # builtin Python file objects, so for something as simple as this, you # generally *should* use builtin Python objects. Only use win32file etc @@ -17,7 +22,7 @@ def SimpleFileDemo(): handle = win32file.CreateFile( testName, win32file.GENERIC_WRITE, 0, None, win32con.CREATE_NEW, 0, None ) - test_data = "Hello\0there".encode("ascii") + test_data = b"Hello\0there" win32file.WriteFile(handle, test_data) handle.Close() # Open it for reading. diff --git a/win32/Demos/win32gui_dialog.py b/win32/Demos/win32gui_dialog.py index 8db06d8ead..c4086563b5 100644 --- a/win32/Demos/win32gui_dialog.py +++ b/win32/Demos/win32gui_dialog.py @@ -20,13 +20,17 @@ import win32gui else: import winxpgui as win32gui -import win32gui_struct -import win32api -import win32con, winerror -import struct, array -import commctrl -import queue + +import array import os +import queue +import struct + +import commctrl +import win32api +import win32con +import win32gui_struct +import winerror IDC_SEARCHTEXT = 1024 IDC_BUTTON_SEARCH = 1025 @@ -142,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 cea8dfe56b..38c4827eb4 100644 --- a/win32/Demos/win32gui_menu.py +++ b/win32/Demos/win32gui_menu.py @@ -15,11 +15,14 @@ from winxpgui import * except ImportError: from win32gui import * -from win32gui_struct import * -import win32con -import sys, os -import struct + import array +import os +import struct +import sys + +import win32con +from win32gui_struct import * this_dir = os.path.split(sys.argv[0])[0] @@ -57,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 1a17f3a954..eca439baa1 100644 --- a/win32/Demos/win32gui_taskbar.py +++ b/win32/Demos/win32gui_taskbar.py @@ -1,8 +1,12 @@ # Creates a task-bar icon. Run from Python.exe to see the # messages printed. -import win32api, win32gui -import win32con, winerror -import sys, os +import os +import sys + +import win32api +import win32con +import win32gui +import winerror class MainWindow: @@ -54,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/netbios.py b/win32/Lib/netbios.py index c9638b25c6..3f80b6b62c 100644 --- a/win32/Lib/netbios.py +++ b/win32/Lib/netbios.py @@ -1,7 +1,7 @@ -import sys -import win32wnet import struct +import win32wnet + # Constants generated by h2py from nb30.h NCBNAMSZ = 16 MAX_LANA = 254 @@ -265,14 +265,6 @@ def ACTION_HEADER(): return NCBStruct(ACTION_HEADER_ITEMS) -def byte_to_int(b): - """Given an element in a binary buffer, return its integer value""" - if sys.version_info >= (3, 0): - # a byte is already an int in py3k - return b - return ord(b) # its a char from a string in py2k. - - if __name__ == "__main__": # code ported from "HOWTO: Get the MAC Address for an Ethernet Adapter" # MS KB ID: Q118623 @@ -286,18 +278,18 @@ def byte_to_int(b): for i in range(la_enum.length): ncb.Reset() ncb.Command = NCBRESET - ncb.Lana_num = byte_to_int(la_enum.lana[i]) + ncb.Lana_num = la_enum.lana[i] rc = Netbios(ncb) if rc != 0: raise RuntimeError("Unexpected result %d" % (rc,)) ncb.Reset() ncb.Command = NCBASTAT - ncb.Lana_num = byte_to_int(la_enum.lana[i]) - ncb.Callname = "* ".encode("ascii") # ensure bytes on py2x and 3k + ncb.Lana_num = la_enum.lana[i] + ncb.Callname = b"* " adapter = ADAPTER_STATUS() ncb.Buffer = adapter Netbios(ncb) print("Adapter address:", end=" ") for ch in adapter.adapter_address: - print("%02x" % (byte_to_int(ch),), end=" ") + print("%02x" % (ch,), end=" ") print() diff --git a/win32/Lib/pywin32_testutil.py b/win32/Lib/pywin32_testutil.py index f7e4ede57e..7ccfcb0203 100644 --- a/win32/Lib/pywin32_testutil.py +++ b/win32/Lib/pywin32_testutil.py @@ -1,39 +1,11 @@ # Utilities for the pywin32 tests +import gc +import os import site import sys -import os import unittest -import gc -import winerror - -## -## General purpose utilities for the test suite. -## - -# The test suite has lots of string constants containing binary data, but -# the strings are used in various "bytes" contexts. -def str2bytes(sval): - if sys.version_info < (3, 0) and isinstance(sval, str): - sval = sval.decode("latin1") - return sval.encode("latin1") - - -# Sometimes we want to pass a string that should explicitly be treated as -# a memory blob. -def str2memory(sval): - if sys.version_info < (3, 0): - return buffer(sval) - # py3k. - return memoryview(sval.encode("latin1")) - - -# Sometimes we want to pass an object that exposes its memory -def ob2memory(ob): - if sys.version_info < (3, 0): - return buffer(ob) - # py3k. - return memoryview(ob) +import winerror ## ## unittest related stuff @@ -66,7 +38,7 @@ def countTestCases(self): def __call__(self, result=None): # For the COM suite's sake, always ensure we don't leak # gateways/interfaces - from pythoncom import _GetInterfaceCount, _GetGatewayCount + from pythoncom import _GetGatewayCount, _GetInterfaceCount gc.collect() ni = _GetInterfaceCount() @@ -182,8 +154,8 @@ def loadTestsFromName(self, name, module=None): def check_is_admin(): global _is_admin if _is_admin is None: - from win32com.shell.shell import IsUserAnAdmin import pythoncom + from win32com.shell.shell import IsUserAnAdmin try: _is_admin = IsUserAnAdmin() diff --git a/win32/Lib/pywintypes.py b/win32/Lib/pywintypes.py index 8f03e0d7a2..631e7db884 100644 --- a/win32/Lib/pywintypes.py +++ b/win32/Lib/pywintypes.py @@ -1,5 +1,8 @@ # Magic utility that "redirects" to pywintypesxx.dll -import importlib.util, importlib.machinery, sys, os +import importlib.machinery +import importlib.util +import os +import sys def __import_pywin32_system_module__(modname, globs): @@ -28,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 d1422b182c..f8995eff26 100644 --- a/win32/Lib/sspi.py +++ b/win32/Lib/sspi.py @@ -11,14 +11,16 @@ If you need finer control than offered here, just use the win32security functions directly. """ +import sspicon + # Based on Roger Upole's sspi demos. # $Id$ -import win32security, sspicon +import win32security error = win32security.error -class _BaseAuth(object): +class _BaseAuth: def __init__(self): self.reset() @@ -385,7 +387,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 = "hello".encode("ascii") # py3k-friendly + data = b"hello" # Simple signature, not compatible with GSSAPI. sig = sspiclient.sign(data) diff --git a/win32/Lib/win32gui_struct.py b/win32/Lib/win32gui_struct.py index ee1da2793c..33672d8932 100644 --- a/win32/Lib/win32gui_struct.py +++ b/win32/Lib/win32gui_struct.py @@ -27,28 +27,23 @@ # win32gui (ie, the Pack* functions) - but doesn't make as much sense for # the Unpack* functions, where the aim is user convenience. -import sys -import win32gui -import win32con -import struct import array +import struct +import sys +from collections import namedtuple + import commctrl import pywintypes +import win32con +import win32gui is64bit = "64 bit" in sys.version -try: - from collections import namedtuple - def _MakeResult(names_str, values): - names = names_str.split() - nt = namedtuple(names[0], names[1:]) - return nt(*values) - -except ImportError: - # no namedtuple support - just return the values as a normal tuple. - def _MakeResult(names_str, values): - return values +def _MakeResult(names_str, values): + names = names_str.split() + nt = namedtuple(names[0], names[1:]) + return nt(*values) _nmhdr_fmt = "PPi" @@ -60,25 +55,11 @@ def _MakeResult(names_str, values): _nmhdr_align_padding = "" # Encode a string suitable for passing in a win32gui related structure -# If win32gui is built with UNICODE defined (ie, py3k), then functions -# like InsertMenuItem are actually calling InsertMenuItemW etc, so all -# strings will need to be unicode. -if win32gui.UNICODE: - - def _make_text_buffer(text): - # XXX - at this stage win32gui.UNICODE is only True in py3k, - # and in py3k is makes sense to reject bytes. - if not isinstance(text, str): - raise TypeError("MENUITEMINFO text must be unicode") - data = (text + "\0").encode("utf-16le") - return array.array("b", data) - -else: - - def _make_text_buffer(text): - if isinstance(text, str): - text = text.encode("mbcs") - return array.array("b", text + "\0") +def _make_text_buffer(text): + if not isinstance(text, str): + raise TypeError("MENUITEMINFO text must be unicode") + data = (text + "\0").encode("utf-16le") + return array.array("b", data) # make an 'empty' buffer, ready for filling with cch characters. @@ -86,23 +67,6 @@ def _make_empty_text_buffer(cch): return _make_text_buffer("\0" * cch) -if sys.version_info < (3, 0): - - def _make_memory(ob): - return str(buffer(ob)) - - def _make_bytes(sval): - return sval - -else: - - def _make_memory(ob): - return bytes(memoryview(ob)) - - def _make_bytes(sval): - return sval.encode("ascii") - - # Generic WM_NOTIFY unpacking def UnpackWMNOTIFY(lparam): format = "PPi" @@ -894,11 +858,11 @@ def PackHDITEM( # Generic function for packing a DEV_BROADCAST_* structure - generally used # by the other PackDEV_BROADCAST_* functions in this module. -def PackDEV_BROADCAST(devicetype, rest_fmt, rest_data, extra_data=_make_bytes("")): +def PackDEV_BROADCAST(devicetype, rest_fmt, rest_data, extra_data=b""): # It seems a requirement is 4 byte alignment, even for the 'BYTE data[1]' # field (eg, that would make DEV_BROADCAST_HANDLE 41 bytes, but we must # be 44. - extra_data += _make_bytes("\0" * (4 - len(extra_data) % 4)) + extra_data += b"\0" * (4 - len(extra_data) % 4) format = "iii" + rest_fmt full_size = struct.calcsize(format) + len(extra_data) data = (full_size, devicetype, 0) + rest_data @@ -908,14 +872,14 @@ def PackDEV_BROADCAST(devicetype, rest_fmt, rest_data, extra_data=_make_bytes("" def PackDEV_BROADCAST_HANDLE( handle, hdevnotify=0, - guid=_make_bytes("\0" * 16), + guid=b"\0" * 16, name_offset=0, - data=_make_bytes("\0"), + data=b"\0", ): return PackDEV_BROADCAST( win32con.DBT_DEVTYP_HANDLE, "PP16sl", - (int(handle), int(hdevnotify), _make_memory(guid), name_offset), + (int(handle), int(hdevnotify), bytes(memoryview(guid)), name_offset), data, ) @@ -925,20 +889,14 @@ def PackDEV_BROADCAST_VOLUME(unitmask, flags): def PackDEV_BROADCAST_DEVICEINTERFACE(classguid, name=""): - if win32gui.UNICODE: - # This really means "is py3k?" - so not accepting bytes is OK - if not isinstance(name, str): - raise TypeError("Must provide unicode for the name") - name = name.encode("utf-16le") - else: - # py2k was passed a unicode object - encode as mbcs. - if isinstance(name, str): - name = name.encode("mbcs") + if not isinstance(name, str): + raise TypeError("Must provide unicode for the name") + name = name.encode("utf-16le") # 16 bytes for the IID followed by \0 term'd string. rest_fmt = "16s%ds" % len(name) - # _make_memory(iid) hoops necessary to get the raw IID bytes. - rest_data = (_make_memory(pywintypes.IID(classguid)), name) + # bytes(memoryview(iid)) hoops necessary to get the raw IID bytes. + rest_data = (bytes(memoryview(pywintypes.IID(classguid))), name) return PackDEV_BROADCAST(win32con.DBT_DEVTYP_DEVICEINTERFACE, rest_fmt, rest_data) diff --git a/win32/Lib/win32timezone.py b/win32/Lib/win32timezone.py index 95e8ae310d..d3b50e3368 100644 --- a/win32/Lib/win32timezone.py +++ b/win32/Lib/win32timezone.py @@ -233,22 +233,22 @@ """ __author__ = "Jason R. Coombs " -import winreg -import struct import datetime -import win32api -import re +import logging import operator +import re +import struct +import winreg from itertools import count -import logging +import win32api log = logging.getLogger(__file__) # 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 = {} @@ -888,15 +888,6 @@ def __getitem__(self, filename): def resolveMUITimeZone(spec): """Resolve a multilingual user interface resource for the time zone name - >>> #some pre-amble for the doc-tests to be py2k and py3k aware) - >>> try: unicode and None - ... except NameError: unicode=str - ... - >>> import sys - >>> result = resolveMUITimeZone('@tzres.dll,-110') - >>> expectedResultType = [type(None),unicode][sys.getwindowsversion() >= (6,)] - >>> type(result) is expectedResultType - True spec should be of the format @path,-stringID[;comment] see http://msdn2.microsoft.com/en-us/library/ms725481.aspx for details @@ -923,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/win32verstamp.py b/win32/Lib/win32verstamp.py index ae818797cc..110c2be1c4 100644 --- a/win32/Lib/win32verstamp.py +++ b/win32/Lib/win32verstamp.py @@ -1,21 +1,19 @@ """ Stamp a Win32 binary with version information. """ -from win32api import BeginUpdateResource, UpdateResource, EndUpdateResource - +import glob +import optparse import os import struct -import glob -import sys -import optparse +from win32api import BeginUpdateResource, EndUpdateResource, UpdateResource VS_FFI_SIGNATURE = -17890115 # 0xFEEF04BD VS_FFI_STRUCVERSION = 0x00010000 VS_FFI_FILEFLAGSMASK = 0x0000003F VOS_NT_WINDOWS32 = 0x00040004 -null_byte = "\0".encode("ascii") # str in py2k, bytes in py3k +null_byte = b"\0" # # Set VS_FF_PRERELEASE and DEBUG if Debug # @@ -52,10 +50,7 @@ def VS_FIXEDFILEINFO(maj, min, sub, build, debug=0, is_dll=1): def nullterm(s): # get raw bytes for a NULL terminated unicode string. - if sys.version_info[:2] < (3, 7): - return (str(s) + "\0").encode("unicode-internal") - else: - return (str(s) + "\0").encode("utf-16le") + return (str(s) + "\0").encode("utf-16le") def pad32(s, extra=2): diff --git a/win32/Lib/winnt.py b/win32/Lib/winnt.py index 2848794a49..f4319cd939 100644 --- a/win32/Lib/winnt.py +++ b/win32/Lib/winnt.py @@ -191,18 +191,6 @@ def DBG_UNREFERENCED_LOCAL_VARIABLE(V): return V -def UNREFERENCED_PARAMETER(P): - return - - -def DBG_UNREFERENCED_PARAMETER(P): - return - - -def DBG_UNREFERENCED_LOCAL_VARIABLE(V): - return - - MAXIMUM_WAIT_OBJECTS = 64 MAXIMUM_SUSPEND_COUNT = MAXCHAR diff --git a/win32/test/handles.py b/win32/test/handles.py index 51751815ad..5f8b00d9e1 100644 --- a/win32/test/handles.py +++ b/win32/test/handles.py @@ -1,8 +1,10 @@ import sys import unittest + import pywintypes import win32api + # A class that will never die vie refcounting, but will die via GC. class Cycle: def __init__(self, handle): @@ -136,17 +138,13 @@ def testHandleNonZero(self): self.assertTrue(h) def testLong(self): - # sys.maxint+1 should always be a 'valid' handle, treated as an + # sys.maxsize+1 should always be a 'valid' handle, treated as an # unsigned int, even though it is a long. Although pywin32 should not # directly create such longs, using struct.unpack() with a P format # may well return them. eg: # >>> struct.unpack("P", struct.pack("P", -1)) # (4294967295L,) - try: - big = sys.maxsize - except AttributeError: - big = sys.maxint - pywintypes.HANDLE(big + 1) + pywintypes.HANDLE(sys.maxsize + 1) def testGC(self): # This used to provoke: diff --git a/win32/test/test_clipboard.py b/win32/test/test_clipboard.py index ca507b29d3..8f74e8575e 100644 --- a/win32/test/test_clipboard.py +++ b/win32/test/test_clipboard.py @@ -1,20 +1,20 @@ # General test module for win32api - please add some :) -import sys, os +import array +import os +import sys import unittest -from win32clipboard import * -import win32gui, win32con import pywintypes -import array - -from pywin32_testutil import str2bytes +import win32con +import win32gui +from win32clipboard import * custom_format_name = "PythonClipboardTestFormat" class CrashingTestCase(unittest.TestCase): def test_722082(self): - class crasher(object): + class crasher: pass obj = crasher() @@ -74,15 +74,15 @@ def test_unicode(self): def test_unicode_text(self): val = "test-val" SetClipboardText(val) - # GetClipboardData doesn't to auto string conversions - so on py3k, - # CF_TEXT returns bytes. - expected = str2bytes(val) + # GetClipboardData doesn't do auto string conversions - + # so CF_TEXT returns bytes. + expected = val.encode("latin1") self.assertEqual(GetClipboardData(win32con.CF_TEXT), expected) SetClipboardText(val, win32con.CF_UNICODETEXT) self.assertEqual(GetClipboardData(win32con.CF_UNICODETEXT), val) def test_string(self): - val = str2bytes("test") + val = b"test" SetClipboardData(win32con.CF_TEXT, val) self.assertEqual(GetClipboardData(win32con.CF_TEXT), val) @@ -95,8 +95,8 @@ def tearDown(self): CloseClipboard() def test_mem(self): - val = str2bytes("test") - expected = str2bytes("test\0") + val = b"test" + expected = b"test\0" SetClipboardData(win32con.CF_TEXT, val) # Get the raw data - this will include the '\0' raw_data = GetGlobalMemory(GetClipboardDataHandle(win32con.CF_TEXT)) @@ -112,7 +112,7 @@ def test_bad_mem(self): self.assertRaises(pywintypes.error, GetGlobalMemory, 1) def test_custom_mem(self): - test_data = str2bytes("hello\x00\xff") + test_data = b"hello\x00\xff" test_buffer = array.array("b", test_data) cf = RegisterClipboardFormat(custom_format_name) self.assertEqual(custom_format_name, GetClipboardFormatName(cf)) diff --git a/win32/test/test_exceptions.py b/win32/test/test_exceptions.py index 946a04b19e..2944da364c 100644 --- a/win32/test/test_exceptions.py +++ b/win32/test/test_exceptions.py @@ -1,17 +1,16 @@ """Test pywin32's error semantics""" -import sys import unittest -import win32api, win32file, pywintypes + import pythoncom +import pywintypes +import win32api +import win32file import winerror 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) @@ -63,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() @@ -156,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_odbc.py b/win32/test/test_odbc.py index cf34169ff9..8cba6310f3 100644 --- a/win32/test/test_odbc.py +++ b/win32/test/test_odbc.py @@ -1,16 +1,16 @@ # odbc test suite kindly contributed by Frank Millman. -import sys import os -import unittest -import odbc +import sys import tempfile +import unittest -from pywin32_testutil import str2bytes, str2memory, TestSkipped +import odbc +import pythoncom +from pywin32_testutil import TestSkipped +from win32com.client import constants # We use the DAO ODBC driver from win32com.client.gencache import EnsureDispatch -from win32com.client import constants -import pythoncom class TestStuff(unittest.TestCase): @@ -185,11 +185,7 @@ def testBit(self): def testInt(self): self._test_val("intfield", 1) self._test_val("intfield", 0) - try: - big = sys.maxsize - except AttributeError: - big = sys.maxint - self._test_val("intfield", big) + self._test_val("intfield", sys.maxsize) def testFloat(self): self._test_val("floatfield", 1.01) @@ -206,11 +202,11 @@ def testLongVarchar(self): def testLongBinary(self): """Test a long raw field in excess of internal cursor data size (65536)""" - self._test_val("longbinaryfield", str2memory("\0\1\2" * 70000)) + self._test_val("longbinaryfield", memoryview(b"\0\1\2" * 70000)) def testRaw(self): ## Test binary data - self._test_val("rawfield", str2memory("\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. @@ -244,7 +240,7 @@ def test_set_zero_length(self): self.assertEqual( self.cur.execute( "insert into %s (userid,username) " "values (?,?)" % self.tablename, - [str2bytes("Frank"), ""], + [b"Frank", ""], ), 1, ) diff --git a/win32/test/test_pywintypes.py b/win32/test/test_pywintypes.py index f8a16d757f..101019e2ed 100644 --- a/win32/test/test_pywintypes.py +++ b/win32/test/test_pywintypes.py @@ -1,10 +1,9 @@ -import sys -import unittest -import pywintypes -import time -from pywin32_testutil import str2bytes, ob2memory import datetime import operator +import time +import unittest + +import pywintypes class TestCase(unittest.TestCase): @@ -84,11 +83,9 @@ def testPyTimeTooLarge(self): def testGUID(self): s = "{00020400-0000-0000-C000-000000000046}" iid = pywintypes.IID(s) - iid2 = pywintypes.IID(ob2memory(iid), True) + iid2 = pywintypes.IID(memoryview(iid), True) self.assertEqual(iid, iid2) - self.assertRaises( - ValueError, pywintypes.IID, str2bytes("00"), True - ) # too short + self.assertRaises(ValueError, pywintypes.IID, b"00", True) # too short self.assertRaises(TypeError, pywintypes.IID, 0, True) # no buffer def testGUIDRichCmp(self): @@ -98,11 +95,10 @@ def testGUIDRichCmp(self): self.assertFalse(None == s) self.assertTrue(s != 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_security.py b/win32/test/test_security.py index 93fef98199..3cc8f64a07 100644 --- a/win32/test/test_security.py +++ b/win32/test/test_security.py @@ -1,10 +1,14 @@ # Tests for the win32security module. -import sys, os +import os import unittest -import winerror -from pywin32_testutil import testmain, TestSkipped, ob2memory -import win32api, win32con, win32security, ntsecuritycon, pywintypes +import ntsecuritycon +import pywintypes +import win32api +import win32con +import win32security +import winerror +from pywin32_testutil import TestSkipped, testmain class SecurityTests(unittest.TestCase): @@ -50,8 +54,8 @@ def testBuffer(self): if self.admin_sid is None: raise TestSkipped("No 'Administrator' account is available") self.assertEqual( - ob2memory(win32security.LookupAccountName("", "Administrator")[0]), - ob2memory(win32security.LookupAccountName("", "Administrator")[0]), + memoryview(win32security.LookupAccountName("", "Administrator")[0]), + memoryview(win32security.LookupAccountName("", "Administrator")[0]), ) def testMemory(self): diff --git a/win32/test/test_sspi.py b/win32/test/test_sspi.py index 05898092e7..7010cdfe32 100644 --- a/win32/test/test_sspi.py +++ b/win32/test/test_sspi.py @@ -2,10 +2,15 @@ # Stolen from Roger's original test_sspi.c, a version of which is in "Demos" # See also the other SSPI demos. import re -import win32security, sspi, sspicon, win32api -from pywin32_testutil import TestSkipped, testmain, str2bytes import unittest +import sspi +import sspicon +import win32api +import win32security +from pywin32_testutil import TestSkipped, testmain + + # It is quite likely that the Kerberos tests will fail due to not being # installed. The NTLM tests do *not* get the same behaviour as they should # always be there. @@ -59,7 +64,7 @@ def _doTestEncrypt(self, pkg_name): pkg_size_info = sspiclient.ctxt.QueryContextAttributes( sspicon.SECPKG_ATTR_SIZES ) - msg = str2bytes("some data to be encrypted ......") + msg = b"some data to be encrypted ......" trailersize = pkg_size_info["SecurityTrailer"] encbuf = win32security.PySecBufferDescType() @@ -72,7 +77,7 @@ def _doTestEncrypt(self, pkg_name): sspiserver.ctxt.DecryptMessage(encbuf, 1) self.assertEqual(msg, encbuf[0].Buffer) # and test the higher-level functions - data_in = str2bytes("hello") + data_in = b"hello" data, sig = sspiclient.encrypt(data_in) self.assertEqual(sspiserver.decrypt(data, sig), data_in) @@ -88,7 +93,7 @@ def _doTestEncryptStream(self, pkg_name): pkg_size_info = sspiclient.ctxt.QueryContextAttributes( sspicon.SECPKG_ATTR_SIZES ) - msg = str2bytes("some data to be encrypted ......") + msg = b"some data to be encrypted ......" trailersize = pkg_size_info["SecurityTrailer"] blocksize = pkg_size_info["BlockSize"] @@ -133,7 +138,7 @@ def _doTestSign(self, pkg_name): pkg_size_info = sspiclient.ctxt.QueryContextAttributes( sspicon.SECPKG_ATTR_SIZES ) - msg = str2bytes("some data to be encrypted ......") + msg = b"some data to be encrypted ......" sigsize = pkg_size_info["MaxSignature"] sigbuf = win32security.PySecBufferDescType() @@ -145,7 +150,7 @@ def _doTestSign(self, pkg_name): # and test the higher-level functions sspiclient.next_seq_num = 1 sspiserver.next_seq_num = 1 - data = str2bytes("hello") + data = b"hello" key = sspiclient.sign(data) sspiserver.verify(data, key) key = sspiclient.sign(data) @@ -194,32 +199,31 @@ def testSequenceEncrypt(self): def testSecBufferRepr(self): desc = win32security.PySecBufferDescType() assert re.match( - "PySecBufferDesc\(ulVersion: 0 \| cBuffers: 0 \| pBuffers: 0x[\da-fA-F]{8,16}\)", + r"PySecBufferDesc\(ulVersion: 0 \| cBuffers: 0 \| pBuffers: 0x[\da-fA-F]{8,16}\)", repr(desc), ) buffer1 = win32security.PySecBufferType(0, sspicon.SECBUFFER_TOKEN) assert re.match( - "PySecBuffer\(cbBuffer: 0 \| BufferType: 2 \| pvBuffer: 0x[\da-fA-F]{8,16}\)", + 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( - "PySecBufferDesc\(ulVersion: 0 \| cBuffers: 1 \| pBuffers: 0x[\da-fA-F]{8,16}\)", + r"PySecBufferDesc\(ulVersion: 0 \| cBuffers: 1 \| pBuffers: 0x[\da-fA-F]{8,16}\)", repr(desc), ) buffer2 = win32security.PySecBufferType(4, sspicon.SECBUFFER_DATA) assert re.match( - "PySecBuffer\(cbBuffer: 4 \| BufferType: 1 \| pvBuffer: 0x[\da-fA-F]{8,16}\)", + r"PySecBuffer\(cbBuffer: 4 \| BufferType: 1 \| pvBuffer: 0x[\da-fA-F]{8,16}\)", repr(buffer2), ) desc.append(buffer2) assert re.match( - "PySecBufferDesc\(ulVersion: 0 \| cBuffers: 2 \| pBuffers: 0x[\da-fA-F]{8,16}\)", + r"PySecBufferDesc\(ulVersion: 0 \| cBuffers: 2 \| pBuffers: 0x[\da-fA-F]{8,16}\)", repr(desc), ) diff --git a/win32/test/test_win32api.py b/win32/test/test_win32api.py index 8364db5e91..7570a958b2 100644 --- a/win32/test/test_win32api.py +++ b/win32/test/test_win32api.py @@ -1,12 +1,16 @@ # General test module for win32api - please add some :) +import datetime +import os +import sys +import tempfile import unittest -from pywin32_testutil import str2bytes, TestSkipped -import win32api, win32con, win32event, winerror -import sys, os -import tempfile -import datetime +import win32api +import win32con +import win32event +import winerror +from pywin32_testutil import TestSkipped class CurrentUserTestCase(unittest.TestCase): @@ -92,7 +96,7 @@ def testValues(self): ( "REG_BINARY", win32con.REG_BINARY, - str2bytes("\x00\x01\x02\x03\x04\x05\x06\x07\x08\x01\x00"), + b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x01\x00", ), ) diff --git a/win32/test/test_win32file.py b/win32/test/test_win32file.py index 99c01d43cd..3784bfed14 100644 --- a/win32/test/test_win32file.py +++ b/win32/test/test_win32file.py @@ -1,17 +1,23 @@ -import unittest -from pywin32_testutil import str2bytes, TestSkipped, testmain -import win32api, win32file, win32pipe, pywintypes, winerror, win32event -import win32con, ntsecuritycon -import sys +import datetime import os +import random +import shutil +import socket import tempfile import threading import time -import shutil -import socket -import datetime -import random +import unittest + +import ntsecuritycon +import pywintypes +import win32api +import win32con +import win32event +import win32file +import win32pipe import win32timezone +import winerror +from pywin32_testutil import TestSkipped, testmain try: set @@ -31,7 +37,7 @@ def testSimpleIndex(self): def testSimpleSlice(self): buffer = win32file.AllocateReadBuffer(2) - val = str2bytes("\0\0") + val = b"\0\0" buffer[:2] = val self.assertEqual(buffer[0:2], val) @@ -44,7 +50,7 @@ def testSimpleFiles(self): handle = win32file.CreateFile( filename, win32file.GENERIC_WRITE, 0, None, win32con.CREATE_NEW, 0, None ) - test_data = str2bytes("Hello\0there") + test_data = b"Hello\0there" try: win32file.WriteFile(handle, test_data) handle.Close() @@ -85,7 +91,7 @@ def testMoreFiles(self): ) # Write a known number of bytes to the file. - data = str2bytes("z") * 1025 + data = b"z" * 1025 win32file.WriteFile(h, data) @@ -148,7 +154,7 @@ def testFilePointer(self): ) try: # Write some data - data = str2bytes("Some data") + data = b"Some data" (res, written) = win32file.WriteFile(f, data) self.assertFalse(res) @@ -306,7 +312,7 @@ def testSimpleOverlapped(self): h = win32file.CreateFile( testName, desiredAccess, 0, None, win32file.CREATE_ALWAYS, 0, 0 ) - chunk_data = str2bytes("z") * 0x8000 + chunk_data = b"z" * 0x8000 num_loops = 512 expected_size = num_loops * len(chunk_data) for i in range(num_loops): @@ -434,7 +440,7 @@ def testCompletionPortsNonQueued(self, test_overlapped_death=0): time.sleep(0.1) # let thread do its thing. try: win32pipe.CallNamedPipe( - r"\\.\pipe\pywin32_test_pipe", str2bytes("Hello there"), BUFSIZE, 0 + r"\\.\pipe\pywin32_test_pipe", b"Hello there", BUFSIZE, 0 ) except win32pipe.error: # Testing for overlapped death causes this @@ -524,7 +530,7 @@ def testAcceptEx(self): self.fail("AcceptEx Worker thread failed to start") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("127.0.0.1", port)) - win32file.WSASend(s, str2bytes("hello"), None) + win32file.WSASend(s, b"hello", None) overlapped = pywintypes.OVERLAPPED() overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None) # Like above - WSARecv used to allow strings as the receive buffer!! @@ -535,7 +541,7 @@ def testAcceptEx(self): win32file.WSARecv(s, buffer, overlapped) nbytes = win32file.GetOverlappedResult(s.fileno(), overlapped, True) got = buffer[:nbytes] - self.assertEqual(got, str2bytes("hello")) + self.assertEqual(got, b"hello") # thread should have stopped stopped.wait(2) if not stopped.isSet(): @@ -714,7 +720,7 @@ class TestEncrypt(unittest.TestCase): def testEncrypt(self): fname = tempfile.mktemp("win32file_test") f = open(fname, "wb") - f.write(str2bytes("hello")) + f.write(b"hello") f.close() f = None try: @@ -768,7 +774,7 @@ def connect_thread_runner(self, expect_payload, giveup_event): nbytes = win32file.GetOverlappedResult(listener.fileno(), overlapped, False) if expect_payload: self.request = buffer[:nbytes] - accepter.send(str2bytes("some expected response")) + accepter.send(b"some expected response") def test_connect_with_payload(self): giveup_event = win32event.CreateEvent(None, 0, 0, None) @@ -781,7 +787,7 @@ def test_connect_with_payload(self): ol = pywintypes.OVERLAPPED() s2.bind(("0.0.0.0", 0)) # connectex requires the socket be bound beforehand try: - win32file.ConnectEx(s2, self.addr, ol, str2bytes("some expected request")) + win32file.ConnectEx(s2, self.addr, ol, b"some expected request") except win32file.error as exc: win32event.SetEvent(giveup_event) if exc.winerror == 10022: # WSAEINVAL @@ -800,8 +806,8 @@ def test_connect_with_payload(self): win32file.WSARecv(s2, buff, ol, 0) length = win32file.GetOverlappedResult(s2.fileno(), ol, 1) self.response = buff[:length] - self.assertEqual(self.response, str2bytes("some expected response")) - self.assertEqual(self.request, str2bytes("some expected request")) + self.assertEqual(self.response, b"some expected response") + self.assertEqual(self.request, b"some expected request") t.join(5) self.assertFalse(t.is_alive(), "worker thread didn't terminate") @@ -836,7 +842,7 @@ def test_connect_without_payload(self): win32file.WSARecv(s2, buff, ol, 0) length = win32file.GetOverlappedResult(s2.fileno(), ol, 1) self.response = buff[:length] - self.assertEqual(self.response, str2bytes("some expected response")) + self.assertEqual(self.response, b"some expected response") t.join(5) self.assertFalse(t.is_alive(), "worker thread didn't terminate") @@ -883,11 +889,11 @@ def runner(): s2.connect(self.addr) length = 0 - aaa = str2bytes("[AAA]") - bbb = str2bytes("[BBB]") - ccc = str2bytes("[CCC]") - ddd = str2bytes("[DDD]") - empty = str2bytes("") + aaa = b"[AAA]" + bbb = b"[BBB]" + ccc = b"[CCC]" + ddd = b"[DDD]" + empty = b"" ol = pywintypes.OVERLAPPED() f.seek(0) win32file.TransmitFile( @@ -925,7 +931,7 @@ def runner(): s2.close() th.join() - buf = str2bytes("").join(self.request) + buf = b"".join(self.request) self.assertEqual(length, len(buf)) expected = val + aaa + val + bbb + val + val + ccc + ddd + val self.assertEqual(type(expected), type(buf)) @@ -1008,7 +1014,7 @@ def test_functional(self): events = win32file.WSAEnumNetworkEvents(client, client_event) self.assertEqual(events, {win32file.FD_CONNECT: 0, win32file.FD_WRITE: 0}) sent = 0 - data = str2bytes("x") * 16 * 1024 + data = b"x" * 16 * 1024 while sent < 16 * 1024 * 1024: try: sent += client.send(data) diff --git a/win32/test/test_win32inet.py b/win32/test/test_win32inet.py index 837e56d5b2..d2d30c5252 100644 --- a/win32/test/test_win32inet.py +++ b/win32/test/test_win32inet.py @@ -1,11 +1,9 @@ +import unittest + +import winerror +from pywin32_testutil import TestSkipped, testmain from win32inet import * from win32inetcon import * -import winerror -from pywin32_testutil import str2bytes # py3k-friendly helper -from pywin32_testutil import TestSkipped -from pywin32_testutil import testmain - -import unittest class CookieTests(unittest.TestCase): @@ -54,8 +52,8 @@ def testPythonDotOrg(self): if not chunk: break chunks.append(chunk) - data = str2bytes("").join(chunks) - assert data.find(str2bytes("Python")) > 0, repr( + data = b"".join(chunks) + assert data.find(b"Python") > 0, repr( data ) # This must appear somewhere on the main page! diff --git a/win32/test/test_win32pipe.py b/win32/test/test_win32pipe.py index 4dfb8e8080..00a474caba 100644 --- a/win32/test/test_win32pipe.py +++ b/win32/test/test_win32pipe.py @@ -1,15 +1,13 @@ -import unittest -import time import threading -from pywin32_testutil import str2bytes # py3k-friendly helper - +import time +import unittest -import win32pipe -import win32file -import win32event import pywintypes -import winerror import win32con +import win32event +import win32file +import win32pipe +import winerror class PipeTests(unittest.TestCase): @@ -22,9 +20,9 @@ def _serverThread(self, pipe_handle, event, wait_time): hr in (0, winerror.ERROR_PIPE_CONNECTED), "Got error code 0x%x" % (hr,) ) hr, got = win32file.ReadFile(pipe_handle, 100) - self.assertEqual(got, str2bytes("foo\0bar")) + self.assertEqual(got, b"foo\0bar") time.sleep(wait_time) - win32file.WriteFile(pipe_handle, str2bytes("bar\0foo")) + win32file.WriteFile(pipe_handle, b"bar\0foo") pipe_handle.Close() event.set() @@ -55,9 +53,9 @@ def testCallNamedPipe(self): self.startPipeServer(event) got = win32pipe.CallNamedPipe( - self.pipename, str2bytes("foo\0bar"), 1024, win32pipe.NMPWAIT_WAIT_FOREVER + self.pipename, b"foo\0bar", 1024, win32pipe.NMPWAIT_WAIT_FOREVER ) - self.assertEqual(got, str2bytes("bar\0foo")) + self.assertEqual(got, b"bar\0foo") event.wait(5) self.assertTrue(event.isSet(), "Pipe server thread didn't terminate") @@ -81,8 +79,8 @@ def testTransactNamedPipeBlocking(self): hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None ) - hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), 1024, None) - self.assertEqual(got, str2bytes("bar\0foo")) + hr, got = win32pipe.TransactNamedPipe(hpipe, b"foo\0bar", 1024, None) + self.assertEqual(got, b"bar\0foo") event.wait(5) self.assertTrue(event.isSet(), "Pipe server thread didn't terminate") @@ -109,10 +107,8 @@ def testTransactNamedPipeBlockingBuffer(self): ) buffer = win32file.AllocateReadBuffer(1024) - hr, got = win32pipe.TransactNamedPipe( - hpipe, str2bytes("foo\0bar"), buffer, None - ) - self.assertEqual(got, str2bytes("bar\0foo")) + hr, got = win32pipe.TransactNamedPipe(hpipe, b"foo\0bar", buffer, None) + self.assertEqual(got, b"bar\0foo") event.wait(5) self.assertTrue(event.isSet(), "Pipe server thread didn't terminate") @@ -139,13 +135,11 @@ def testTransactNamedPipeAsync(self): ) buffer = win32file.AllocateReadBuffer(1024) - hr, got = win32pipe.TransactNamedPipe( - hpipe, str2bytes("foo\0bar"), buffer, overlapped - ) + hr, got = win32pipe.TransactNamedPipe(hpipe, b"foo\0bar", buffer, overlapped) self.assertEqual(hr, winerror.ERROR_IO_PENDING) nbytes = win32file.GetOverlappedResult(hpipe, overlapped, True) got = buffer[:nbytes] - self.assertEqual(got, str2bytes("bar\0foo")) + self.assertEqual(got, b"bar\0foo") event.wait(5) self.assertTrue(event.isSet(), "Pipe server thread didn't terminate") diff --git a/win32/test/test_win32timezone.py b/win32/test/test_win32timezone.py index 98de2d1191..4f77d437bb 100644 --- a/win32/test/test_win32timezone.py +++ b/win32/test/test_win32timezone.py @@ -1,23 +1,13 @@ # Test module for win32timezone -import sys +import doctest import unittest + import win32timezone -import doctest 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) diff --git a/win32/test/test_win32trace.py b/win32/test/test_win32trace.py index c96c66bcb1..969457a8c1 100644 --- a/win32/test/test_win32trace.py +++ b/win32/test/test_win32trace.py @@ -1,9 +1,10 @@ -import unittest -import win32trace -import threading -import time import os import sys +import threading +import time +import unittest + +import win32trace from pywin32_testutil import TestSkipped if __name__ == "__main__": @@ -119,8 +120,6 @@ def testRoundTrip(self): def testRoundTripUnicode(self): win32trace.write("\xa9opyright Syver Enstad") syverEnstad = win32trace.read() - # str objects are always returned in py2k (latin-1 encoding was used - # on unicode objects) self.assertEqual("\xa9opyright Syver Enstad", syverEnstad) def testBlockingRead(self): @@ -129,8 +128,6 @@ def testBlockingRead(self): def testBlockingReadUnicode(self): win32trace.write("\xa9opyright Syver Enstad") - # str objects are always returned in py2k (latin-1 encoding was used - # on unicode objects) self.assertEqual("\xa9opyright Syver Enstad", win32trace.blockingread()) def testFlush(self): diff --git a/win32/test/test_win32wnet.py b/win32/test/test_win32wnet.py index 2b3bc78e8b..eeb0146a61 100644 --- a/win32/test/test_win32wnet.py +++ b/win32/test/test_win32wnet.py @@ -1,9 +1,8 @@ import unittest -import win32wnet -import win32api -import netbios -from pywin32_testutil import str2bytes +import netbios +import win32api +import win32wnet RESOURCE_CONNECTED = 0x00000001 RESOURCE_GLOBALNET = 0x00000002 @@ -65,9 +64,9 @@ def _checkItemAttributes(self, item, attrs): new_val = val + 1 elif typ is str: if val is not None: - # on py2k, must be string or unicode. py3k must be string or bytes. + # must be string or bytes. self.assertTrue( - type(val) in (str, str), "Attr %r has value %r" % (attr, val) + type(val) in (str, bytes), "Attr %r has value %r" % (attr, val) ) new_val = val + " new value" else: @@ -108,13 +107,13 @@ def testNetbios(self): for i in range(la_enum.length): ncb.Reset() ncb.Command = netbios.NCBRESET - ncb.Lana_num = netbios.byte_to_int(la_enum.lana[i]) + ncb.Lana_num = la_enum.lana[i] rc = Netbios(ncb) self.assertEqual(rc, 0) ncb.Reset() ncb.Command = netbios.NCBASTAT - ncb.Lana_num = byte_to_int(la_enum.lana[i]) - ncb.Callname = str2bytes("* ") # ensure bytes on py2x and 3k + ncb.Lana_num = la_enum.lana[i] + ncb.Callname = b"* " adapter = netbios.ADAPTER_STATUS() ncb.Buffer = adapter Netbios(ncb) diff --git a/win32/test/testall.py b/win32/test/testall.py index 179c27467c..85adf736e3 100644 --- a/win32/test/testall.py +++ b/win32/test/testall.py @@ -1,7 +1,9 @@ -import sys, os +import os import re -import unittest +import sys import traceback +import unittest + import pywin32_testutil # A list of demos that depend on user-interface of *any* kind. Tests listed @@ -30,7 +32,7 @@ no_user_interaction = True # re to pull apart an exception line into the exception type and the args. -re_exception = re.compile("([a-zA-Z0-9_.]*): (.*)$") +re_exception = re.compile(r"([a-zA-Z0-9_.]*): (.*)$") def find_exception_in_output(data): From 03400f1693d33c5a2962c6d54bf6ede837c84007 Mon Sep 17 00:00:00 2001 From: Avasam Date: Sun, 19 Feb 2023 18:31:18 -0500 Subject: [PATCH 02/24] Revert sorting and organizing imports. leave that to #1986 --- Pythonwin/Scintilla/src/LexGen.py | 4 +-- Pythonwin/pywin/debugger/debugger.py | 20 ++++++------- Pythonwin/pywin/framework/app.py | 15 +++++----- Pythonwin/pywin/framework/editor/editor.py | 16 +++++------ Pythonwin/pywin/framework/interact.py | 26 ++++++++--------- Pythonwin/pywin/framework/mdi_pychecker.py | 14 ++-------- Pythonwin/pywin/framework/scriptutils.py | 15 +++++----- Pythonwin/pywin/framework/sgrepmdi.py | 15 +++++----- Pythonwin/pywin/framework/toolmenu.py | 12 ++++---- Pythonwin/pywin/framework/winout.py | 17 ++++------- Pythonwin/pywin/idle/AutoIndent.py | 8 ++---- Pythonwin/pywin/idle/FormatParagraph.py | 2 +- Pythonwin/pywin/idle/PyParse.py | 2 +- Pythonwin/pywin/mfc/activex.py | 4 +-- Pythonwin/pywin/mfc/dialog.py | 2 +- Pythonwin/pywin/scintilla/control.py | 16 +++++------ Pythonwin/pywin/scintilla/document.py | 14 ++++------ Pythonwin/pywin/scintilla/view.py | 27 ++++++++++-------- Pythonwin/pywin/tools/browser.py | 6 ++-- Pythonwin/pywin/tools/hierlist.py | 9 +++--- adodbapi/__init__.py | 28 +++++++++---------- adodbapi/adodbapi.py | 4 +-- adodbapi/apibase.py | 4 +-- adodbapi/remote.py | 4 +-- adodbapi/remote/server.py | 6 ++-- adodbapi/setup.py | 4 ++- adodbapi/test/adodbapitest.py | 7 +++-- adodbapi/test/adodbapitestconfig.py | 2 +- adodbapi/test/dbapi20.py | 3 +- adodbapi/test/setuptestframework.py | 5 ++-- com/win32com/client/__init__.py | 7 ++--- com/win32com/client/build.py | 6 ++-- com/win32com/client/combrowse.py | 8 ++---- com/win32com/client/genpy.py | 3 +- com/win32com/client/makepy.py | 12 +++----- com/win32com/client/selecttlb.py | 4 +-- com/win32com/demos/connect.py | 5 ++-- com/win32com/demos/excelRTDServer.py | 6 ++-- com/win32com/demos/iebutton.py | 21 ++++++-------- com/win32com/demos/ietoolbar.py | 25 ++++++++--------- com/win32com/makegw/makegw.py | 1 - com/win32com/server/dispatcher.py | 8 ++---- com/win32com/server/register.py | 15 ++++------ com/win32com/test/testPersist.py | 24 ++++++++-------- com/win32com/test/testPippo.py | 3 +- com/win32com/test/testPyComTest.py | 18 ++++++------ com/win32com/test/testShell.py | 14 +++++----- com/win32com/test/testStreams.py | 4 +-- com/win32com/test/testall.py | 19 ++++--------- com/win32com/test/testvb.py | 10 +++---- com/win32com/test/testvbscript_regexp.py | 5 ++-- com/win32com/test/util.py | 23 ++++++++------- com/win32comext/axscript/client/debug.py | 22 +++++++-------- com/win32comext/axscript/client/error.py | 11 ++++---- com/win32comext/axscript/client/framework.py | 16 +++++------ com/win32comext/axscript/client/pyscript.py | 25 +++++++++-------- com/win32comext/axscript/test/leakTest.py | 9 +++--- com/win32comext/axscript/test/testHost.py | 12 ++++---- com/win32comext/mapi/mapiutil.py | 3 +- .../shell/demos/ITransferAdviseSink.py | 2 +- .../shell/demos/servers/copy_hook.py | 1 - isapi/samples/redirector.py | 4 +-- setup.py | 26 +++++++++-------- win32/Demos/BackupRead_BackupWrite.py | 13 ++------- .../Demos/CreateFileTransacted_MiniVersion.py | 11 ++------ win32/Demos/OpenEncryptedFileRaw.py | 5 +--- win32/Demos/eventLogDemo.py | 8 +++--- win32/Demos/mmapfile_demo.py | 7 ++--- win32/Demos/security/sspi/socket_server.py | 14 ++++++---- win32/Demos/service/pipeTestServiceClient.py | 13 ++++----- win32/Demos/win32clipboardDemo.py | 3 +- win32/Demos/win32fileDemo.py | 9 ++---- win32/Demos/win32gui_dialog.py | 16 ++++------- win32/Demos/win32gui_menu.py | 11 +++----- win32/Demos/win32gui_taskbar.py | 10 ++----- win32/Lib/netbios.py | 4 +-- win32/Lib/pywin32_testutil.py | 9 +++--- win32/Lib/pywintypes.py | 5 +--- win32/Lib/sspi.py | 4 +-- win32/Lib/win32gui_struct.py | 11 ++++---- win32/Lib/win32timezone.py | 10 +++---- win32/Lib/win32verstamp.py | 8 ++++-- win32/test/handles.py | 2 -- win32/test/test_clipboard.py | 10 +++---- win32/test/test_exceptions.py | 6 ++-- win32/test/test_odbc.py | 10 +++---- win32/test/test_pywintypes.py | 8 +++--- win32/test/test_security.py | 12 +++----- win32/test/test_sspi.py | 9 ++---- win32/test/test_win32api.py | 14 ++++------ win32/test/test_win32file.py | 24 ++++++---------- win32/test/test_win32inet.py | 9 +++--- win32/test/test_win32pipe.py | 12 ++++---- win32/test/test_win32timezone.py | 4 +-- win32/test/test_win32trace.py | 9 +++--- win32/test/test_win32wnet.py | 5 ++-- win32/test/testall.py | 6 ++-- 97 files changed, 430 insertions(+), 564 deletions(-) diff --git a/Pythonwin/Scintilla/src/LexGen.py b/Pythonwin/Scintilla/src/LexGen.py index 3ba2d2c2f7..47505fafb8 100644 --- a/Pythonwin/Scintilla/src/LexGen.py +++ b/Pythonwin/Scintilla/src/LexGen.py @@ -16,10 +16,10 @@ # Does not regenerate the Visual C++ 6 project files but does the VS .NET # project file. -import glob -import os import string import sys +import os +import glob # EOL constants CR = "\r" diff --git a/Pythonwin/pywin/debugger/debugger.py b/Pythonwin/pywin/debugger/debugger.py index 53ebadf373..b54a84ddaa 100644 --- a/Pythonwin/pywin/debugger/debugger.py +++ b/Pythonwin/pywin/debugger/debugger.py @@ -8,23 +8,23 @@ # >>> import pywin.debugger # >>> pywin.debugger.GetDebugger().run("command") -import bdb -import os import pdb -import string +import bdb import sys -import traceback +import string +import os import types -import commctrl -import pywin.docking.DockingBar +import win32ui import win32api import win32con -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 +import pywin.docking.DockingBar +from pywin.mfc import dialog, object, afxres, window +from pywin.framework import app, interact, editor, scriptutils +from pywin.framework.editor.color.coloreditor import MARKER_CURRENT, MARKER_BREAKPOINT from pywin.tools import browser, hierlist +import commctrl +import traceback # import win32traceutil LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITW diff --git a/Pythonwin/pywin/framework/app.py b/Pythonwin/pywin/framework/app.py index 56fea1bb19..1c900dfe9e 100644 --- a/Pythonwin/pywin/framework/app.py +++ b/Pythonwin/pywin/framework/app.py @@ -4,17 +4,16 @@ # # We also grab the FileOpen command, to invoke our Python editor " The PythonWin application code. Manages most aspects of MDI, etc " -import os -import string -import sys -import traceback - -import regutil -import win32api import win32con +import win32api import win32ui -from pywin.mfc import afxres, dialog, window +import sys +import string +import os +from pywin.mfc import window, dialog, afxres from pywin.mfc.thread import WinApp +import traceback +import regutil from . import scriptutils diff --git a/Pythonwin/pywin/framework/editor/editor.py b/Pythonwin/pywin/framework/editor/editor.py index fd80e5c719..50a76f9d16 100644 --- a/Pythonwin/pywin/framework/editor/editor.py +++ b/Pythonwin/pywin/framework/editor/editor.py @@ -17,23 +17,23 @@ # Note that it will _always_ prompt you if the file in the editor has been modified. -import os +import win32ui +import win32api +import win32con +import regex import re import string +import sys, os import traceback +from pywin.mfc import docview, dialog, afxres -import regex -import win32api -import win32con -import win32ui from pywin.framework.editor import ( - GetEditorFontOption, GetEditorOption, - SetEditorFontOption, SetEditorOption, + GetEditorFontOption, + SetEditorFontOption, defaultCharacterFormat, ) -from pywin.mfc import afxres, dialog, docview patImport = regex.symcomp(r"import \(.*\)") patIndent = regex.compile(r"^\\([ \t]*[~ \t]\\)") diff --git a/Pythonwin/pywin/framework/interact.py b/Pythonwin/pywin/framework/interact.py index 702e759354..7628c58dcd 100644 --- a/Pythonwin/pywin/framework/interact.py +++ b/Pythonwin/pywin/framework/interact.py @@ -3,23 +3,23 @@ ## Interactive Shell Window ## -import array +import sys, os import code -import os import string -import sys -import traceback -import __main__ -import afxres -import pywin.framework.app -import pywin.scintilla.control -import pywin.scintilla.formatter -import pywin.scintilla.IDLEenvironment +import win32ui import win32api import win32clipboard import win32con -import win32ui +import traceback +import afxres +import array +import __main__ + +import pywin.scintilla.formatter +import pywin.scintilla.control +import pywin.scintilla.IDLEenvironment +import pywin.framework.app ## sequential after ID_GOTO_LINE defined in editor.py ID_EDIT_COPY_CODE = 0xE2002 @@ -27,10 +27,10 @@ trace = pywin.scintilla.formatter.trace -import re - from . import winout +import re + # from IDLE. _is_block_opener = re.compile(r":\s*(#.*)?$").search _is_block_closer = re.compile( diff --git a/Pythonwin/pywin/framework/mdi_pychecker.py b/Pythonwin/pywin/framework/mdi_pychecker.py index 67dc4ec220..bd31532908 100644 --- a/Pythonwin/pywin/framework/mdi_pychecker.py +++ b/Pythonwin/pywin/framework/mdi_pychecker.py @@ -33,19 +33,11 @@ ## ###################################################################### -import glob -import os -import re -import stat -import string -import sys -import time - +import win32ui import win32api +from pywin.mfc import docview, dialog, window import win32con -import win32ui -from pywin.mfc import dialog, docview, window - +import sys, string, re, glob, os, stat, time from . import scriptutils diff --git a/Pythonwin/pywin/framework/scriptutils.py b/Pythonwin/pywin/framework/scriptutils.py index 5e9e54245e..b12457d27d 100644 --- a/Pythonwin/pywin/framework/scriptutils.py +++ b/Pythonwin/pywin/framework/scriptutils.py @@ -1,19 +1,18 @@ """ Various utilities for running/importing a script """ -import bdb -import linecache -import os -import string import sys -import traceback - -import __main__ +import win32ui import win32api import win32con -import win32ui +import __main__ from pywin.mfc import dialog from pywin.mfc.docview import TreeView +import os +import string +import traceback +import linecache +import bdb from .cmdline import ParseArgs diff --git a/Pythonwin/pywin/framework/sgrepmdi.py b/Pythonwin/pywin/framework/sgrepmdi.py index 5403c379bf..13f55aecc3 100644 --- a/Pythonwin/pywin/framework/sgrepmdi.py +++ b/Pythonwin/pywin/framework/sgrepmdi.py @@ -18,17 +18,16 @@ # Hats off to Mark Hammond for providing an environment where I could cobble # something like this together in a couple evenings! +import win32ui +import win32api +from pywin.mfc import docview, dialog, window +import win32con +import string +import re import glob import os -import re import stat -import string - -import win32api -import win32con -import win32ui -from pywin.mfc import dialog, docview, window - +import glob from . import scriptutils diff --git a/Pythonwin/pywin/framework/toolmenu.py b/Pythonwin/pywin/framework/toolmenu.py index 88dc5ddc48..2856de6040 100644 --- a/Pythonwin/pywin/framework/toolmenu.py +++ b/Pythonwin/pywin/framework/toolmenu.py @@ -1,13 +1,11 @@ # toolmenu.py -import string -import sys - -import win32api -import win32con import win32ui - +import win32con +import win32api from . import app +import sys +import string tools = {} idPos = 100 @@ -111,8 +109,8 @@ def SetToolsMenu(menu, menuPos=None): def HandleToolCommand(cmd, code): - import re import traceback + import re global tools (menuString, pyCmd, desc) = tools[cmd] diff --git a/Pythonwin/pywin/framework/winout.py b/Pythonwin/pywin/framework/winout.py index deaa0cef48..76043365cb 100644 --- a/Pythonwin/pywin/framework/winout.py +++ b/Pythonwin/pywin/framework/winout.py @@ -20,15 +20,11 @@ # This module is thread safe - output can originate from any thread. If any thread # other than the main thread attempts to print, it is always queued until next idle time -import queue -import re -import string - -import win32api -import win32con -import win32ui -from pywin.framework import app, window +import sys, string, re from pywin.mfc import docview +from pywin.framework import app, window +import win32ui, win32api, win32con +import queue debug = lambda msg: None @@ -47,8 +43,8 @@ class flags: # WindowOutputDocumentParent=docview.RichEditDoc # WindowOutputDocumentParent=docview.Document import pywin.scintilla.document -from pywin import default_scintilla_encoding from pywin.scintilla import scintillacon +from pywin import default_scintilla_encoding WindowOutputDocumentParent = pywin.scintilla.document.CScintillaDocument @@ -148,8 +144,7 @@ def HandleSpecialLine(self): # An OLE Exception - pull apart the exception # and try and locate a help file. try: - import win32api - import win32con + import win32api, win32con det = eval(line[line.find(":") + 1 :].strip()) win32ui.SetStatusText("Opening help file on OLE error...") diff --git a/Pythonwin/pywin/idle/AutoIndent.py b/Pythonwin/pywin/idle/AutoIndent.py index 6dafa9e9e2..6be149a508 100644 --- a/Pythonwin/pywin/idle/AutoIndent.py +++ b/Pythonwin/pywin/idle/AutoIndent.py @@ -1,9 +1,7 @@ -import string -import tokenize - -from pywin import default_scintilla_encoding - +import sys +import string, tokenize from . import PyParse +from pywin import default_scintilla_encoding # tokenize() is the generator working with 'byte' objects, and # token_generator is the 'undocumented b/w compat' function that diff --git a/Pythonwin/pywin/idle/FormatParagraph.py b/Pythonwin/pywin/idle/FormatParagraph.py index 2443cc1465..5ca2915832 100644 --- a/Pythonwin/pywin/idle/FormatParagraph.py +++ b/Pythonwin/pywin/idle/FormatParagraph.py @@ -14,8 +14,8 @@ # spaces, they will not be considered part of the same block. # * Fancy comments, like this bulleted list, arent handled :-) -import re import string +import re class FormatParagraph: diff --git a/Pythonwin/pywin/idle/PyParse.py b/Pythonwin/pywin/idle/PyParse.py index abebbca63f..cb67c0485a 100644 --- a/Pythonwin/pywin/idle/PyParse.py +++ b/Pythonwin/pywin/idle/PyParse.py @@ -1,5 +1,5 @@ -import re import string +import re import sys # Reason last stmt is continued (or C_NONE if it's not). diff --git a/Pythonwin/pywin/mfc/activex.py b/Pythonwin/pywin/mfc/activex.py index a9828e78dc..225c95d1db 100644 --- a/Pythonwin/pywin/mfc/activex.py +++ b/Pythonwin/pywin/mfc/activex.py @@ -1,8 +1,6 @@ """Support for ActiveX control hosting in Pythonwin. """ -import win32ui -import win32uiole - +import win32ui, win32uiole from . import window diff --git a/Pythonwin/pywin/mfc/dialog.py b/Pythonwin/pywin/mfc/dialog.py index 1a547bec36..276311b147 100644 --- a/Pythonwin/pywin/mfc/dialog.py +++ b/Pythonwin/pywin/mfc/dialog.py @@ -4,8 +4,8 @@ # dialog.py # Python class for Dialog Boxes in PythonWin. -import win32con import win32ui +import win32con # sob - 2to3 doesn't see this as a relative import :( from pywin.mfc import window diff --git a/Pythonwin/pywin/scintilla/control.py b/Pythonwin/pywin/scintilla/control.py index a786147bc2..f1ab4d0612 100644 --- a/Pythonwin/pywin/scintilla/control.py +++ b/Pythonwin/pywin/scintilla/control.py @@ -4,17 +4,15 @@ # a "standard" MFC edit control (eg, control.GetTextLength(), control.GetSel() # plus many Scintilla specific features (eg control.SCIAddStyledText()) -import array -import os -import string -import struct - -import win32api +from pywin.mfc import window +from pywin import default_scintilla_encoding import win32con import win32ui -from pywin import default_scintilla_encoding -from pywin.mfc import window - +import win32api +import array +import struct +import string +import os from . import scintillacon # Load Scintilla.dll to get access to the control. diff --git a/Pythonwin/pywin/scintilla/document.py b/Pythonwin/pywin/scintilla/document.py index 1a114173b1..32a3df9258 100644 --- a/Pythonwin/pywin/scintilla/document.py +++ b/Pythonwin/pywin/scintilla/document.py @@ -1,14 +1,12 @@ -import codecs -import os -import re -import string - -import win32con import win32ui -from pywin import default_scintilla_encoding from pywin.mfc import docview - +from pywin import default_scintilla_encoding from . import scintillacon +import win32con +import string +import os +import codecs +import re crlf_bytes = b"\r\n" lf_bytes = b"\n" diff --git a/Pythonwin/pywin/scintilla/view.py b/Pythonwin/pywin/scintilla/view.py index 910161bad4..f56838a1a6 100644 --- a/Pythonwin/pywin/scintilla/view.py +++ b/Pythonwin/pywin/scintilla/view.py @@ -1,20 +1,23 @@ # A general purpose MFC CCtrlView view that uses Scintilla. -import array -import os -import re +from . import control +from . import IDLEenvironment # IDLE emulation. +from pywin.mfc import docview +from pywin.mfc import dialog +from . import scintillacon +import win32con +import win32ui +import afxres import string -import struct +import array import sys - +import types import __main__ # for attribute lookup -import afxres -import win32con -import win32ui -from pywin.mfc import dialog, docview - -from . import IDLEenvironment # IDLE emulation. -from . import bindings, control, keycodes, scintillacon +from . import bindings +from . import keycodes +import struct +import re +import os PRINTDLGORD = 1538 IDC_PRINT_MAG_EDIT = 1010 diff --git a/Pythonwin/pywin/tools/browser.py b/Pythonwin/pywin/tools/browser.py index 1733f0ab97..2022a9ea29 100644 --- a/Pythonwin/pywin/tools/browser.py +++ b/Pythonwin/pywin/tools/browser.py @@ -7,7 +7,6 @@ # >>> browser.Browse(your_module) import sys import types - import __main__ import win32ui from pywin.mfc import dialog @@ -372,11 +371,10 @@ def ShowObject(object, title): dlg.DoModal() -import commctrl -import win32api - # And some mods for a sizable dialog from Sam Rushing! import win32con +import win32api +import commctrl class dynamic_browser(dialog.Dialog): diff --git a/Pythonwin/pywin/tools/hierlist.py b/Pythonwin/pywin/tools/hierlist.py index fc591666e1..8bb67a5c9b 100644 --- a/Pythonwin/pywin/tools/hierlist.py +++ b/Pythonwin/pywin/tools/hierlist.py @@ -13,13 +13,14 @@ # choice. However, you should investigate using the tree control directly # to provide maximum flexibility (but with extra work). -import commctrl -import win32api -import win32con +import sys import win32ui -from pywin.mfc import dialog, docview, object, window +import win32con +import win32api from win32api import RGB +from pywin.mfc import object, window, docview, dialog +import commctrl # helper to get the text of an arbitary item def GetItemText(item): diff --git a/adodbapi/__init__.py b/adodbapi/__init__.py index 787f2161f3..80ea48900d 100644 --- a/adodbapi/__init__.py +++ b/adodbapi/__init__.py @@ -3,30 +3,28 @@ Copyright (C) 2002 Henrik Ekelund, version 2.1 by Vernon Cole * http://sourceforge.net/projects/adodbapi """ +import sys import time -from .adodbapi import Connection, Cursor, __version__, connect, dateconverter +from .apibase import apilevel, threadsafety, paramstyle from .apibase import ( - BINARY, - DATETIME, - NUMBER, - ROWID, - STRING, + Warning, + Error, + InterfaceError, DatabaseError, DataError, - Error, - FetchFailedError, + OperationalError, IntegrityError, - InterfaceError, +) +from .apibase import ( InternalError, - NotSupportedError, - OperationalError, ProgrammingError, - Warning, - apilevel, - paramstyle, - threadsafety, + NotSupportedError, + FetchFailedError, ) +from .apibase import NUMBER, STRING, BINARY, DATETIME, ROWID + +from .adodbapi import connect, Connection, __version__, dateconverter, Cursor # ----------------------------------------------------------- diff --git a/adodbapi/adodbapi.py b/adodbapi/adodbapi.py index 4a7276b5ff..83dd94b5ec 100644 --- a/adodbapi/adodbapi.py +++ b/adodbapi/adodbapi.py @@ -35,9 +35,7 @@ import sys import weakref -from . import ado_consts as adc -from . import apibase as api -from . import process_connect_string +from . import ado_consts as adc, apibase as api, process_connect_string try: verbose = int(os.environ["ADODBAPI_VERBOSE"]) diff --git a/adodbapi/apibase.py b/adodbapi/apibase.py index 46be10285f..87d5e0db96 100644 --- a/adodbapi/apibase.py +++ b/adodbapi/apibase.py @@ -5,11 +5,11 @@ * http://sourceforge.net/projects/adodbapi """ +import sys +import time import datetime import decimal import numbers -import sys -import time # noinspection PyUnresolvedReferences from . import ado_consts as adc diff --git a/adodbapi/remote.py b/adodbapi/remote.py index 455e2fe7e4..4a43a129b2 100644 --- a/adodbapi/remote.py +++ b/adodbapi/remote.py @@ -28,11 +28,11 @@ __version__ = "3.7.0.0" version = "adodbapi.remote v" + __version__ -import array -import datetime import os import sys +import array import time +import datetime # Pyro4 is required for server and remote operation --> https://pypi.python.org/pypi/Pyro4/ try: diff --git a/adodbapi/remote/server.py b/adodbapi/remote/server.py index 36b217448d..5e5749e9d3 100644 --- a/adodbapi/remote/server.py +++ b/adodbapi/remote/server.py @@ -30,11 +30,11 @@ PYRO_COMMTIMEOUT = 40 # to be larger than the default database timeout SERVICE_NAME = "ado.connection" -import array -import datetime import os import sys import time +import array +import datetime # Pyro4 is required for server and remote operation --> https://pypi.python.org/pypi/Pyro4/ try: @@ -42,8 +42,8 @@ except ImportError: print('* * * Sorry, server operation requires Pyro4. Please "pip install" it.') exit(11) -import adodbapi import adodbapi.apibase as api +import adodbapi import adodbapi.process_connect_string try: diff --git a/adodbapi/setup.py b/adodbapi/setup.py index bd85486d2b..b6660fa9bb 100644 --- a/adodbapi/setup.py +++ b/adodbapi/setup.py @@ -38,11 +38,13 @@ break a.close() +import sys + def setup_package(): - from distutils.command.build_py import build_py from distutils.core import setup + from distutils.command.build_py import build_py setup( cmdclass={"build_py": build_py}, diff --git a/adodbapi/test/adodbapitest.py b/adodbapi/test/adodbapitest.py index 09bdf9e418..a66cae0837 100644 --- a/adodbapi/test/adodbapitest.py +++ b/adodbapi/test/adodbapitest.py @@ -21,13 +21,13 @@ Updates by Vernon Cole """ -import copy +import unittest +import sys import datetime import decimal +import copy import random import string -import sys -import unittest try: import win32com.client @@ -45,6 +45,7 @@ import adodbapi import adodbapi.apibase as api + try: import adodbapi.ado_consts as ado_consts except ImportError: # we are doing a shortcut import as a module -- so diff --git a/adodbapi/test/adodbapitestconfig.py b/adodbapi/test/adodbapitestconfig.py index e3ec196ced..0aed2feb63 100644 --- a/adodbapi/test/adodbapitestconfig.py +++ b/adodbapi/test/adodbapitestconfig.py @@ -12,8 +12,8 @@ # # -- the things you need to change are below it. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # import platform -import random import sys +import random import is64bit import setuptestframework diff --git a/adodbapi/test/dbapi20.py b/adodbapi/test/dbapi20.py index 3d6a8216ff..6f54efeff2 100644 --- a/adodbapi/test/dbapi20.py +++ b/adodbapi/test/dbapi20.py @@ -14,8 +14,9 @@ __version__ = "$Revision: 1.16.0 $"[11:-2] __author__ = "Stuart Bishop " -import time import unittest +import time +import sys def _failUnless(self, expr, msg=None): diff --git a/adodbapi/test/setuptestframework.py b/adodbapi/test/setuptestframework.py index 39c14a494c..795b3007b5 100644 --- a/adodbapi/test/setuptestframework.py +++ b/adodbapi/test/setuptestframework.py @@ -2,8 +2,9 @@ # Configure this in order to run the testcases. "setuptestframework.py v 3.7.0.0" import os -import shutil +import sys import tempfile +import shutil try: OSErrors = (WindowsError, OSError) @@ -74,8 +75,8 @@ def makemdb(testfolder, mdb_name): print("using JET database=", _accessdatasource) else: try: - from win32com.client import constants from win32com.client.gencache import EnsureDispatch + from win32com.client import constants win32 = True except ImportError: # perhaps we are not running CPython diff --git a/com/win32com/client/__init__.py b/com/win32com/client/__init__.py index bd045b6753..49a5b2d854 100644 --- a/com/win32com/client/__init__.py +++ b/com/win32com/client/__init__.py @@ -6,13 +6,12 @@ # dispatch object, the known class will be used. This contrasts # with dynamic.Dispatch behaviour, where dynamic objects are always used. -import sys - import pythoncom +from . import dynamic +from . import gencache +import sys import pywintypes -from . import dynamic, gencache - _PyIDispatchType = pythoncom.TypeIIDs[pythoncom.IID_IDispatch] diff --git a/com/win32com/client/build.py b/com/win32com/client/build.py index e40b8897db..0797983590 100644 --- a/com/win32com/client/build.py +++ b/com/win32com/client/build.py @@ -16,14 +16,14 @@ # # OleItem, DispatchItem, MapEntry, BuildCallList() is used by makepy -import datetime +import sys import string from keyword import iskeyword import pythoncom -import winerror from pywintypes import TimeType - +import winerror +import datetime # It isn't really clear what the quoting rules are in a C/IDL string and # literals like a quote char and backslashes makes life a little painful to diff --git a/com/win32com/client/combrowse.py b/com/win32com/client/combrowse.py index 93a24f4f91..0b32df2cd4 100644 --- a/com/win32com/client/combrowse.py +++ b/com/win32com/client/combrowse.py @@ -22,14 +22,12 @@ work. """ +import win32con +import win32api, win32ui import sys - import pythoncom -import win32api -import win32con -import win32ui -from pywin.tools import browser from win32com.client import util +from pywin.tools import browser class HLIRoot(browser.HLIPythonObject): diff --git a/com/win32com/client/genpy.py b/com/win32com/client/genpy.py index 0c75172c8b..12b528d096 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -16,10 +16,9 @@ import os import sys import time - -import pythoncom import win32com +import pythoncom from . import build error = "makepy.error" diff --git a/com/win32com/client/makepy.py b/com/win32com/client/makepy.py index 610178a0f7..59c0c4b00e 100644 --- a/com/win32com/client/makepy.py +++ b/com/win32com/client/makepy.py @@ -66,12 +66,9 @@ """ -import importlib -import os -import sys - -import pythoncom -from win32com.client import Dispatch, gencache, genpy, selecttlb +import sys, os, importlib, pythoncom +from win32com.client import genpy, selecttlb, gencache +from win32com.client import Dispatch bForDemandDefault = 0 # Default value of bForDemand - toggle this to change the world - see also gencache.py @@ -153,8 +150,7 @@ def LogWarning(self, desc): class GUIProgress(SimpleProgress): def __init__(self, verboseLevel): # Import some modules we need so we can trap failure now. - import pywin - import win32ui + import win32ui, pywin SimpleProgress.__init__(self, verboseLevel) self.dialog = None diff --git a/com/win32com/client/selecttlb.py b/com/win32com/client/selecttlb.py index 1337bc468b..5206fcc6d8 100644 --- a/com/win32com/client/selecttlb.py +++ b/com/win32com/client/selecttlb.py @@ -1,9 +1,7 @@ """Utilities for selecting and enumerating the Type Libraries installed on the system """ -import pythoncom -import win32api -import win32con +import win32api, win32con, pythoncom class TypelibSpec: diff --git a/com/win32com/demos/connect.py b/com/win32com/demos/connect.py index 7f5afb7947..d1b5b92c51 100644 --- a/com/win32com/demos/connect.py +++ b/com/win32com/demos/connect.py @@ -6,8 +6,8 @@ # is cheated on - so this is still working as a fully-fledged server. import pythoncom -import win32com.server.connect import win32com.server.util +import win32com.server.connect from win32com.server.exception import Exception # This is the IID of the Events interface both Client and Server support. @@ -74,8 +74,7 @@ def CheckEvent(server, client, val, verbose): # In the real world, it is likely that the code controlling the server # will be in the same class as that getting the notifications. def test(verbose=0): - import win32com.client.connect - import win32com.client.dynamic + import win32com.client.dynamic, win32com.client.connect import win32com.server.policy server = win32com.client.dynamic.Dispatch( diff --git a/com/win32com/demos/excelRTDServer.py b/com/win32com/demos/excelRTDServer.py index 6eda469530..ada923cd85 100644 --- a/com/win32com/demos/excelRTDServer.py +++ b/com/win32com/demos/excelRTDServer.py @@ -30,15 +30,15 @@ # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. -import datetime # For the example classes... -import threading - import pythoncom import win32com.client from win32com import universal from win32com.client import gencache from win32com.server.exception import COMException +import threading +import datetime # For the example classes... + # Typelib info for version 10 - aka Excel XP. # This is the minimum version of excel that we can work with as this is when # Microsoft introduced these interfaces. diff --git a/com/win32com/demos/iebutton.py b/com/win32com/demos/iebutton.py index 4b1890f9dc..0886b6ed47 100644 --- a/com/win32com/demos/iebutton.py +++ b/com/win32com/demos/iebutton.py @@ -24,17 +24,15 @@ Contribtions to this sample to make it a little "friendlier" welcome! """ -import os - +# imports section +import sys, os +from win32com import universal +from win32com.client import gencache, DispatchWithEvents, Dispatch +from win32com.client import constants, getevents +import win32com.server.register +import win32com import pythoncom import win32api -import win32com -import win32com.server.register -from win32com import universal -from win32com.client import Dispatch, DispatchWithEvents, constants, gencache, getevents - -# imports section - # This demo uses 'print' - use win32traceutil to see it if we have no # console. @@ -43,11 +41,10 @@ except win32api.error: import win32traceutil -import array -import struct - from win32com.axcontrol import axcontrol +import array, struct + # ensure we know the ms internet controls typelib so we have access to IWebBrowser2 later on win32com.client.gencache.EnsureModule("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1) diff --git a/com/win32com/demos/ietoolbar.py b/com/win32com/demos/ietoolbar.py index 309fa1a6b5..54a3acfa6a 100644 --- a/com/win32com/demos/ietoolbar.py +++ b/com/win32com/demos/ietoolbar.py @@ -15,19 +15,18 @@ to catch WM_COMMAND messages. """ -import os - # imports section -import sys +import sys, os +from win32com import universal +from win32com.client import gencache, DispatchWithEvents, Dispatch +from win32com.client import constants, getevents +import win32com +import pythoncom import winreg -import pythoncom -import win32com -from win32com import universal -from win32com.axcontrol import axcontrol -from win32com.client import Dispatch, DispatchWithEvents, constants, gencache, getevents from win32com.shell import shell from win32com.shell.shellcon import * +from win32com.axcontrol import axcontrol try: # try to get styles (winxp) @@ -35,13 +34,11 @@ except: # import default module (win2k and lower) import win32gui - -import array -import struct - -import commctrl -import win32con import win32ui +import win32con +import commctrl + +import array, struct # ensure we know the ms internet controls typelib so we have access to IWebBrowser2 later on win32com.client.gencache.EnsureModule("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1) diff --git a/com/win32com/makegw/makegw.py b/com/win32com/makegw/makegw.py index 6074900d5f..ebc8f858c6 100644 --- a/com/win32com/makegw/makegw.py +++ b/com/win32com/makegw/makegw.py @@ -47,7 +47,6 @@ """ import re - from . import makegwparse diff --git a/com/win32com/server/dispatcher.py b/com/win32com/server/dispatcher.py index 1abe9cd88b..06932344bf 100644 --- a/com/win32com/server/dispatcher.py +++ b/com/win32com/server/dispatcher.py @@ -2,16 +2,12 @@ Please see policy.py for a discussion on dispatchers and policies """ -import traceback +import pythoncom, traceback, win32api from sys import exc_info -import pythoncom -import win32api -import win32com - -# from win32com.server.exception import IsCOMServerException from win32com.util import IIDToInterfaceName +import win32com class DispatcherBase: diff --git a/com/win32com/server/register.py b/com/win32com/server/register.py index 476cc98798..746e191104 100644 --- a/com/win32com/server/register.py +++ b/com/win32com/server/register.py @@ -6,13 +6,12 @@ construct the necessary Python object, and dispatch COM events. """ -import os import sys - -import pythoncom import win32api import win32con +import pythoncom import winerror +import os CATID_PythonCOMServer = "{B3EF80D0-68E2-11D0-A689-00C04FD658FF}" @@ -535,13 +534,11 @@ def UnregisterInfoClasses(*classes, **flags): # Attempt to 're-execute' our current process with elevation. def ReExecuteElevated(flags): - import tempfile - - import win32event - import win32process - import winxpgui # we've already checked we are running XP above - from win32com.shell import shellcon from win32com.shell.shell import ShellExecuteEx + from win32com.shell import shellcon + import win32process, win32event + import winxpgui # we've already checked we are running XP above + import tempfile if not flags["quiet"]: print("Requesting elevation and retrying...") diff --git a/com/win32com/test/testPersist.py b/com/win32com/test/testPersist.py index d37e8a5d1d..03f361c615 100644 --- a/com/win32com/test/testPersist.py +++ b/com/win32com/test/testPersist.py @@ -1,27 +1,25 @@ -import os -import string +import pythoncom +import win32com.server.util import time -import traceback -import pythoncom -import pywintypes -import win32api -import win32com -import win32com.client +import win32com, sys, string, win32api, traceback import win32com.client.dynamic -import win32com.server.util -import win32ui +import win32com.client +import pythoncom +from win32com.axcontrol import axcontrol from pywintypes import Unicode from win32com import storagecon -from win32com.axcontrol import axcontrol from win32com.test.util import CheckClean -S_OK = 0 +import pywintypes +import win32ui +import win32api, os import datetime - import win32timezone +S_OK = 0 + now = win32timezone.now() diff --git a/com/win32com/test/testPippo.py b/com/win32com/test/testPippo.py index 414483b53e..2cd5a05c91 100644 --- a/com/win32com/test/testPippo.py +++ b/com/win32com/test/testPippo.py @@ -1,6 +1,5 @@ import sys import unittest - import pythoncom from win32com.client import Dispatch from win32com.client.gencache import EnsureDispatch @@ -8,8 +7,8 @@ class PippoTester(unittest.TestCase): def setUp(self): - from win32com.test import pippo_server from win32com.test.util import RegisterPythonServer + from win32com.test import pippo_server RegisterPythonServer(pippo_server.__file__, "Python.Test.Pippo") # create it. diff --git a/com/win32com/test/testPyComTest.py b/com/win32com/test/testPyComTest.py index 0e93f14366..96c8c0b6be 100644 --- a/com/win32com/test/testPyComTest.py +++ b/com/win32com/test/testPyComTest.py @@ -4,20 +4,18 @@ import sys sys.coinit_flags = 0 # Must be free-threaded! -import datetime -import decimal -import os -import time - -import pythoncom +import win32api, pythoncom, time import pywintypes -import win32api +import os +import winerror import win32com import win32com.client.connect +from win32com.test.util import CheckClean +from win32com.client import constants, DispatchBaseClass, CastTo, VARIANT +from win32com.test.util import RegisterPythonServer +import datetime +import decimal import win32timezone -import winerror -from win32com.client import VARIANT, CastTo, DispatchBaseClass, constants -from win32com.test.util import CheckClean, 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++" diff --git a/com/win32com/test/testShell.py b/com/win32com/test/testShell.py index 48937c523b..928af61835 100644 --- a/com/win32com/test/testShell.py +++ b/com/win32com/test/testShell.py @@ -1,19 +1,19 @@ -import copy -import datetime -import os +import sys, os import struct -import sys import unittest +import copy +import datetime +import win32timezone +import win32con import pythoncom import pywintypes -import win32com.test.util -import win32con -import win32timezone from win32com.shell import shell from win32com.shell.shellcon import * from win32com.storagecon import * +import win32com.test.util + class ShellTester(win32com.test.util.TestCase): def testShellLink(self): diff --git a/com/win32com/test/testStreams.py b/com/win32com/test/testStreams.py index b43da524f3..8c6196f8ed 100644 --- a/com/win32com/test/testStreams.py +++ b/com/win32com/test/testStreams.py @@ -1,9 +1,9 @@ -import unittest - import pythoncom import win32com.server.util import win32com.test.util +import unittest + class Persists: _public_methods_ = [ diff --git a/com/win32com/test/testall.py b/com/win32com/test/testall.py index 3538a45bd6..d4b339989e 100644 --- a/com/win32com/test/testall.py +++ b/com/win32com/test/testall.py @@ -1,10 +1,5 @@ -import getopt -import os -import re -import string -import sys -import traceback -import unittest +import sys, os, string, re +import getopt, traceback, unittest try: this_file = __file__ @@ -25,13 +20,13 @@ import pythoncom import win32com.client from win32com.test.util import ( - CapturingFunctionTestCase, CheckClean, - RegisterPythonServer, - ShellTestCase, TestCase, + CapturingFunctionTestCase, + ShellTestCase, TestLoader, TestRunner, + RegisterPythonServer, ) verbosity = 1 # default unittest verbosity. @@ -48,9 +43,7 @@ def GenerateAndRunOldStyle(): def CleanGenerated(): - import shutil - - import win32com + import win32com, shutil if os.path.isdir(win32com.__gen_path__): if verbosity > 1: diff --git a/com/win32com/test/testvb.py b/com/win32com/test/testvb.py index e88f06fe0a..3c9ed0402f 100644 --- a/com/win32com/test/testvb.py +++ b/com/win32com/test/testvb.py @@ -3,16 +3,14 @@ # This requires the PythonCOM VB Test Harness. # -import traceback - -import pythoncom -import win32com.client -import win32com.client.dynamic -import win32com.client.gencache +import sys import winerror +import pythoncom, win32com.client, win32com.client.dynamic, win32com.client.gencache from win32com.server.util import NewCollection, wrap from win32com.test import util +import traceback + # for debugging useDispatcher = None ## import win32com.server.dispatcher diff --git a/com/win32com/test/testvbscript_regexp.py b/com/win32com/test/testvbscript_regexp.py index a6c09ae8a7..9fe4f5536b 100644 --- a/com/win32com/test/testvbscript_regexp.py +++ b/com/win32com/test/testvbscript_regexp.py @@ -1,8 +1,7 @@ import unittest - -import win32com.test.util -from win32com.client.dynamic import DumbDispatch from win32com.client.gencache import EnsureDispatch +from win32com.client.dynamic import DumbDispatch +import win32com.test.util class RegexTest(win32com.test.util.TestCase): diff --git a/com/win32com/test/util.py b/com/win32com/test/util.py index ce071202b5..cbd3ec12bd 100644 --- a/com/win32com/test/util.py +++ b/com/win32com/test/util.py @@ -1,20 +1,19 @@ -import gc -import io as StringIO -import logging -import os -import sys +import sys, os +import win32api import tempfile import unittest +import gc +import pywintypes +import pythoncom +import winerror +from pythoncom import _GetInterfaceCount, _GetGatewayCount +import win32com +import logging import winreg +import io as StringIO -import pythoncom import pywin32_testutil -import pywintypes -import win32api -import win32com -import winerror -from pythoncom import _GetGatewayCount, _GetInterfaceCount -from pywin32_testutil import LeakTestCase, TestLoader, TestResult, TestRunner +from pywin32_testutil import TestLoader, TestResult, TestRunner, LeakTestCase def CheckClean(): diff --git a/com/win32comext/axscript/client/debug.py b/com/win32comext/axscript/client/debug.py index 7a5aa2e074..338cbb8f91 100644 --- a/com/win32comext/axscript/client/debug.py +++ b/com/win32comext/axscript/client/debug.py @@ -1,19 +1,17 @@ -import os -import string -import sys -import traceback +import traceback, sys, string -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.codecontainer import SourceCodeContainer -from win32com.axdebug.util import _wrap, _wrap_remove +from win32com.util import IIDToInterfaceName from win32com.client.util import Enumerator from win32com.server.exception import COMException -from win32com.util import IIDToInterfaceName +import pythoncom +from .framework import trace +from win32com.axdebug import axdebug, gateways, contexts, stackframe, documents, adb +from win32com.axdebug.codecontainer import SourceCodeContainer +from win32com.axdebug.util import _wrap, _wrap_remove +import win32com.client.connect +import win32api, winerror +import os try: os.environ["DEBUG_AXDEBUG"] diff --git a/com/win32comext/axscript/client/error.py b/com/win32comext/axscript/client/error.py index 95b333bc0c..559f6960ff 100644 --- a/com/win32comext/axscript/client/error.py +++ b/com/win32comext/axscript/client/error.py @@ -5,14 +5,13 @@ """ -import re -import traceback - -import pythoncom +import sys, traceback +from win32com.axscript import axscript +import winerror import win32com.server.exception import win32com.server.util -import winerror -from win32com.axscript import axscript +import pythoncom +import re debugging = 0 diff --git a/com/win32comext/axscript/client/framework.py b/com/win32comext/axscript/client/framework.py index a90fda649b..d4ad954e40 100644 --- a/com/win32comext/axscript/client/framework.py +++ b/com/win32comext/axscript/client/framework.py @@ -6,16 +6,16 @@ There are classes defined for the engine itself, and for ScriptItems """ -import re import sys -import types +from win32com.axscript import axscript +import win32com.server.util -import pythoncom -import win32api import win32com.client.connect # Need simple connection point support -import win32com.server.util -import winerror -from win32com.axscript import axscript + +import win32api, winerror +import pythoncom +import types +import re def RemoveCR(text): @@ -30,7 +30,6 @@ def RemoveCR(text): SCRIPTTEXT_ISPERSISTENT = 0x00000040 from win32com.server.exception import Exception, IsCOMServerException - from . import error # ax.client.error state_map = { @@ -726,7 +725,6 @@ def SetScriptSite(self, site): try: import win32com.axdebug.axdebug # see if the core exists. - from . import debug self.debugManager = debug.DebugManager(self) diff --git a/com/win32comext/axscript/client/pyscript.py b/com/win32comext/axscript/client/pyscript.py index 20f47bbf0b..d6ccc64b09 100644 --- a/com/win32comext/axscript/client/pyscript.py +++ b/com/win32comext/axscript/client/pyscript.py @@ -7,24 +7,25 @@ command line. """ -import re -import traceback - -import pythoncom -import win32api +import winerror import win32com +import win32api +import pythoncom +import sys +import traceback +import re import win32com.client.dynamic -import win32com.server.register -import winerror -from win32com.axscript import axscript from win32com.axscript.client import framework, scriptdispatch +from win32com.axscript import axscript +import win32com.server.register + from win32com.axscript.client.framework import ( + RaiseAssert, + trace, + Exception, SCRIPTTEXT_FORCEEXECUTION, SCRIPTTEXT_ISEXPRESSION, SCRIPTTEXT_ISPERSISTENT, - Exception, - RaiseAssert, - trace, ) PyScript_CLSID = "{DF630910-1C1D-11d0-AE36-8C0F5E000000}" @@ -433,6 +434,8 @@ def DllRegisterServer(): def Register(klass=PyScript): + import sys + ret = win32com.server.register.UseCommandLine( klass, finalize_register=DllRegisterServer ) diff --git a/com/win32comext/axscript/test/leakTest.py b/com/win32comext/axscript/test/leakTest.py index 5022ab1a89..02c2e3c690 100644 --- a/com/win32comext/axscript/test/leakTest.py +++ b/com/win32comext/axscript/test/leakTest.py @@ -1,11 +1,10 @@ import sys - -import pythoncom -import win32com.server.policy +from win32com.axscript.server.error import Exception from win32com.axscript import axscript from win32com.axscript.server import axsite -from win32com.axscript.server.error import Exception -from win32com.server import connect, util +import pythoncom +from win32com.server import util, connect +import win32com.server.policy class MySite(axsite.AXSite): diff --git a/com/win32comext/axscript/test/testHost.py b/com/win32comext/axscript/test/testHost.py index d3e6bb5f66..c7e04f1727 100644 --- a/com/win32comext/axscript/test/testHost.py +++ b/com/win32comext/axscript/test/testHost.py @@ -1,16 +1,16 @@ import sys -import unittest - import pythoncom -import win32com.server.policy -import win32com.test.util +from win32com.axscript.server.error import Exception from win32com.axscript import axscript from win32com.axscript.server import axsite -from win32com.axscript.server.error import Exception +from win32com.server import util, connect +import win32com.server.policy from win32com.client.dynamic import Dispatch -from win32com.server import connect, util from win32com.server.exception import COMException +import unittest +import win32com.test.util + verbose = "-v" in sys.argv diff --git a/com/win32comext/mapi/mapiutil.py b/com/win32comext/mapi/mapiutil.py index 39f35729bd..f93a411f65 100644 --- a/com/win32comext/mapi/mapiutil.py +++ b/com/win32comext/mapi/mapiutil.py @@ -1,7 +1,6 @@ # General utilities for MAPI and MAPI objects. -import pythoncom from pywintypes import TimeType - +import pythoncom from . import mapi, mapitags prTable = {} diff --git a/com/win32comext/shell/demos/ITransferAdviseSink.py b/com/win32comext/shell/demos/ITransferAdviseSink.py index fc766fb0b2..0fa8c54d98 100644 --- a/com/win32comext/shell/demos/ITransferAdviseSink.py +++ b/com/win32comext/shell/demos/ITransferAdviseSink.py @@ -1,8 +1,8 @@ # ITransferAdviseSink implementation template import pythoncom -from win32com.server.policy import DesignatedWrapPolicy from win32com.shell import shell, shellcon +from win32com.server.policy import DesignatedWrapPolicy tsf_flags = list( (k, v) for k, v in list(shellcon.__dict__.items()) if k.startswith("TSF_") diff --git a/com/win32comext/shell/demos/servers/copy_hook.py b/com/win32comext/shell/demos/servers/copy_hook.py index d46a7d59ca..889780ecb6 100644 --- a/com/win32comext/shell/demos/servers/copy_hook.py +++ b/com/win32comext/shell/demos/servers/copy_hook.py @@ -12,7 +12,6 @@ import win32con import winerror - # Our shell extension. class ShellExtension: _reg_progid_ = "Python.ShellExtension.CopyHook" diff --git a/isapi/samples/redirector.py b/isapi/samples/redirector.py index bab44f877a..fd58f244ba 100644 --- a/isapi/samples/redirector.py +++ b/isapi/samples/redirector.py @@ -16,13 +16,13 @@ # an example. If this sample is run on IIS5 or earlier it simply ignores # any excludes. +from isapi import isapicon, threaded_extension import sys import traceback -from urllib.request import urlopen +from urllib.request import urlopen import win32api -from isapi import isapicon, threaded_extension # sys.isapidllhandle will exist when we are loaded by the IIS framework. # In this case we redirect our output to the win32traceutil collector. diff --git a/setup.py b/setup.py index e26335da93..64a6b64ac9 100644 --- a/setup.py +++ b/setup.py @@ -22,36 +22,38 @@ build_env.md, which is getting out of date but might help getting everything required for an official build - see README.md for that process. """ -import glob - # Originally by Thomas Heller, started in 2000 or so. import os -import platform +import sys +import glob import re +from tempfile import gettempdir +import platform import shutil import subprocess -import sys + import winreg -from distutils import log -from distutils.command.build import build -from distutils.command.install import install -from distutils.command.install_data import install_data -from distutils.command.install_lib import install_lib -from distutils.core import Extension -from tempfile import gettempdir # The rest of our imports. from setuptools import setup +from distutils.core import Extension +from distutils.command.install import install +from distutils.command.install_lib import install_lib from setuptools.command.build_ext import build_ext +from distutils.command.build import build +from distutils.command.install_data import install_data + +from distutils import log + # some modules need a static CRT to avoid problems caused by them having a # manifest. static_crt_modules = ["winxpgui"] -import distutils.util from distutils.dep_util import newer_group from distutils.filelist import FileList +import distutils.util build_id_patch = build_id if not "." in build_id_patch: diff --git a/win32/Demos/BackupRead_BackupWrite.py b/win32/Demos/BackupRead_BackupWrite.py index 86aebcc34f..b3a3821a40 100644 --- a/win32/Demos/BackupRead_BackupWrite.py +++ b/win32/Demos/BackupRead_BackupWrite.py @@ -1,16 +1,9 @@ ## demonstrates using BackupRead and BackupWrite to copy all of a file's data streams -import struct -import traceback - -import ntsecuritycon -import pythoncom -import pywintypes -import win32api -import win32con -import win32file -import win32security +import win32file, win32api, win32con, win32security, ntsecuritycon from win32com import storagecon +import pythoncom, pywintypes +import struct, traceback all_sd_info = ( win32security.DACL_SECURITY_INFORMATION diff --git a/win32/Demos/CreateFileTransacted_MiniVersion.py b/win32/Demos/CreateFileTransacted_MiniVersion.py index 6ad5868a23..cf4e8bdfec 100644 --- a/win32/Demos/CreateFileTransacted_MiniVersion.py +++ b/win32/Demos/CreateFileTransacted_MiniVersion.py @@ -4,15 +4,10 @@ miniversion (effectively a savepoint within a transaction). """ -import os +import win32file, win32api, win32transaction, winerror +import win32con, winioctlcon import struct - -import win32api -import win32con -import win32file -import win32transaction -import winerror -import winioctlcon +import os def demo(): diff --git a/win32/Demos/OpenEncryptedFileRaw.py b/win32/Demos/OpenEncryptedFileRaw.py index c9e2d54d87..0bdb6988ad 100644 --- a/win32/Demos/OpenEncryptedFileRaw.py +++ b/win32/Demos/OpenEncryptedFileRaw.py @@ -1,9 +1,6 @@ +import win32file, win32api, winerror import os -import win32api -import win32file -import winerror - def ReadCallback(input_buffer, data, buflen): fnamein, fnameout, f = data diff --git a/win32/Demos/eventLogDemo.py b/win32/Demos/eventLogDemo.py index 28c4f424a6..49c69342f2 100644 --- a/win32/Demos/eventLogDemo.py +++ b/win32/Demos/eventLogDemo.py @@ -1,9 +1,10 @@ +import win32evtlog import win32api import win32con -import win32evtlog -import win32evtlogutil import win32security # To translate NT Sids to account names. +import win32evtlogutil + def ReadLog(computer, logType="Application", dumpEachRecord=0): # read the entire log back. @@ -76,8 +77,7 @@ def test(): print("This sample only runs on NT") return - import getopt - import sys + import sys, getopt opts, args = getopt.getopt(sys.argv[1:], "rwh?c:t:v") computer = None diff --git a/win32/Demos/mmapfile_demo.py b/win32/Demos/mmapfile_demo.py index ff3ac8f136..381ba043ca 100644 --- a/win32/Demos/mmapfile_demo.py +++ b/win32/Demos/mmapfile_demo.py @@ -1,9 +1,6 @@ -import os -import tempfile - -import mmapfile -import win32api +import win32api, mmapfile import winerror +import tempfile, os system_info = win32api.GetSystemInfo() page_size = system_info[1] diff --git a/win32/Demos/security/sspi/socket_server.py b/win32/Demos/security/sspi/socket_server.py index 5ca44729ec..468f09fd98 100644 --- a/win32/Demos/security/sspi/socket_server.py +++ b/win32/Demos/security/sspi/socket_server.py @@ -19,16 +19,18 @@ See the SSPI documentation for more details. """ -import http.client -import optparse # sorry, this demo needs 2.3+ -import socketserver + +import sys import struct +import socketserver +import win32api +import http.client import traceback -import sspi -import sspicon -import win32api import win32security +import sspi, sspicon + +import optparse # sorry, this demo needs 2.3+ options = None # set to optparse object. diff --git a/win32/Demos/service/pipeTestServiceClient.py b/win32/Demos/service/pipeTestServiceClient.py index b4e7948cc7..7d6295faf8 100644 --- a/win32/Demos/service/pipeTestServiceClient.py +++ b/win32/Demos/service/pipeTestServiceClient.py @@ -6,15 +6,13 @@ # Eg: pipeTestServiceClient.py -s server_name Hi There # Should work. -import os -import traceback - +from win32pipe import * +from win32file import * +from win32event import * import pywintypes import win32api import winerror -from win32event import * -from win32file import * -from win32pipe import * +import sys, os, traceback verbose = 0 @@ -109,8 +107,7 @@ def stressTestClient(server, numThreads, numMessages): def main(): - import getopt - import sys + import sys, getopt server = "." thread_count = 0 diff --git a/win32/Demos/win32clipboardDemo.py b/win32/Demos/win32clipboardDemo.py index ba7f88795c..90cc3897f4 100644 --- a/win32/Demos/win32clipboardDemo.py +++ b/win32/Demos/win32clipboardDemo.py @@ -1,8 +1,9 @@ # win32clipboardDemo.py # # Demo/test of the win32clipboard module. -import win32con from win32clipboard import * +import win32con +import types if not __debug__: print("WARNING: The test code in this module uses assert") diff --git a/win32/Demos/win32fileDemo.py b/win32/Demos/win32fileDemo.py index 4467d02fea..8ff714cebb 100644 --- a/win32/Demos/win32fileDemo.py +++ b/win32/Demos/win32fileDemo.py @@ -1,14 +1,9 @@ # This is a "demo" of win32file - it used to be more a test case than a # demo, so has been moved to the test directory. -import os - -import win32api -import win32con - # Please contribute your favourite simple little demo. -import win32file - +import win32file, win32api, win32con +import os # A very simple demo - note that this does no more than you can do with # builtin Python file objects, so for something as simple as this, you diff --git a/win32/Demos/win32gui_dialog.py b/win32/Demos/win32gui_dialog.py index c4086563b5..3c89f481cc 100644 --- a/win32/Demos/win32gui_dialog.py +++ b/win32/Demos/win32gui_dialog.py @@ -20,17 +20,13 @@ import win32gui else: import winxpgui as win32gui - -import array -import os -import queue -import struct - -import commctrl -import win32api -import win32con import win32gui_struct -import winerror +import win32api +import win32con, winerror +import struct, array +import commctrl +import queue +import os IDC_SEARCHTEXT = 1024 IDC_BUTTON_SEARCH = 1025 diff --git a/win32/Demos/win32gui_menu.py b/win32/Demos/win32gui_menu.py index 38c4827eb4..a97be4fcf1 100644 --- a/win32/Demos/win32gui_menu.py +++ b/win32/Demos/win32gui_menu.py @@ -15,14 +15,11 @@ from winxpgui import * except ImportError: from win32gui import * - -import array -import os -import struct -import sys - -import win32con from win32gui_struct import * +import win32con +import sys, os +import struct +import array this_dir = os.path.split(sys.argv[0])[0] diff --git a/win32/Demos/win32gui_taskbar.py b/win32/Demos/win32gui_taskbar.py index eca439baa1..c9071bd205 100644 --- a/win32/Demos/win32gui_taskbar.py +++ b/win32/Demos/win32gui_taskbar.py @@ -1,12 +1,8 @@ # Creates a task-bar icon. Run from Python.exe to see the # messages printed. -import os -import sys - -import win32api -import win32con -import win32gui -import winerror +import win32api, win32gui +import win32con, winerror +import sys, os class MainWindow: diff --git a/win32/Lib/netbios.py b/win32/Lib/netbios.py index 3f80b6b62c..4eeec552fb 100644 --- a/win32/Lib/netbios.py +++ b/win32/Lib/netbios.py @@ -1,6 +1,6 @@ -import struct - +import sys import win32wnet +import struct # Constants generated by h2py from nb30.h NCBNAMSZ = 16 diff --git a/win32/Lib/pywin32_testutil.py b/win32/Lib/pywin32_testutil.py index 7ccfcb0203..d5d2bf4bee 100644 --- a/win32/Lib/pywin32_testutil.py +++ b/win32/Lib/pywin32_testutil.py @@ -1,10 +1,9 @@ # Utilities for the pywin32 tests -import gc -import os import site import sys +import os import unittest - +import gc import winerror ## @@ -38,7 +37,7 @@ def countTestCases(self): def __call__(self, result=None): # For the COM suite's sake, always ensure we don't leak # gateways/interfaces - from pythoncom import _GetGatewayCount, _GetInterfaceCount + from pythoncom import _GetInterfaceCount, _GetGatewayCount gc.collect() ni = _GetInterfaceCount() @@ -154,8 +153,8 @@ def loadTestsFromName(self, name, module=None): def check_is_admin(): global _is_admin if _is_admin is None: - import pythoncom from win32com.shell.shell import IsUserAnAdmin + import pythoncom try: _is_admin = IsUserAnAdmin() diff --git a/win32/Lib/pywintypes.py b/win32/Lib/pywintypes.py index 631e7db884..fd3ebe2cff 100644 --- a/win32/Lib/pywintypes.py +++ b/win32/Lib/pywintypes.py @@ -1,8 +1,5 @@ # Magic utility that "redirects" to pywintypesxx.dll -import importlib.machinery -import importlib.util -import os -import sys +import importlib.util, importlib.machinery, sys, os def __import_pywin32_system_module__(modname, globs): diff --git a/win32/Lib/sspi.py b/win32/Lib/sspi.py index f8995eff26..fd6ad67c16 100644 --- a/win32/Lib/sspi.py +++ b/win32/Lib/sspi.py @@ -11,11 +11,9 @@ If you need finer control than offered here, just use the win32security functions directly. """ -import sspicon - # Based on Roger Upole's sspi demos. # $Id$ -import win32security +import win32security, sspicon error = win32security.error diff --git a/win32/Lib/win32gui_struct.py b/win32/Lib/win32gui_struct.py index 33672d8932..5aca22cb06 100644 --- a/win32/Lib/win32gui_struct.py +++ b/win32/Lib/win32gui_struct.py @@ -27,15 +27,14 @@ # win32gui (ie, the Pack* functions) - but doesn't make as much sense for # the Unpack* functions, where the aim is user convenience. -import array -import struct import sys -from collections import namedtuple - +import win32gui +import win32con +import struct +import array import commctrl import pywintypes -import win32con -import win32gui +from collections import namedtuple is64bit = "64 bit" in sys.version diff --git a/win32/Lib/win32timezone.py b/win32/Lib/win32timezone.py index d3b50e3368..5475dd48ca 100644 --- a/win32/Lib/win32timezone.py +++ b/win32/Lib/win32timezone.py @@ -233,15 +233,15 @@ """ __author__ = "Jason R. Coombs " +import winreg +import struct import datetime -import logging -import operator +import win32api import re -import struct -import winreg +import operator from itertools import count -import win32api +import logging log = logging.getLogger(__file__) diff --git a/win32/Lib/win32verstamp.py b/win32/Lib/win32verstamp.py index 110c2be1c4..57c7d74b4a 100644 --- a/win32/Lib/win32verstamp.py +++ b/win32/Lib/win32verstamp.py @@ -1,12 +1,14 @@ """ Stamp a Win32 binary with version information. """ -import glob -import optparse +from win32api import BeginUpdateResource, UpdateResource, EndUpdateResource + import os import struct +import glob +import sys -from win32api import BeginUpdateResource, EndUpdateResource, UpdateResource +import optparse VS_FFI_SIGNATURE = -17890115 # 0xFEEF04BD VS_FFI_STRUCVERSION = 0x00010000 diff --git a/win32/test/handles.py b/win32/test/handles.py index 5f8b00d9e1..76fa2e3860 100644 --- a/win32/test/handles.py +++ b/win32/test/handles.py @@ -1,10 +1,8 @@ import sys import unittest - import pywintypes import win32api - # A class that will never die vie refcounting, but will die via GC. class Cycle: def __init__(self, handle): diff --git a/win32/test/test_clipboard.py b/win32/test/test_clipboard.py index 8f74e8575e..61752104a5 100644 --- a/win32/test/test_clipboard.py +++ b/win32/test/test_clipboard.py @@ -1,13 +1,11 @@ # General test module for win32api - please add some :) -import array -import os -import sys +import sys, os import unittest -import pywintypes -import win32con -import win32gui from win32clipboard import * +import win32gui, win32con +import pywintypes +import array custom_format_name = "PythonClipboardTestFormat" diff --git a/win32/test/test_exceptions.py b/win32/test/test_exceptions.py index 2944da364c..74838597af 100644 --- a/win32/test/test_exceptions.py +++ b/win32/test/test_exceptions.py @@ -1,10 +1,8 @@ """Test pywin32's error semantics""" +import sys import unittest - +import win32api, win32file, pywintypes import pythoncom -import pywintypes -import win32api -import win32file import winerror diff --git a/win32/test/test_odbc.py b/win32/test/test_odbc.py index 8cba6310f3..b104ad230b 100644 --- a/win32/test/test_odbc.py +++ b/win32/test/test_odbc.py @@ -1,16 +1,16 @@ # odbc test suite kindly contributed by Frank Millman. -import os import sys -import tempfile +import os import unittest - import odbc -import pythoncom +import tempfile + from pywin32_testutil import TestSkipped -from win32com.client import constants # We use the DAO ODBC driver from win32com.client.gencache import EnsureDispatch +from win32com.client import constants +import pythoncom class TestStuff(unittest.TestCase): diff --git a/win32/test/test_pywintypes.py b/win32/test/test_pywintypes.py index 101019e2ed..799d9193a5 100644 --- a/win32/test/test_pywintypes.py +++ b/win32/test/test_pywintypes.py @@ -1,9 +1,9 @@ -import datetime -import operator -import time +import sys import unittest - import pywintypes +import time +import datetime +import operator class TestCase(unittest.TestCase): diff --git a/win32/test/test_security.py b/win32/test/test_security.py index 3cc8f64a07..9f29cfd806 100644 --- a/win32/test/test_security.py +++ b/win32/test/test_security.py @@ -1,14 +1,10 @@ # Tests for the win32security module. -import os +import sys, os import unittest - -import ntsecuritycon -import pywintypes -import win32api -import win32con -import win32security import winerror -from pywin32_testutil import TestSkipped, testmain +from pywin32_testutil import testmain, TestSkipped + +import win32api, win32con, win32security, ntsecuritycon, pywintypes class SecurityTests(unittest.TestCase): diff --git a/win32/test/test_sspi.py b/win32/test/test_sspi.py index 7010cdfe32..6f47496f7f 100644 --- a/win32/test/test_sspi.py +++ b/win32/test/test_sspi.py @@ -2,14 +2,9 @@ # Stolen from Roger's original test_sspi.c, a version of which is in "Demos" # See also the other SSPI demos. import re -import unittest - -import sspi -import sspicon -import win32api -import win32security +import win32security, sspi, sspicon, win32api from pywin32_testutil import TestSkipped, testmain - +import unittest # It is quite likely that the Kerberos tests will fail due to not being # installed. The NTLM tests do *not* get the same behaviour as they should diff --git a/win32/test/test_win32api.py b/win32/test/test_win32api.py index 7570a958b2..e20ef328fd 100644 --- a/win32/test/test_win32api.py +++ b/win32/test/test_win32api.py @@ -1,17 +1,13 @@ # General test module for win32api - please add some :) -import datetime -import os -import sys -import tempfile import unittest - -import win32api -import win32con -import win32event -import winerror from pywin32_testutil import TestSkipped +import win32api, win32con, win32event, winerror +import sys, os +import tempfile +import datetime + class CurrentUserTestCase(unittest.TestCase): def testGetCurrentUser(self): diff --git a/win32/test/test_win32file.py b/win32/test/test_win32file.py index 3784bfed14..3e692e58f2 100644 --- a/win32/test/test_win32file.py +++ b/win32/test/test_win32file.py @@ -1,23 +1,17 @@ -import datetime +import unittest +from pywin32_testutil import TestSkipped, testmain +import win32api, win32file, win32pipe, pywintypes, winerror, win32event +import win32con, ntsecuritycon +import sys import os -import random -import shutil -import socket import tempfile import threading import time -import unittest - -import ntsecuritycon -import pywintypes -import win32api -import win32con -import win32event -import win32file -import win32pipe +import shutil +import socket +import datetime +import random import win32timezone -import winerror -from pywin32_testutil import TestSkipped, testmain try: set diff --git a/win32/test/test_win32inet.py b/win32/test/test_win32inet.py index d2d30c5252..59f1036349 100644 --- a/win32/test/test_win32inet.py +++ b/win32/test/test_win32inet.py @@ -1,9 +1,10 @@ -import unittest - -import winerror -from pywin32_testutil import TestSkipped, testmain from win32inet import * from win32inetcon import * +import winerror +from pywin32_testutil import TestSkipped +from pywin32_testutil import testmain + +import unittest class CookieTests(unittest.TestCase): diff --git a/win32/test/test_win32pipe.py b/win32/test/test_win32pipe.py index 00a474caba..99a89f70e5 100644 --- a/win32/test/test_win32pipe.py +++ b/win32/test/test_win32pipe.py @@ -1,13 +1,13 @@ -import threading -import time import unittest +import time +import threading -import pywintypes -import win32con -import win32event -import win32file import win32pipe +import win32file +import win32event +import pywintypes import winerror +import win32con class PipeTests(unittest.TestCase): diff --git a/win32/test/test_win32timezone.py b/win32/test/test_win32timezone.py index 4f77d437bb..3f91a5f18a 100644 --- a/win32/test/test_win32timezone.py +++ b/win32/test/test_win32timezone.py @@ -1,9 +1,9 @@ # Test module for win32timezone -import doctest +import sys import unittest - import win32timezone +import doctest class Win32TimeZoneTest(unittest.TestCase): diff --git a/win32/test/test_win32trace.py b/win32/test/test_win32trace.py index 969457a8c1..58f62b8c34 100644 --- a/win32/test/test_win32trace.py +++ b/win32/test/test_win32trace.py @@ -1,10 +1,9 @@ -import os -import sys -import threading -import time import unittest - import win32trace +import threading +import time +import os +import sys from pywin32_testutil import TestSkipped if __name__ == "__main__": diff --git a/win32/test/test_win32wnet.py b/win32/test/test_win32wnet.py index eeb0146a61..a53b7bfc7e 100644 --- a/win32/test/test_win32wnet.py +++ b/win32/test/test_win32wnet.py @@ -1,8 +1,7 @@ import unittest - -import netbios -import win32api import win32wnet +import win32api +import netbios RESOURCE_CONNECTED = 0x00000001 RESOURCE_GLOBALNET = 0x00000002 diff --git a/win32/test/testall.py b/win32/test/testall.py index 85adf736e3..4fb9d0d465 100644 --- a/win32/test/testall.py +++ b/win32/test/testall.py @@ -1,9 +1,7 @@ -import os +import sys, os import re -import sys -import traceback import unittest - +import traceback import pywin32_testutil # A list of demos that depend on user-interface of *any* kind. Tests listed From 3e0dbf5e628917b0887b09cae7bdd56d578d8af6 Mon Sep 17 00:00:00 2001 From: Avasam Date: Sun, 19 Feb 2023 19:04:48 -0500 Subject: [PATCH 03/24] re-run `black .` --- adodbapi/adodbapi.py | 1 - 1 file changed, 1 deletion(-) diff --git a/adodbapi/adodbapi.py b/adodbapi/adodbapi.py index 6c89b7aecb..a598da2665 100644 --- a/adodbapi/adodbapi.py +++ b/adodbapi/adodbapi.py @@ -68,7 +68,6 @@ def getIndexedValue(obj, index): from collections.abc import Mapping - # ----------------- The .connect method ----------------- def make_COM_connecter(): try: From 9b7eb376ed781dbab4c54e4c3f71420cde711340 Mon Sep 17 00:00:00 2001 From: Avasam Date: Sun, 19 Feb 2023 19:13:45 -0500 Subject: [PATCH 04/24] manual formatting fixes --- adodbapi/apibase.py | 1 + adodbapi/remote.py | 1 + win32/Lib/win32gui_struct.py | 1 + win32/Lib/win32verstamp.py | 1 + 4 files changed, 4 insertions(+) diff --git a/adodbapi/apibase.py b/adodbapi/apibase.py index 6022d75ef2..07aad9a4e1 100644 --- a/adodbapi/apibase.py +++ b/adodbapi/apibase.py @@ -16,6 +16,7 @@ verbose = False # debugging flag + # ------- Error handlers ------ def standardErrorHandler(connection, cursor, errorclass, errorvalue): err = (errorclass, errorvalue) diff --git a/adodbapi/remote.py b/adodbapi/remote.py index 4a43a129b2..107d98a620 100644 --- a/adodbapi/remote.py +++ b/adodbapi/remote.py @@ -58,6 +58,7 @@ if verbose: print(version) + # ----------------------------------------------------------- # conversion functions mandated by PEP 249 def Binary(aString): diff --git a/win32/Lib/win32gui_struct.py b/win32/Lib/win32gui_struct.py index fb4548942b..bf003330fe 100644 --- a/win32/Lib/win32gui_struct.py +++ b/win32/Lib/win32gui_struct.py @@ -53,6 +53,7 @@ def _MakeResult(names_str, values): else: _nmhdr_align_padding = "" + # Encode a string suitable for passing in a win32gui related structure def _make_text_buffer(text): if not isinstance(text, str): diff --git a/win32/Lib/win32verstamp.py b/win32/Lib/win32verstamp.py index 129b55fde4..33c2aa8741 100644 --- a/win32/Lib/win32verstamp.py +++ b/win32/Lib/win32verstamp.py @@ -17,6 +17,7 @@ null_byte = b"\0" + # # Set VS_FF_PRERELEASE and DEBUG if Debug # From a4c5c68eed2c4e884aa410623feb0de22090eb25 Mon Sep 17 00:00:00 2001 From: Avasam Date: Mon, 17 Apr 2023 19:21:38 -0400 Subject: [PATCH 05/24] test --- Pythonwin/pywin/framework/scriptutils.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Pythonwin/pywin/framework/scriptutils.py b/Pythonwin/pywin/framework/scriptutils.py index e710f0fcd8..a6f40a27f2 100644 --- a/Pythonwin/pywin/framework/scriptutils.py +++ b/Pythonwin/pywin/framework/scriptutils.py @@ -28,9 +28,9 @@ "\n" ) -byte_cr = b"\r" -byte_lf = b"\n" -byte_crlf = b"\r\n" +byte_cr = "\r".encode("ascii") +byte_lf = "\n".encode("ascii") +byte_crlf = "\r\n".encode("ascii") # A dialog box for the "Run Script" command. From 0d96ceb6ee2eb8da2b0b084e485dc6849863f7c2 Mon Sep 17 00:00:00 2001 From: Avasam Date: Mon, 17 Apr 2023 19:50:49 -0400 Subject: [PATCH 06/24] Extract raw string changes --- Pythonwin/pywin/framework/editor/editor.py | 6 +++--- Pythonwin/pywin/framework/mdi_pychecker.py | 4 ++-- Pythonwin/pywin/framework/sgrepmdi.py | 2 +- Pythonwin/pywin/framework/toolmenu.py | 2 +- Pythonwin/pywin/idle/FormatParagraph.py | 2 +- Pythonwin/pywin/scintilla/document.py | 6 +++--- Pythonwin/pywin/scintilla/view.py | 4 ++-- Pythonwin/pywin/tools/browser.py | 2 +- com/win32com/makegw/makegw.py | 2 +- com/win32com/makegw/makegwparse.py | 2 +- com/win32com/test/testall.py | 2 +- com/win32com/test/testvbscript_regexp.py | 4 ++-- com/win32comext/axscript/client/error.py | 4 ++-- com/win32comext/axscript/client/framework.py | 2 +- com/win32comext/axscript/client/pyscript.py | 4 ++-- setup.py | 2 +- win32/test/test_sspi.py | 10 +++++----- win32/test/testall.py | 2 +- 18 files changed, 31 insertions(+), 31 deletions(-) diff --git a/Pythonwin/pywin/framework/editor/editor.py b/Pythonwin/pywin/framework/editor/editor.py index 40e4da021c..aa1f53857d 100644 --- a/Pythonwin/pywin/framework/editor/editor.py +++ b/Pythonwin/pywin/framework/editor/editor.py @@ -32,8 +32,8 @@ ) from pywin.mfc import afxres, dialog, docview -patImport = regex.symcomp(r"import \(.*\)") -patIndent = regex.compile(r"^\\([ \t]*[~ \t]\\)") +patImport = regex.symcomp("import \(.*\)") +patIndent = regex.compile("^\\([ \t]*[~ \t]\\)") ID_LOCATE_FILE = 0xE200 ID_GOTO_LINE = 0xE2001 @@ -131,7 +131,7 @@ def TranslateLoadedData(self, data): win32ui.SetStatusText( "Translating from Unix file format - please wait...", 1 ) - return re.sub(r"\r*\n", "\r\n", data) + return re.sub("\r*\n", "\r\n", data) else: return data diff --git a/Pythonwin/pywin/framework/mdi_pychecker.py b/Pythonwin/pywin/framework/mdi_pychecker.py index 5825550eb6..c89f33b9b9 100644 --- a/Pythonwin/pywin/framework/mdi_pychecker.py +++ b/Pythonwin/pywin/framework/mdi_pychecker.py @@ -146,7 +146,7 @@ def __radd__(self, other): # Group(1) is the filename, group(2) is the lineno. -# regexGrepResult=regex.compile(r"^\([a-zA-Z]:.*\)(\([0-9]+\))") +# regexGrepResult=regex.compile("^\\([a-zA-Z]:.*\\)(\\([0-9]+\\))") # regexGrep=re.compile(r"^([a-zA-Z]:[^(]*)\((\d+)\)") regexGrep = re.compile(r"^(..[^\(:]+)?[\(:](\d+)[\):]:?\s*(.*)") @@ -544,7 +544,7 @@ def OnAddComment(self, cmd, code): errtext = m.group(3) if start != end and line_start == line_end: errtext = self.GetSelText() - errtext = repr(re.escape(errtext).replace(r"\ ", " ")) + errtext = repr(re.escape(errtext).replace("\ ", " ")) view.ReplaceSel(addspecific and cmnt % locals() or cmnt) return 0 diff --git a/Pythonwin/pywin/framework/sgrepmdi.py b/Pythonwin/pywin/framework/sgrepmdi.py index 7bb54afb0d..b7d938bbb3 100644 --- a/Pythonwin/pywin/framework/sgrepmdi.py +++ b/Pythonwin/pywin/framework/sgrepmdi.py @@ -129,7 +129,7 @@ def __radd__(self, other): # Group(1) is the filename, group(2) is the lineno. -# regexGrepResult=regex.compile(r"^\([a-zA-Z]:.*\)(\([0-9]+\))") +# regexGrepResult=regex.compile("^\\([a-zA-Z]:.*\\)(\\([0-9]+\\))") regexGrep = re.compile(r"^([a-zA-Z]:[^(]*)\(([0-9]+)\)") diff --git a/Pythonwin/pywin/framework/toolmenu.py b/Pythonwin/pywin/framework/toolmenu.py index afe06b2b41..9e75c06be9 100644 --- a/Pythonwin/pywin/framework/toolmenu.py +++ b/Pythonwin/pywin/framework/toolmenu.py @@ -116,7 +116,7 @@ def HandleToolCommand(cmd, code): global tools (menuString, pyCmd, desc) = tools[cmd] win32ui.SetStatusText("Executing tool %s" % desc, 1) - pyCmd = re.sub(r"\\n", "\n", pyCmd) + pyCmd = re.sub("\\\\n", "\n", pyCmd) win32ui.DoWaitCursor(1) oldFlag = None try: diff --git a/Pythonwin/pywin/idle/FormatParagraph.py b/Pythonwin/pywin/idle/FormatParagraph.py index b3e74c532e..143c18ee32 100644 --- a/Pythonwin/pywin/idle/FormatParagraph.py +++ b/Pythonwin/pywin/idle/FormatParagraph.py @@ -133,7 +133,7 @@ def reformat_paragraph(data, limit=70): partial = indent1 while i < n and not is_all_white(lines[i]): # XXX Should take double space after period (etc.) into account - words = re.split(r"(\s+)", lines[i]) + words = re.split("(\s+)", lines[i]) for j in range(0, len(words), 2): word = words[j] if not word: diff --git a/Pythonwin/pywin/scintilla/document.py b/Pythonwin/pywin/scintilla/document.py index 7fb5e264a5..476eb8bcc6 100644 --- a/Pythonwin/pywin/scintilla/document.py +++ b/Pythonwin/pywin/scintilla/document.py @@ -13,8 +13,8 @@ lf_bytes = b"\n" # re from pep263 - but we use it both on bytes and strings. -re_encoding_bytes = re.compile(rb"coding[:=]\s*([-\w.]+)") -re_encoding_text = re.compile(r"coding[:=]\s*([-\w.]+)") +re_encoding_bytes = re.compile(b"coding[:=]\s*([-\w.]+)") +re_encoding_text = re.compile("coding[:=]\s*([-\w.]+)") ParentScintillaDocument = docview.Document @@ -168,7 +168,7 @@ def _SaveTextToFile(self, view, filename, encoding=None): source_encoding = self.source_encoding else: # no BOM - look for an encoding. - bits = re.split(r"[\r\n]+", s, 3) + bits = re.split("[\r\n]+", s, 3) for look in bits[:-1]: match = re_encoding_text.search(look) if match is not None: diff --git a/Pythonwin/pywin/scintilla/view.py b/Pythonwin/pywin/scintilla/view.py index 910161bad4..431c4afb1f 100644 --- a/Pythonwin/pywin/scintilla/view.py +++ b/Pythonwin/pywin/scintilla/view.py @@ -22,7 +22,7 @@ wordbreaks = "._" + string.ascii_uppercase + string.ascii_lowercase + string.digits -patImport = re.compile(r"import (?P.*)") +patImport = re.compile("import (?P.*)") _event_commands = [ # File menu @@ -533,7 +533,7 @@ def list2dict(l): endpos = self.LineIndex(maxline) text = self.GetTextRange(self.LineIndex(minline), endpos) try: - l = re.findall(r"\b" + left + r"\.\w+", text) + l = re.findall("\b" + left + "\.\w+", text) except re.error: # parens etc may make an invalid RE, but this code wouldnt # benefit even if the RE did work :-) diff --git a/Pythonwin/pywin/tools/browser.py b/Pythonwin/pywin/tools/browser.py index 3742582773..36bcb5ecaa 100644 --- a/Pythonwin/pywin/tools/browser.py +++ b/Pythonwin/pywin/tools/browser.py @@ -364,7 +364,7 @@ def OnInitDialog(self): t, v, tb = sys.exc_info() strval = "Exception getting object value\n\n%s:%s" % (t, v) tb = None - strval = re.sub(r"\n", "\r\n", strval) + strval = re.sub("\n", "\r\n", strval) self.edit.ReplaceSel(strval) diff --git a/com/win32com/makegw/makegw.py b/com/win32com/makegw/makegw.py index 6074900d5f..8d2e83d654 100644 --- a/com/win32com/makegw/makegw.py +++ b/com/win32com/makegw/makegw.py @@ -197,7 +197,7 @@ def _write_ifc_cpp(f, interface): % (interface.__dict__) ) - ptr = re.sub(r"[a-z]", "", interface.name) + ptr = re.sub("[a-z]", "", interface.name) strdict = {"interfacename": interface.name, "ptr": ptr} for method in interface.methods: strdict["method"] = method.name diff --git a/com/win32com/makegw/makegwparse.py b/com/win32com/makegw/makegwparse.py index ffe69cb4c7..59512f4873 100644 --- a/com/win32com/makegw/makegwparse.py +++ b/com/win32com/makegw/makegwparse.py @@ -928,7 +928,7 @@ class Interface: # name base # -------- -------- - regex = re.compile(r"(interface|) ([^ ]*) : public (.*)$") + regex = re.compile("(interface|) ([^ ]*) : public (.*)$") def __init__(self, mo): self.methods = [] diff --git a/com/win32com/test/testall.py b/com/win32com/test/testall.py index 6ca312e344..6da07407a3 100644 --- a/com/win32com/test/testall.py +++ b/com/win32com/test/testall.py @@ -63,7 +63,7 @@ def CleanGenerated(): def RemoveRefCountOutput(data): while 1: last_line_pos = data.rfind("\n") - if not re.match(r"\[\d+ refs\]", data[last_line_pos + 1 :]): + if not re.match("\[\d+ refs\]", data[last_line_pos + 1 :]): break if last_line_pos < 0: # All the output diff --git a/com/win32com/test/testvbscript_regexp.py b/com/win32com/test/testvbscript_regexp.py index a6c09ae8a7..a22f0bea52 100644 --- a/com/win32com/test/testvbscript_regexp.py +++ b/com/win32com/test/testvbscript_regexp.py @@ -13,8 +13,8 @@ def _CheckMatches(self, match, expected): self.assertEqual(list(found), list(expected)) def _TestVBScriptRegex(self, re): - StringToSearch = r"Python python pYthon Python" - re.Pattern = r"Python" + StringToSearch = "Python python pYthon Python" + re.Pattern = "Python" re.Global = True re.IgnoreCase = True diff --git a/com/win32comext/axscript/client/error.py b/com/win32comext/axscript/client/error.py index 95b333bc0c..97b3098268 100644 --- a/com/win32comext/axscript/client/error.py +++ b/com/win32comext/axscript/client/error.py @@ -24,11 +24,11 @@ def FormatForAX(text): def ExpandTabs(text): - return re.sub(r"\t", " ", text) + return re.sub("\t", " ", text) def AddCR(text): - return re.sub(r"\n", "\r\n", text) + return re.sub("\n", "\r\n", text) class IActiveScriptError: diff --git a/com/win32comext/axscript/client/framework.py b/com/win32comext/axscript/client/framework.py index 89b8dc879f..43e490745d 100644 --- a/com/win32comext/axscript/client/framework.py +++ b/com/win32comext/axscript/client/framework.py @@ -21,7 +21,7 @@ def RemoveCR(text): # No longer just "RemoveCR" - should be renamed to # FixNewlines, or something. Idea is to fix arbitary newlines into # something Python can compile... - return re.sub(r"(\r\n)|\r|(\n\r)", "\n", text) + return re.sub("(\r\n)|\r|(\n\r)", "\n", text) SCRIPTTEXT_FORCEEXECUTION = -2147483648 # 0x80000000 diff --git a/com/win32comext/axscript/client/pyscript.py b/com/win32comext/axscript/client/pyscript.py index 94e30b8396..d2b21b58e1 100644 --- a/com/win32comext/axscript/client/pyscript.py +++ b/com/win32comext/axscript/client/pyscript.py @@ -37,11 +37,11 @@ def debug_attr_print(*args): def ExpandTabs(text): - return re.sub(r"\t", " ", text) + return re.sub("\t", " ", text) def AddCR(text): - return re.sub(r"\n", "\r\n", text) + return re.sub("\n", "\r\n", text) class AXScriptCodeBlock(framework.AXScriptCodeBlock): diff --git a/setup.py b/setup.py index 0ca4c61743..c11f64156e 100644 --- a/setup.py +++ b/setup.py @@ -2146,7 +2146,7 @@ def convert_data_files(files): 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(re.compile(".*\\\\CVS\\\\"), is_regex=1, anchor=0) flist.exclude_pattern("*.pyc", anchor=0) flist.exclude_pattern("*.pyo", anchor=0) if not flist.files: diff --git a/win32/test/test_sspi.py b/win32/test/test_sspi.py index a9db878e93..99d115bafe 100644 --- a/win32/test/test_sspi.py +++ b/win32/test/test_sspi.py @@ -197,31 +197,31 @@ def testSequenceEncrypt(self): def testSecBufferRepr(self): desc = win32security.PySecBufferDescType() assert re.match( - r"PySecBufferDesc\(ulVersion: 0 \| cBuffers: 0 \| pBuffers: 0x[\da-fA-F]{8,16}\)", + "PySecBufferDesc\(ulVersion: 0 \| cBuffers: 0 \| pBuffers: 0x[\da-fA-F]{8,16}\)", repr(desc), ) buffer1 = win32security.PySecBufferType(0, sspicon.SECBUFFER_TOKEN) assert re.match( - r"PySecBuffer\(cbBuffer: 0 \| BufferType: 2 \| pvBuffer: 0x[\da-fA-F]{8,16}\)", + "PySecBuffer\(cbBuffer: 0 \| BufferType: 2 \| pvBuffer: 0x[\da-fA-F]{8,16}\)", repr(buffer1), ) desc.append(buffer1) assert re.match( - r"PySecBufferDesc\(ulVersion: 0 \| cBuffers: 1 \| pBuffers: 0x[\da-fA-F]{8,16}\)", + "PySecBufferDesc\(ulVersion: 0 \| cBuffers: 1 \| pBuffers: 0x[\da-fA-F]{8,16}\)", repr(desc), ) buffer2 = win32security.PySecBufferType(4, sspicon.SECBUFFER_DATA) assert re.match( - r"PySecBuffer\(cbBuffer: 4 \| BufferType: 1 \| pvBuffer: 0x[\da-fA-F]{8,16}\)", + "PySecBuffer\(cbBuffer: 4 \| BufferType: 1 \| pvBuffer: 0x[\da-fA-F]{8,16}\)", repr(buffer2), ) desc.append(buffer2) assert re.match( - r"PySecBufferDesc\(ulVersion: 0 \| cBuffers: 2 \| pBuffers: 0x[\da-fA-F]{8,16}\)", + "PySecBufferDesc\(ulVersion: 0 \| cBuffers: 2 \| pBuffers: 0x[\da-fA-F]{8,16}\)", repr(desc), ) diff --git a/win32/test/testall.py b/win32/test/testall.py index 85adf736e3..d3df263018 100644 --- a/win32/test/testall.py +++ b/win32/test/testall.py @@ -32,7 +32,7 @@ no_user_interaction = True # re to pull apart an exception line into the exception type and the args. -re_exception = re.compile(r"([a-zA-Z0-9_.]*): (.*)$") +re_exception = re.compile("([a-zA-Z0-9_.]*): (.*)$") def find_exception_in_output(data): From 172ac3bad3b0ea27c1c249d176f8d6a45cfe2f44 Mon Sep 17 00:00:00 2001 From: Avasam Date: Mon, 17 Apr 2023 20:28:56 -0400 Subject: [PATCH 07/24] Fix post-merge leftovers --- Pythonwin/pywin/scintilla/view.py | 2 +- README.md | 9 ++------- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/Pythonwin/pywin/scintilla/view.py b/Pythonwin/pywin/scintilla/view.py index 431c4afb1f..3783666fc8 100644 --- a/Pythonwin/pywin/scintilla/view.py +++ b/Pythonwin/pywin/scintilla/view.py @@ -533,7 +533,7 @@ def list2dict(l): endpos = self.LineIndex(maxline) text = self.GetTextRange(self.LineIndex(minline), endpos) try: - l = re.findall("\b" + left + "\.\w+", text) + l = re.findall(r"\b" + left + "\.\w+", text) except re.error: # parens etc may make an invalid RE, but this code wouldnt # benefit even if the RE did work :-) diff --git a/README.md b/README.md index 149ffa5ac2..a905d7fc29 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,6 @@ This is the readme for the Python for Win32 (pywin32) extensions, which provides See [CHANGES.txt](https://github.com/mhammond/pywin32/blob/master/CHANGES.txt) for recent notable changes. -Only Python 3.7+ is supported. If you want Python 2 support, you want build `228`. - ## Docs The docs are a long and sad story, but [there's now an online version](https://mhammond.github.io/pywin32/) @@ -33,7 +31,6 @@ closed. For such issues, please email the note that you must be subscribed to the list before posting. ## Binaries - [Binary releases are deprecated.](https://mhammond.github.io/pywin32_installers.html) While they are still provided, [find them here](https://github.com/mhammond/pywin32/releases) @@ -64,10 +61,8 @@ will be changed, etc) ### Running as a Windows Service -### `The specified procedure could not be found` / `Entry-point not found` Errors? - -A very common report is that people install pywin32, but many imports fail with errors -similar to the above. +To run as a service, you probably want to install pywin32 globally from an elevated +command prompt - see above. You also need to ensure Python is installed in a location where the user running the service has access to the installation and is able to load `pywintypesXX.dll` and `pythonXX.dll`. In particular, the `LocalSystem` account typically will not have access From 52f14cd98c40c3d919412d331aac7905e2068603 Mon Sep 17 00:00:00 2001 From: Avasam Date: Mon, 17 Apr 2023 20:50:12 -0400 Subject: [PATCH 08/24] Use bytes-string for constant bytes values .encode on direct strings Replace uses of str2bytes --- Pythonwin/pywin/framework/interact.py | 4 +- Pythonwin/pywin/framework/scriptutils.py | 6 +-- Pythonwin/pywin/scintilla/control.py | 2 +- Pythonwin/pywin/scintilla/document.py | 6 +-- adodbapi/test/adodbapitest.py | 6 +-- adodbapi/test/dbapi20.py | 8 +--- com/win32com/demos/connect.py | 3 +- com/win32com/test/testPersist.py | 7 ++- com/win32com/test/testShell.py | 25 +++++------ com/win32com/test/testStreams.py | 11 +++-- com/win32comext/mapi/mapiutil.py | 2 +- win32/Demos/BackupRead_BackupWrite.py | 4 +- .../Demos/CreateFileTransacted_MiniVersion.py | 5 +-- win32/Demos/eventLogDemo.py | 6 +-- win32/Demos/mmapfile_demo.py | 17 ++++--- win32/Demos/service/pipeTestService.py | 2 +- win32/Demos/win32clipboardDemo.py | 5 +-- win32/Demos/win32fileDemo.py | 2 +- win32/Lib/netbios.py | 2 +- win32/Lib/pywin32_testutil.py | 8 ---- win32/Lib/sspi.py | 2 +- win32/Lib/win32verstamp.py | 2 +- win32/test/test_clipboard.py | 11 +++-- win32/test/test_odbc.py | 4 +- win32/test/test_pywintypes.py | 4 +- win32/test/test_sspi.py | 12 ++--- win32/test/test_win32api.py | 4 +- win32/test/test_win32file.py | 44 +++++++++---------- win32/test/test_win32inet.py | 5 +-- win32/test/test_win32pipe.py | 21 +++++---- win32/test/test_win32wnet.py | 3 +- 31 files changed, 108 insertions(+), 135 deletions(-) diff --git a/Pythonwin/pywin/framework/interact.py b/Pythonwin/pywin/framework/interact.py index 5f0b87f2e1..6f86789d2c 100644 --- a/Pythonwin/pywin/framework/interact.py +++ b/Pythonwin/pywin/framework/interact.py @@ -47,7 +47,7 @@ re.VERBOSE, ).match -tracebackHeader = "Traceback (".encode("ascii") +tracebackHeader = b"Traceback (" sectionProfile = "Interactive Window" valueFormatTitle = "FormatTitle" @@ -201,7 +201,7 @@ def ColorizeInteractiveCode(self, cdoc, styleStart, stylePyStart): # It is a PythonColorizer state - seek past the end of the line # and ask the Python colorizer to color that. end = startSeg - while end < lengthDoc and cdoc[end] not in "\r\n".encode("ascii"): + while end < lengthDoc and cdoc[end] not in b"\r\n": end = end + 1 self.ColorizePythonCode(cdoc[:end], startSeg, state) stylePyStart = self.GetStringStyle(end - 1) diff --git a/Pythonwin/pywin/framework/scriptutils.py b/Pythonwin/pywin/framework/scriptutils.py index e5bc57c8ff..0f4830d42f 100644 --- a/Pythonwin/pywin/framework/scriptutils.py +++ b/Pythonwin/pywin/framework/scriptutils.py @@ -28,9 +28,9 @@ "\n" ) -byte_cr = "\r".encode("ascii") -byte_lf = "\n".encode("ascii") -byte_crlf = "\r\n".encode("ascii") +byte_cr = b"\r" +byte_lf = b"\n" +byte_crlf = b"\r\n" # A dialog box for the "Run Script" command. diff --git a/Pythonwin/pywin/scintilla/control.py b/Pythonwin/pywin/scintilla/control.py index 460b168645..05aea5f355 100644 --- a/Pythonwin/pywin/scintilla/control.py +++ b/Pythonwin/pywin/scintilla/control.py @@ -40,7 +40,7 @@ dllid = win32api.LoadLibrary("Scintilla.DLL") # null_byte is str in py2k, bytes on py3k -null_byte = "\0".encode("ascii") +null_byte = b"\0" ## These are from Richedit.h - need to add to win32con or commctrl EM_GETTEXTRANGE = 1099 diff --git a/Pythonwin/pywin/scintilla/document.py b/Pythonwin/pywin/scintilla/document.py index cddb442c11..476eb8bcc6 100644 --- a/Pythonwin/pywin/scintilla/document.py +++ b/Pythonwin/pywin/scintilla/document.py @@ -9,11 +9,11 @@ from . import scintillacon -crlf_bytes = "\r\n".encode("ascii") -lf_bytes = "\n".encode("ascii") +crlf_bytes = b"\r\n" +lf_bytes = b"\n" # re from pep263 - but we use it both on bytes and strings. -re_encoding_bytes = re.compile("coding[:=]\s*([-\w.]+)".encode("ascii")) +re_encoding_bytes = re.compile(b"coding[:=]\s*([-\w.]+)") re_encoding_text = re.compile("coding[:=]\s*([-\w.]+)") ParentScintillaDocument = docview.Document diff --git a/adodbapi/test/adodbapitest.py b/adodbapi/test/adodbapitest.py index e5b3dc1946..4b7b352a14 100644 --- a/adodbapi/test/adodbapitest.py +++ b/adodbapi/test/adodbapitest.py @@ -54,10 +54,6 @@ from adodbapi import ado_consts -def str2bytes(sval): - return sval.encode("latin1") - - long = int @@ -519,7 +515,7 @@ def testDataTypeDate(self): ) def testDataTypeBinary(self): - binfld = str2bytes("\x07\x00\xE2\x40*") + binfld = b"\x07\x00\xE2\x40*" arv = [binfld, adodbapi.Binary(binfld), bytes(binfld)] if self.getEngine() == "PostgreSQL": self.helpTestDataType( diff --git a/adodbapi/test/dbapi20.py b/adodbapi/test/dbapi20.py index e378b1941d..19b576ad1e 100644 --- a/adodbapi/test/dbapi20.py +++ b/adodbapi/test/dbapi20.py @@ -95,10 +95,6 @@ def _failUnless(self, expr, msg=None): # nothing # - Fix bugs in test_setoutputsize_basic and test_setinputsizes # -def str2bytes(sval): - if sys.version_info < (3, 0) and isinstance(sval, str): - sval = sval.decode("latin1") - return sval.encode("latin1") # python 3 make unicode into bytes class DatabaseAPI20Test(unittest.TestCase): @@ -910,8 +906,8 @@ def test_Timestamp(self): # self.assertEqual(str(t1),str(t2)) def test_Binary(self): - b = self.driver.Binary(str2bytes("Something")) - b = self.driver.Binary(str2bytes("")) + b = self.driver.Binary(b"Something") + b = self.driver.Binary(b"") def test_STRING(self): _failUnless( diff --git a/com/win32com/demos/connect.py b/com/win32com/demos/connect.py index ed7f51c9cd..cb5928b6a5 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 pywin32_testutil import str2bytes from win32com.server.exception import Exception # This is the IID of the Events interface both Client and Server support. @@ -87,7 +86,7 @@ def test(verbose=0): client = ConnectableClient() connection.Connect(server, client, IID_IConnectDemoEvents) CheckEvent(server, client, "Hello", verbose) - CheckEvent(server, client, str2bytes("Here is a null>\x00<"), verbose) + CheckEvent(server, client, b"Here is a null>\x00<", verbose) CheckEvent(server, client, "Here is a null>\x00<", verbose) val = "test-\xe0\xf2" # 2 extended characters. CheckEvent(server, client, val, verbose) diff --git a/com/win32com/test/testPersist.py b/com/win32com/test/testPersist.py index 066f402921..1371498cc8 100644 --- a/com/win32com/test/testPersist.py +++ b/com/win32com/test/testPersist.py @@ -8,7 +8,6 @@ import win32com.client.dynamic import win32com.server.util import win32ui -from pywin32_testutil import str2bytes from pywintypes import Unicode from win32com import storagecon from win32com.axcontrol import axcontrol @@ -34,8 +33,8 @@ class LockBytes: ] _com_interfaces_ = [pythoncom.IID_ILockBytes] - def __init__(self, data=""): - self.data = str2bytes(data) + def __init__(self, data=b""): + self.data = data self.ctime = now self.mtime = now self.atime = now @@ -68,7 +67,7 @@ def Flush(self, whatsthis=0): def SetSize(self, size): print("Set Size" + str(size)) if size > len(self.data): - self.data = self.data + str2bytes("\000" * (size - len(self.data))) + self.data = self.data + b"\000" * (size - len(self.data)) else: self.data = self.data[0:size] return S_OK diff --git a/com/win32com/test/testShell.py b/com/win32com/test/testShell.py index b312a9dc0f..c903a1caec 100644 --- a/com/win32com/test/testShell.py +++ b/com/win32com/test/testShell.py @@ -14,7 +14,6 @@ import pywintypes import win32com.test.util import win32con -from pywin32_testutil import str2bytes from win32com.shell import shell from win32com.shell.shellcon import * from win32com.storagecon import * @@ -87,25 +86,25 @@ def _rtCIDA(self, parent, kids): self.assertEqual(cida_str_rt, cida_str) def testPIDL(self): - # A PIDL of "\1" is: cb pidl cb - expect = str2bytes("\03\00" "\1" "\0\0") - self.assertEqual(shell.PIDLAsString([str2bytes("\1")]), expect) - self._rtPIDL([str2bytes("\0")]) - self._rtPIDL([str2bytes("\1"), str2bytes("\2"), str2bytes("\3")]) - self._rtPIDL([str2bytes("\0") * 2048] * 2048) + # A PIDL of "\1" is: cb + pidl + cb + expect = b"\03\00" + b"\1" + b"\0\0" + self.assertEqual(shell.PIDLAsString([b"\1"]), expect) + self._rtPIDL([b"\0"]) + self._rtPIDL([b"\1", b"\2", b"\3"]) + self._rtPIDL([b"\0" * 2048] * 2048) # PIDL must be a list self.assertRaises(TypeError, shell.PIDLAsString, "foo") def testCIDA(self): - self._rtCIDA([str2bytes("\0")], [[str2bytes("\0")]]) - self._rtCIDA([str2bytes("\1")], [[str2bytes("\2")]]) + self._rtCIDA([b"\0"], [[b"\0"]]) + self._rtCIDA([b"\1"], [[b"\2"]]) self._rtCIDA( - [str2bytes("\0")], [[str2bytes("\0")], [str2bytes("\1")], [str2bytes("\2")]] + [b"\0"], [[b"\0"], [b"\1"], [b"\2"]] ) def testBadShortPIDL(self): - # A too-short child element: cb pidl cb - pidl = str2bytes("\01\00" "\1") + # A too-short child element: cb + pidl + cb + pidl = b"\01\00" + "\1" self.assertRaises(ValueError, shell.StringAsPIDL, pidl) # ack - tried to test too long PIDLs, but a len of 0xFFFF may not @@ -224,7 +223,7 @@ def setUp(self): self.src_name = os.path.join(tempfile.gettempdir(), "pywin32_testshell") self.dest_name = os.path.join(tempfile.gettempdir(), "pywin32_testshell_dest") - self.test_data = str2bytes("Hello from\0Python") + self.test_data = b"Hello from\0Python" f = open(self.src_name, "wb") f.write(self.test_data) f.close() diff --git a/com/win32com/test/testStreams.py b/com/win32com/test/testStreams.py index 3beb47c760..da0329d5b4 100644 --- a/com/win32com/test/testStreams.py +++ b/com/win32com/test/testStreams.py @@ -3,7 +3,6 @@ import pythoncom import win32com.server.util import win32com.test.util -from pywin32_testutil import str2bytes class Persists: @@ -18,7 +17,7 @@ class Persists: _com_interfaces_ = [pythoncom.IID_IPersistStreamInit] def __init__(self): - self.data = str2bytes("abcdefg") + self.data = b"abcdefg" self.dirty = 1 def GetClassID(self): @@ -82,7 +81,7 @@ class BadStream(Stream): """ def Read(self, amount): - return str2bytes("x") * (amount + 1) + return b"x" * (amount + 1) class StreamTest(win32com.test.util.TestCase): @@ -98,7 +97,7 @@ def _readWrite(self, data, write_stream, read_stream=None): self.assertEqual(data[1:-1], got) def testit(self): - mydata = str2bytes("abcdefghijklmnopqrstuvwxyz") + mydata = b"abcdefghijklmnopqrstuvwxyz" # First test the objects just as Python objects... s = Stream(mydata) @@ -118,7 +117,7 @@ def testit(self): self._readWrite(mydata, s2, s) self._readWrite(mydata, s2, s2) - self._readWrite(str2bytes("string with\0a NULL"), s2, s2) + self._readWrite(b"string with\0a NULL", s2, s2) # reset the stream s.Write(mydata) p2.Load(s2) @@ -126,7 +125,7 @@ def testit(self): self.assertEqual(s.data, mydata) def testseek(self): - s = Stream(str2bytes("yo")) + s = Stream(b"yo") s = win32com.server.util.wrap(s, pythoncom.IID_IStream) # we used to die in py3k passing a value > 32bits s.Seek(0x100000000, pythoncom.STREAM_SEEK_SET) diff --git a/com/win32comext/mapi/mapiutil.py b/com/win32comext/mapi/mapiutil.py index ab89e6adfb..c9519414aa 100644 --- a/com/win32comext/mapi/mapiutil.py +++ b/com/win32comext/mapi/mapiutil.py @@ -147,7 +147,7 @@ def GetAllProperties(obj, make_tag_names=True): _MapiTypeMap = { type(0.0): mapitags.PT_DOUBLE, type(0): mapitags.PT_I4, - type("".encode("ascii")): mapitags.PT_STRING8, # bytes + type(b""): mapitags.PT_STRING8, # bytes type(""): mapitags.PT_UNICODE, # str type(None): mapitags.PT_UNSPECIFIED, # In Python 2.2.2, bool isn't a distinct type (type(1==1) is type(0)). diff --git a/win32/Demos/BackupRead_BackupWrite.py b/win32/Demos/BackupRead_BackupWrite.py index 0e9fc9f920..1f88af8fd6 100644 --- a/win32/Demos/BackupRead_BackupWrite.py +++ b/win32/Demos/BackupRead_BackupWrite.py @@ -8,7 +8,7 @@ import win32con import win32file import win32security -from pywin32_testutil import ob2memory, str2bytes +from pywin32_testutil import ob2memory from win32com import storagecon all_sd_info = ( @@ -103,7 +103,7 @@ ) print("Written:", bytes_written, "Context:", outctxt) win32file.BackupRead(h, 0, buf, True, True, ctxt) -win32file.BackupWrite(outh, 0, str2bytes(""), True, True, outctxt) +win32file.BackupWrite(outh, 0, b"", True, True, outctxt) win32file.CloseHandle(h) win32file.CloseHandle(outh) diff --git a/win32/Demos/CreateFileTransacted_MiniVersion.py b/win32/Demos/CreateFileTransacted_MiniVersion.py index fd600b5908..6ad5868a23 100644 --- a/win32/Demos/CreateFileTransacted_MiniVersion.py +++ b/win32/Demos/CreateFileTransacted_MiniVersion.py @@ -13,7 +13,6 @@ import win32transaction import winerror import winioctlcon -from pywin32_testutil import str2bytes # py3k-friendly helper def demo(): @@ -49,14 +48,14 @@ def demo(): Transaction=trans, ) - win32file.WriteFile(hfile, str2bytes("This is first miniversion.\n")) + win32file.WriteFile(hfile, b"This is first miniversion.\n") buf = win32file.DeviceIoControl( hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION, None, buf_size, None ) struct_ver, struct_len, base_ver, ver_1 = struct.unpack(buf_fmt, buf) win32file.SetFilePointer(hfile, 0, win32con.FILE_BEGIN) - win32file.WriteFile(hfile, str2bytes("This is second miniversion!\n")) + win32file.WriteFile(hfile, b"This is second miniversion!\n") buf = win32file.DeviceIoControl( hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION, None, buf_size, None ) diff --git a/win32/Demos/eventLogDemo.py b/win32/Demos/eventLogDemo.py index 8d4220b070..52d3ae9f37 100644 --- a/win32/Demos/eventLogDemo.py +++ b/win32/Demos/eventLogDemo.py @@ -113,7 +113,7 @@ def test(): logType, 2, strings=["The message text for event 2", "Another insert"], - data="Raw\0Data".encode("ascii"), + data=b"Raw\0Data", sid=my_sid, ) win32evtlogutil.ReportEvent( @@ -121,7 +121,7 @@ def test(): 1, eventType=win32evtlog.EVENTLOG_WARNING_TYPE, strings=["A warning", "An even more dire warning"], - data="Raw\0Data".encode("ascii"), + data=b"Raw\0Data", sid=my_sid, ) win32evtlogutil.ReportEvent( @@ -129,7 +129,7 @@ def test(): 1, eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE, strings=["An info", "Too much info"], - data="Raw\0Data".encode("ascii"), + data=b"Raw\0Data", sid=my_sid, ) print("Successfully wrote 3 records to the log") diff --git a/win32/Demos/mmapfile_demo.py b/win32/Demos/mmapfile_demo.py index 9068ce72fd..ff3ac8f136 100644 --- a/win32/Demos/mmapfile_demo.py +++ b/win32/Demos/mmapfile_demo.py @@ -4,7 +4,6 @@ import mmapfile import win32api import winerror -from pywin32_testutil import str2bytes system_info = win32api.GetSystemInfo() page_size = system_info[1] @@ -17,16 +16,16 @@ m1 = mmapfile.mmapfile(File=fname, Name=mapping_name, MaximumSize=fsize) m1.seek(100) -m1.write_byte(str2bytes("?")) +m1.write_byte(b"?") m1.seek(-1, 1) -assert m1.read_byte() == str2bytes("?") +assert m1.read_byte() == b"?" ## A reopened named mapping should have exact same size as original mapping m2 = mmapfile.mmapfile(Name=mapping_name, File=None, MaximumSize=fsize * 2) assert m2.size() == m1.size() m1.seek(0, 0) -m1.write(fsize * str2bytes("s")) -assert m2.read(fsize) == fsize * str2bytes("s") +m1.write(fsize * b"s") +assert m2.read(fsize) == fsize * b"s" move_src = 100 move_dest = 500 @@ -34,17 +33,17 @@ m2.seek(move_src, 0) assert m2.tell() == move_src -m2.write(str2bytes("m") * move_size) +m2.write(b"m" * move_size) m2.move(move_dest, move_src, move_size) m2.seek(move_dest, 0) -assert m2.read(move_size) == str2bytes("m") * move_size +assert m2.read(move_size) == b"m" * move_size ## m2.write('x'* (fsize+1)) m2.close() m1.resize(fsize * 2) assert m1.size() == fsize * 2 m1.seek(fsize) -m1.write(str2bytes("w") * fsize) +m1.write(b"w" * fsize) m1.flush() m1.close() os.remove(fname) @@ -54,7 +53,7 @@ ## need 10 GB free on drive where your temp folder lives fname_large = tempfile.mktemp() mapping_name = "Pywin32_large_mmap" -offsetdata = str2bytes("This is start of offset") +offsetdata = b"This is start of offset" ## Deliberately use odd numbers to test rounding logic fsize = (1024 * 1024 * 1024 * 10) + 333 diff --git a/win32/Demos/service/pipeTestService.py b/win32/Demos/service/pipeTestService.py index 2efda60647..abd3cb1cb4 100644 --- a/win32/Demos/service/pipeTestService.py +++ b/win32/Demos/service/pipeTestService.py @@ -73,7 +73,7 @@ def DoProcessClient(self, pipeHandle, tid): try: # Create a loop, reading large data. If we knew the data stream was # was small, a simple ReadFile would do. - d = "".encode("ascii") # ensure bytes on py2k and py3k... + d = b"" # ensure bytes on py2k and py3k... hr = winerror.ERROR_MORE_DATA while hr == winerror.ERROR_MORE_DATA: hr, thisd = ReadFile(pipeHandle, 256) diff --git a/win32/Demos/win32clipboardDemo.py b/win32/Demos/win32clipboardDemo.py index 1252ff7d59..e3a3fab03a 100644 --- a/win32/Demos/win32clipboardDemo.py +++ b/win32/Demos/win32clipboardDemo.py @@ -3,7 +3,6 @@ # Demo/test of the win32clipboard module. import win32con -from pywin32_testutil import str2bytes # py3k-friendly helper from win32clipboard import * if not __debug__: @@ -32,7 +31,7 @@ def TestText(): OpenClipboard() try: text = "Hello from Python" - text_bytes = str2bytes(text) + text_bytes = text.encode("latin1") SetClipboardText(text) got = GetClipboardData(win32con.CF_TEXT) # CF_TEXT always gives us 'bytes' back . @@ -54,7 +53,7 @@ def TestText(): # Unicode tests EmptyClipboard() text = "Hello from Python unicode" - text_bytes = str2bytes(text) + text_bytes = text.encode("latin1") # Now set the Unicode value SetClipboardData(win32con.CF_UNICODETEXT, text) # Get it in Unicode. diff --git a/win32/Demos/win32fileDemo.py b/win32/Demos/win32fileDemo.py index a80999251a..e7e5e3bee8 100644 --- a/win32/Demos/win32fileDemo.py +++ b/win32/Demos/win32fileDemo.py @@ -21,7 +21,7 @@ def SimpleFileDemo(): handle = win32file.CreateFile( testName, win32file.GENERIC_WRITE, 0, None, win32con.CREATE_NEW, 0, None ) - test_data = "Hello\0there".encode("ascii") + test_data = b"Hello\0there" win32file.WriteFile(handle, test_data) handle.Close() # Open it for reading. diff --git a/win32/Lib/netbios.py b/win32/Lib/netbios.py index dca4dee679..d60c6d0724 100644 --- a/win32/Lib/netbios.py +++ b/win32/Lib/netbios.py @@ -294,7 +294,7 @@ def byte_to_int(b): ncb.Reset() ncb.Command = NCBASTAT ncb.Lana_num = byte_to_int(la_enum.lana[i]) - ncb.Callname = "* ".encode("ascii") # ensure bytes on py2x and 3k + ncb.Callname = b"* " # ensure bytes on py2x and 3k adapter = ADAPTER_STATUS() ncb.Buffer = adapter Netbios(ncb) diff --git a/win32/Lib/pywin32_testutil.py b/win32/Lib/pywin32_testutil.py index 41566a8eb2..42d41f3ecf 100644 --- a/win32/Lib/pywin32_testutil.py +++ b/win32/Lib/pywin32_testutil.py @@ -12,14 +12,6 @@ ## -# The test suite has lots of string constants containing binary data, but -# the strings are used in various "bytes" contexts. -def str2bytes(sval): - if sys.version_info < (3, 0) and isinstance(sval, str): - sval = sval.decode("latin1") - return sval.encode("latin1") - - # Sometimes we want to pass a string that should explicitly be treated as # a memory blob. def str2memory(sval): diff --git a/win32/Lib/sspi.py b/win32/Lib/sspi.py index 22c0e4a0eb..c6f92ad381 100644 --- a/win32/Lib/sspi.py +++ b/win32/Lib/sspi.py @@ -386,7 +386,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 = "hello".encode("ascii") # py3k-friendly + data = b"hello" # py3k-friendly # Simple signature, not compatible with GSSAPI. sig = sspiclient.sign(data) diff --git a/win32/Lib/win32verstamp.py b/win32/Lib/win32verstamp.py index dea032b0a7..9623c2920e 100644 --- a/win32/Lib/win32verstamp.py +++ b/win32/Lib/win32verstamp.py @@ -14,7 +14,7 @@ VS_FFI_FILEFLAGSMASK = 0x0000003F VOS_NT_WINDOWS32 = 0x00040004 -null_byte = "\0".encode("ascii") # str in py2k, bytes in py3k +null_byte = b"\0" # str in py2k, bytes in py3k # diff --git a/win32/test/test_clipboard.py b/win32/test/test_clipboard.py index 843435b6a8..5a8623d781 100644 --- a/win32/test/test_clipboard.py +++ b/win32/test/test_clipboard.py @@ -7,7 +7,6 @@ import pywintypes import win32con import win32gui -from pywin32_testutil import str2bytes from win32clipboard import * custom_format_name = "PythonClipboardTestFormat" @@ -77,13 +76,13 @@ def test_unicode_text(self): SetClipboardText(val) # GetClipboardData doesn't to auto string conversions - so on py3k, # CF_TEXT returns bytes. - expected = str2bytes(val) + expected = val.encode("latin1") self.assertEqual(GetClipboardData(win32con.CF_TEXT), expected) SetClipboardText(val, win32con.CF_UNICODETEXT) self.assertEqual(GetClipboardData(win32con.CF_UNICODETEXT), val) def test_string(self): - val = str2bytes("test") + val = b"test" SetClipboardData(win32con.CF_TEXT, val) self.assertEqual(GetClipboardData(win32con.CF_TEXT), val) @@ -96,8 +95,8 @@ def tearDown(self): CloseClipboard() def test_mem(self): - val = str2bytes("test") - expected = str2bytes("test\0") + val = b"test" + expected = b"test\0" SetClipboardData(win32con.CF_TEXT, val) # Get the raw data - this will include the '\0' raw_data = GetGlobalMemory(GetClipboardDataHandle(win32con.CF_TEXT)) @@ -113,7 +112,7 @@ def test_bad_mem(self): self.assertRaises(pywintypes.error, GetGlobalMemory, 1) def test_custom_mem(self): - test_data = str2bytes("hello\x00\xff") + test_data = b"hello\x00\xff" test_buffer = array.array("b", test_data) cf = RegisterClipboardFormat(custom_format_name) self.assertEqual(custom_format_name, GetClipboardFormatName(cf)) diff --git a/win32/test/test_odbc.py b/win32/test/test_odbc.py index ef2b45167c..808ebfce11 100644 --- a/win32/test/test_odbc.py +++ b/win32/test/test_odbc.py @@ -6,7 +6,7 @@ import odbc import pythoncom -from pywin32_testutil import TestSkipped, str2bytes, str2memory +from pywin32_testutil import TestSkipped, str2memory from win32com.client import constants # We use the DAO ODBC driver @@ -244,7 +244,7 @@ def test_set_zero_length(self): self.assertEqual( self.cur.execute( "insert into %s (userid,username) " "values (?,?)" % self.tablename, - [str2bytes("Frank"), ""], + [b"Frank", ""], ), 1, ) diff --git a/win32/test/test_pywintypes.py b/win32/test/test_pywintypes.py index bbd9d8823d..c7f9dd7b4d 100644 --- a/win32/test/test_pywintypes.py +++ b/win32/test/test_pywintypes.py @@ -5,7 +5,7 @@ import unittest import pywintypes -from pywin32_testutil import ob2memory, str2bytes +from pywin32_testutil import ob2memory class TestCase(unittest.TestCase): @@ -88,7 +88,7 @@ def testGUID(self): iid2 = pywintypes.IID(ob2memory(iid), True) self.assertEqual(iid, iid2) self.assertRaises( - ValueError, pywintypes.IID, str2bytes("00"), True + ValueError, pywintypes.IID, b"00", True ) # too short self.assertRaises(TypeError, pywintypes.IID, 0, True) # no buffer diff --git a/win32/test/test_sspi.py b/win32/test/test_sspi.py index 5d349d4d30..69404fe6f6 100644 --- a/win32/test/test_sspi.py +++ b/win32/test/test_sspi.py @@ -8,7 +8,7 @@ import sspicon import win32api import win32security -from pywin32_testutil import TestSkipped, str2bytes, testmain +from pywin32_testutil import TestSkipped, testmain # It is quite likely that the Kerberos tests will fail due to not being @@ -63,7 +63,7 @@ def _doTestEncrypt(self, pkg_name): pkg_size_info = sspiclient.ctxt.QueryContextAttributes( sspicon.SECPKG_ATTR_SIZES ) - msg = str2bytes("some data to be encrypted ......") + msg = b"some data to be encrypted ......" trailersize = pkg_size_info["SecurityTrailer"] encbuf = win32security.PySecBufferDescType() @@ -76,7 +76,7 @@ def _doTestEncrypt(self, pkg_name): sspiserver.ctxt.DecryptMessage(encbuf, 1) self.assertEqual(msg, encbuf[0].Buffer) # and test the higher-level functions - data_in = str2bytes("hello") + data_in = b"hello" data, sig = sspiclient.encrypt(data_in) self.assertEqual(sspiserver.decrypt(data, sig), data_in) @@ -92,7 +92,7 @@ def _doTestEncryptStream(self, pkg_name): pkg_size_info = sspiclient.ctxt.QueryContextAttributes( sspicon.SECPKG_ATTR_SIZES ) - msg = str2bytes("some data to be encrypted ......") + msg = b"some data to be encrypted ......" trailersize = pkg_size_info["SecurityTrailer"] blocksize = pkg_size_info["BlockSize"] @@ -136,7 +136,7 @@ def _doTestSign(self, pkg_name): pkg_size_info = sspiclient.ctxt.QueryContextAttributes( sspicon.SECPKG_ATTR_SIZES ) - msg = str2bytes("some data to be encrypted ......") + msg = b"some data to be encrypted ......" sigsize = pkg_size_info["MaxSignature"] sigbuf = win32security.PySecBufferDescType() @@ -148,7 +148,7 @@ def _doTestSign(self, pkg_name): # and test the higher-level functions sspiclient.next_seq_num = 1 sspiserver.next_seq_num = 1 - data = str2bytes("hello") + data = b"hello" key = sspiclient.sign(data) sspiserver.verify(data, key) key = sspiclient.sign(data) diff --git a/win32/test/test_win32api.py b/win32/test/test_win32api.py index 58ac15978a..416f310222 100644 --- a/win32/test/test_win32api.py +++ b/win32/test/test_win32api.py @@ -10,7 +10,7 @@ import win32con import win32event import winerror -from pywin32_testutil import TestSkipped, str2bytes +from pywin32_testutil import TestSkipped class CurrentUserTestCase(unittest.TestCase): @@ -96,7 +96,7 @@ def testValues(self): ( "REG_BINARY", win32con.REG_BINARY, - str2bytes("\x00\x01\x02\x03\x04\x05\x06\x07\x08\x01\x00"), + b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x01\x00", ), ) diff --git a/win32/test/test_win32file.py b/win32/test/test_win32file.py index da99803278..3784bfed14 100644 --- a/win32/test/test_win32file.py +++ b/win32/test/test_win32file.py @@ -17,7 +17,7 @@ import win32pipe import win32timezone import winerror -from pywin32_testutil import TestSkipped, str2bytes, testmain +from pywin32_testutil import TestSkipped, testmain try: set @@ -37,7 +37,7 @@ def testSimpleIndex(self): def testSimpleSlice(self): buffer = win32file.AllocateReadBuffer(2) - val = str2bytes("\0\0") + val = b"\0\0" buffer[:2] = val self.assertEqual(buffer[0:2], val) @@ -50,7 +50,7 @@ def testSimpleFiles(self): handle = win32file.CreateFile( filename, win32file.GENERIC_WRITE, 0, None, win32con.CREATE_NEW, 0, None ) - test_data = str2bytes("Hello\0there") + test_data = b"Hello\0there" try: win32file.WriteFile(handle, test_data) handle.Close() @@ -91,7 +91,7 @@ def testMoreFiles(self): ) # Write a known number of bytes to the file. - data = str2bytes("z") * 1025 + data = b"z" * 1025 win32file.WriteFile(h, data) @@ -154,7 +154,7 @@ def testFilePointer(self): ) try: # Write some data - data = str2bytes("Some data") + data = b"Some data" (res, written) = win32file.WriteFile(f, data) self.assertFalse(res) @@ -312,7 +312,7 @@ def testSimpleOverlapped(self): h = win32file.CreateFile( testName, desiredAccess, 0, None, win32file.CREATE_ALWAYS, 0, 0 ) - chunk_data = str2bytes("z") * 0x8000 + chunk_data = b"z" * 0x8000 num_loops = 512 expected_size = num_loops * len(chunk_data) for i in range(num_loops): @@ -440,7 +440,7 @@ def testCompletionPortsNonQueued(self, test_overlapped_death=0): time.sleep(0.1) # let thread do its thing. try: win32pipe.CallNamedPipe( - r"\\.\pipe\pywin32_test_pipe", str2bytes("Hello there"), BUFSIZE, 0 + r"\\.\pipe\pywin32_test_pipe", b"Hello there", BUFSIZE, 0 ) except win32pipe.error: # Testing for overlapped death causes this @@ -530,7 +530,7 @@ def testAcceptEx(self): self.fail("AcceptEx Worker thread failed to start") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("127.0.0.1", port)) - win32file.WSASend(s, str2bytes("hello"), None) + win32file.WSASend(s, b"hello", None) overlapped = pywintypes.OVERLAPPED() overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None) # Like above - WSARecv used to allow strings as the receive buffer!! @@ -541,7 +541,7 @@ def testAcceptEx(self): win32file.WSARecv(s, buffer, overlapped) nbytes = win32file.GetOverlappedResult(s.fileno(), overlapped, True) got = buffer[:nbytes] - self.assertEqual(got, str2bytes("hello")) + self.assertEqual(got, b"hello") # thread should have stopped stopped.wait(2) if not stopped.isSet(): @@ -720,7 +720,7 @@ class TestEncrypt(unittest.TestCase): def testEncrypt(self): fname = tempfile.mktemp("win32file_test") f = open(fname, "wb") - f.write(str2bytes("hello")) + f.write(b"hello") f.close() f = None try: @@ -774,7 +774,7 @@ def connect_thread_runner(self, expect_payload, giveup_event): nbytes = win32file.GetOverlappedResult(listener.fileno(), overlapped, False) if expect_payload: self.request = buffer[:nbytes] - accepter.send(str2bytes("some expected response")) + accepter.send(b"some expected response") def test_connect_with_payload(self): giveup_event = win32event.CreateEvent(None, 0, 0, None) @@ -787,7 +787,7 @@ def test_connect_with_payload(self): ol = pywintypes.OVERLAPPED() s2.bind(("0.0.0.0", 0)) # connectex requires the socket be bound beforehand try: - win32file.ConnectEx(s2, self.addr, ol, str2bytes("some expected request")) + win32file.ConnectEx(s2, self.addr, ol, b"some expected request") except win32file.error as exc: win32event.SetEvent(giveup_event) if exc.winerror == 10022: # WSAEINVAL @@ -806,8 +806,8 @@ def test_connect_with_payload(self): win32file.WSARecv(s2, buff, ol, 0) length = win32file.GetOverlappedResult(s2.fileno(), ol, 1) self.response = buff[:length] - self.assertEqual(self.response, str2bytes("some expected response")) - self.assertEqual(self.request, str2bytes("some expected request")) + self.assertEqual(self.response, b"some expected response") + self.assertEqual(self.request, b"some expected request") t.join(5) self.assertFalse(t.is_alive(), "worker thread didn't terminate") @@ -842,7 +842,7 @@ def test_connect_without_payload(self): win32file.WSARecv(s2, buff, ol, 0) length = win32file.GetOverlappedResult(s2.fileno(), ol, 1) self.response = buff[:length] - self.assertEqual(self.response, str2bytes("some expected response")) + self.assertEqual(self.response, b"some expected response") t.join(5) self.assertFalse(t.is_alive(), "worker thread didn't terminate") @@ -889,11 +889,11 @@ def runner(): s2.connect(self.addr) length = 0 - aaa = str2bytes("[AAA]") - bbb = str2bytes("[BBB]") - ccc = str2bytes("[CCC]") - ddd = str2bytes("[DDD]") - empty = str2bytes("") + aaa = b"[AAA]" + bbb = b"[BBB]" + ccc = b"[CCC]" + ddd = b"[DDD]" + empty = b"" ol = pywintypes.OVERLAPPED() f.seek(0) win32file.TransmitFile( @@ -931,7 +931,7 @@ def runner(): s2.close() th.join() - buf = str2bytes("").join(self.request) + buf = b"".join(self.request) self.assertEqual(length, len(buf)) expected = val + aaa + val + bbb + val + val + ccc + ddd + val self.assertEqual(type(expected), type(buf)) @@ -1014,7 +1014,7 @@ def test_functional(self): events = win32file.WSAEnumNetworkEvents(client, client_event) self.assertEqual(events, {win32file.FD_CONNECT: 0, win32file.FD_WRITE: 0}) sent = 0 - data = str2bytes("x") * 16 * 1024 + data = b"x" * 16 * 1024 while sent < 16 * 1024 * 1024: try: sent += client.send(data) diff --git a/win32/test/test_win32inet.py b/win32/test/test_win32inet.py index 044ef8e612..d2d30c5252 100644 --- a/win32/test/test_win32inet.py +++ b/win32/test/test_win32inet.py @@ -1,7 +1,6 @@ import unittest import winerror -from pywin32_testutil import str2bytes # py3k-friendly helper from pywin32_testutil import TestSkipped, testmain from win32inet import * from win32inetcon import * @@ -53,8 +52,8 @@ def testPythonDotOrg(self): if not chunk: break chunks.append(chunk) - data = str2bytes("").join(chunks) - assert data.find(str2bytes("Python")) > 0, repr( + data = b"".join(chunks) + assert data.find(b"Python") > 0, repr( data ) # This must appear somewhere on the main page! diff --git a/win32/test/test_win32pipe.py b/win32/test/test_win32pipe.py index cbe647dde7..4832a8b0c7 100644 --- a/win32/test/test_win32pipe.py +++ b/win32/test/test_win32pipe.py @@ -8,7 +8,6 @@ import win32file import win32pipe import winerror -from pywin32_testutil import str2bytes # py3k-friendly helper class PipeTests(unittest.TestCase): @@ -21,9 +20,9 @@ def _serverThread(self, pipe_handle, event, wait_time): hr in (0, winerror.ERROR_PIPE_CONNECTED), "Got error code 0x%x" % (hr,) ) hr, got = win32file.ReadFile(pipe_handle, 100) - self.assertEqual(got, str2bytes("foo\0bar")) + self.assertEqual(got, b"foo\0bar") time.sleep(wait_time) - win32file.WriteFile(pipe_handle, str2bytes("bar\0foo")) + win32file.WriteFile(pipe_handle, b"bar\0foo") pipe_handle.Close() event.set() @@ -54,9 +53,9 @@ def testCallNamedPipe(self): self.startPipeServer(event) got = win32pipe.CallNamedPipe( - self.pipename, str2bytes("foo\0bar"), 1024, win32pipe.NMPWAIT_WAIT_FOREVER + self.pipename, b"foo\0bar", 1024, win32pipe.NMPWAIT_WAIT_FOREVER ) - self.assertEqual(got, str2bytes("bar\0foo")) + self.assertEqual(got, b"bar\0foo") event.wait(5) self.assertTrue(event.isSet(), "Pipe server thread didn't terminate") @@ -80,8 +79,8 @@ def testTransactNamedPipeBlocking(self): hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None ) - hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), 1024, None) - self.assertEqual(got, str2bytes("bar\0foo")) + hr, got = win32pipe.TransactNamedPipe(hpipe, b"foo\0bar", 1024, None) + self.assertEqual(got, b"bar\0foo") event.wait(5) self.assertTrue(event.isSet(), "Pipe server thread didn't terminate") @@ -109,9 +108,9 @@ def testTransactNamedPipeBlockingBuffer(self): buffer = win32file.AllocateReadBuffer(1024) hr, got = win32pipe.TransactNamedPipe( - hpipe, str2bytes("foo\0bar"), buffer, None + hpipe, b"foo\0bar", buffer, None ) - self.assertEqual(got, str2bytes("bar\0foo")) + self.assertEqual(got, b"bar\0foo") event.wait(5) self.assertTrue(event.isSet(), "Pipe server thread didn't terminate") @@ -139,12 +138,12 @@ def testTransactNamedPipeAsync(self): buffer = win32file.AllocateReadBuffer(1024) hr, got = win32pipe.TransactNamedPipe( - hpipe, str2bytes("foo\0bar"), buffer, overlapped + hpipe, b"foo\0bar", buffer, overlapped ) self.assertEqual(hr, winerror.ERROR_IO_PENDING) nbytes = win32file.GetOverlappedResult(hpipe, overlapped, True) got = buffer[:nbytes] - self.assertEqual(got, str2bytes("bar\0foo")) + self.assertEqual(got, b"bar\0foo") event.wait(5) self.assertTrue(event.isSet(), "Pipe server thread didn't terminate") diff --git a/win32/test/test_win32wnet.py b/win32/test/test_win32wnet.py index 04ad8a4de0..69f54a09d4 100644 --- a/win32/test/test_win32wnet.py +++ b/win32/test/test_win32wnet.py @@ -3,7 +3,6 @@ import netbios import win32api import win32wnet -from pywin32_testutil import str2bytes RESOURCE_CONNECTED = 0x00000001 RESOURCE_GLOBALNET = 0x00000002 @@ -114,7 +113,7 @@ def testNetbios(self): ncb.Reset() ncb.Command = netbios.NCBASTAT ncb.Lana_num = byte_to_int(la_enum.lana[i]) - ncb.Callname = str2bytes("* ") # ensure bytes on py2x and 3k + ncb.Callname = b"* " # ensure bytes on py2x and 3k adapter = netbios.ADAPTER_STATUS() ncb.Buffer = adapter Netbios(ncb) From 09f2456909dd61ac6eedd89161f505adeb9f2999 Mon Sep 17 00:00:00 2001 From: Avasam Date: Mon, 17 Apr 2023 21:37:57 -0400 Subject: [PATCH 09/24] Run formatters --- com/win32com/test/testShell.py | 6 ++---- win32/test/test_pywintypes.py | 4 +--- win32/test/test_win32pipe.py | 8 ++------ 3 files changed, 5 insertions(+), 13 deletions(-) diff --git a/com/win32com/test/testShell.py b/com/win32com/test/testShell.py index c903a1caec..d6a164caa2 100644 --- a/com/win32com/test/testShell.py +++ b/com/win32com/test/testShell.py @@ -98,13 +98,11 @@ def testPIDL(self): def testCIDA(self): self._rtCIDA([b"\0"], [[b"\0"]]) self._rtCIDA([b"\1"], [[b"\2"]]) - self._rtCIDA( - [b"\0"], [[b"\0"], [b"\1"], [b"\2"]] - ) + self._rtCIDA([b"\0"], [[b"\0"], [b"\1"], [b"\2"]]) def testBadShortPIDL(self): # A too-short child element: cb + pidl + cb - pidl = b"\01\00" + "\1" + pidl = b"\01\00" + b"\1" self.assertRaises(ValueError, shell.StringAsPIDL, pidl) # ack - tried to test too long PIDLs, but a len of 0xFFFF may not diff --git a/win32/test/test_pywintypes.py b/win32/test/test_pywintypes.py index c7f9dd7b4d..44b5c960cb 100644 --- a/win32/test/test_pywintypes.py +++ b/win32/test/test_pywintypes.py @@ -87,9 +87,7 @@ def testGUID(self): iid = pywintypes.IID(s) iid2 = pywintypes.IID(ob2memory(iid), True) self.assertEqual(iid, iid2) - self.assertRaises( - ValueError, pywintypes.IID, b"00", True - ) # too short + self.assertRaises(ValueError, pywintypes.IID, b"00", True) # too short self.assertRaises(TypeError, pywintypes.IID, 0, True) # no buffer def testGUIDRichCmp(self): diff --git a/win32/test/test_win32pipe.py b/win32/test/test_win32pipe.py index 4832a8b0c7..00a474caba 100644 --- a/win32/test/test_win32pipe.py +++ b/win32/test/test_win32pipe.py @@ -107,9 +107,7 @@ def testTransactNamedPipeBlockingBuffer(self): ) buffer = win32file.AllocateReadBuffer(1024) - hr, got = win32pipe.TransactNamedPipe( - hpipe, b"foo\0bar", buffer, None - ) + hr, got = win32pipe.TransactNamedPipe(hpipe, b"foo\0bar", buffer, None) self.assertEqual(got, b"bar\0foo") event.wait(5) self.assertTrue(event.isSet(), "Pipe server thread didn't terminate") @@ -137,9 +135,7 @@ def testTransactNamedPipeAsync(self): ) buffer = win32file.AllocateReadBuffer(1024) - hr, got = win32pipe.TransactNamedPipe( - hpipe, b"foo\0bar", buffer, overlapped - ) + hr, got = win32pipe.TransactNamedPipe(hpipe, b"foo\0bar", buffer, overlapped) self.assertEqual(hr, winerror.ERROR_IO_PENDING) nbytes = win32file.GetOverlappedResult(hpipe, overlapped, True) got = buffer[:nbytes] From 3fb1140b5f46bd662698fa659bfddfdd1a9022da Mon Sep 17 00:00:00 2001 From: Avasam Date: Mon, 17 Apr 2023 22:41:02 -0400 Subject: [PATCH 10/24] Spotted a couple typos --- com/win32com/client/__init__.py | 2 +- com/win32com/client/genpy.py | 4 ++-- com/win32com/storagecon.py | 2 +- win32/Demos/security/sspi/socket_server.py | 2 +- win32/Demos/service/pipeTestService.py | 9 ++++----- 5 files changed, 9 insertions(+), 10 deletions(-) diff --git a/com/win32com/client/__init__.py b/com/win32com/client/__init__.py index 303eabe5d3..17257ca123 100644 --- a/com/win32com/client/__init__.py +++ b/com/win32com/client/__init__.py @@ -476,7 +476,7 @@ def Record(name, object): # XXX - to do - probably should allow "object" to already be a module object. from . import gencache - object = gencache.EnsureDispatch + object = gencache.EnsureDispatch(object) module = sys.modules[object.__class__.__module__] # to allow us to work correctly with "demand generated" code, # we must use the typelib CLSID to obtain the module diff --git a/com/win32com/client/genpy.py b/com/win32com/client/genpy.py index 920cbf1953..6ad1f36b57 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -45,8 +45,8 @@ pythoncom.VT_UI1: "int", pythoncom.VT_UI2: "int", pythoncom.VT_UI4: "int", - pythoncom.VT_I8: "lint", - pythoncom.VT_UI8: "lint", + pythoncom.VT_I8: "int", + pythoncom.VT_UI8: "int", pythoncom.VT_INT: "int", pythoncom.VT_DATE: "pythoncom.PyTimeType", # FIXME: Type does not exist anywhere; pywintypes.TimeType ? pythoncom.VT_UINT: "int", diff --git a/com/win32com/storagecon.py b/com/win32com/storagecon.py index 10ee65de43..3ed5290238 100644 --- a/com/win32com/storagecon.py +++ b/com/win32com/storagecon.py @@ -1,6 +1,6 @@ """Constants related to IStorage and related interfaces -This file was generated by h2py from d:\\msdev\\include\\objbase.h +This file was generated by h2py from d:\msdev\include\objbase.h then hand edited, a few extra constants added, etc. """ diff --git a/win32/Demos/security/sspi/socket_server.py b/win32/Demos/security/sspi/socket_server.py index d1ac70b22c..4d606bb86b 100644 --- a/win32/Demos/security/sspi/socket_server.py +++ b/win32/Demos/security/sspi/socket_server.py @@ -9,7 +9,7 @@ Running either the client or server as a different user can be informative. A command-line such as the following may be useful: -`runas /user:{user} {fqp}\\python.exe {fqp}\\socket_server.py --wait client|server` +`runas /user:{user} {fqp}\python.exe {fqp}\socket_server.py --wait client|server` {fqp} should specify the relevant fully-qualified path names. diff --git a/win32/Demos/service/pipeTestService.py b/win32/Demos/service/pipeTestService.py index 50c8c0a9f9..27aec92555 100644 --- a/win32/Demos/service/pipeTestService.py +++ b/win32/Demos/service/pipeTestService.py @@ -88,11 +88,10 @@ def DoProcessClient(self, pipeHandle, tid): # pipe, but for the sake of this demo we dont (if only to see what errors # we can get when our clients break at strange times :-) if ok: - msg = b"%s (on thread %d) sent me %s" % ( - GetNamedPipeHandleState(pipeHandle, False, True)[4], - tid, - d, - ) + msg = ( + "%s (on thread %d) sent me %s" + % (GetNamedPipeHandleState(pipeHandle, False, True)[4], tid, d) + ).encode("ascii") WriteFile(pipeHandle, msg) finally: ApplyIgnoreError(DisconnectNamedPipe, (pipeHandle,)) From 8246c1d83092bac494a73145b0e2bbc23779654d Mon Sep 17 00:00:00 2001 From: Avasam Date: Thu, 20 Apr 2023 20:48:16 -0400 Subject: [PATCH 11/24] Found another r string to revert --- Pythonwin/pywin/framework/winout.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Pythonwin/pywin/framework/winout.py b/Pythonwin/pywin/framework/winout.py index 21f8a95f3b..e78e959a9a 100644 --- a/Pythonwin/pywin/framework/winout.py +++ b/Pythonwin/pywin/framework/winout.py @@ -101,7 +101,7 @@ def OnDestroy(self, message): class WindowOutputViewImpl: def __init__(self): - self.patErrorMessage = re.compile(r'\W*File "(.*)", line ([0-9]+)') + self.patErrorMessage = re.compile('\W*File "(.*)", line ([0-9]+)') self.template = self.GetDocument().GetDocTemplate() def HookHandlers(self): From 1b9d623b365440d67748118ce050d631c54515b4 Mon Sep 17 00:00:00 2001 From: Avasam Date: Thu, 20 Apr 2023 23:08:04 -0400 Subject: [PATCH 12/24] Remove references to outdated IronPython --- adodbapi/adodbapi.py | 86 +++++++---------------------- adodbapi/apibase.py | 29 +--------- adodbapi/is64bit.py | 13 ++--- adodbapi/quick_reference.md | 6 +- adodbapi/readme.txt | 12 +--- adodbapi/remote.py | 1 - adodbapi/remote/server.py | 1 - adodbapi/setup.py | 1 - adodbapi/test/is64bit.py | 13 ++--- adodbapi/test/setuptestframework.py | 9 +-- 10 files changed, 38 insertions(+), 133 deletions(-) diff --git a/adodbapi/adodbapi.py b/adodbapi/adodbapi.py index 8f7c045ea7..2d2dc36875 100644 --- a/adodbapi/adodbapi.py +++ b/adodbapi/adodbapi.py @@ -24,7 +24,6 @@ DB-API 2.0 specification: http://www.python.org/dev/peps/pep-0249/ This module source should run correctly in CPython versions 2.7 and later, -or IronPython version 2.7 and later, or, after running through 2to3.py, CPython 3.4 or later. """ @@ -48,45 +47,24 @@ # --- define objects to smooth out IronPython <-> CPython differences onWin32 = False # assume the worst -if api.onIronPython: - from clr import Reference - from System import ( - Activator, - Array, - Byte, - DateTime, - DBNull, - Decimal as SystemDecimal, - Type, - ) - - def Dispatch(dispatch): - type = Type.GetTypeFromProgID(dispatch) - return Activator.CreateInstance(type) - - def getIndexedValue(obj, index): - return obj.Item[index] +try: + import pythoncom + import pywintypes + import win32com.client -else: # try pywin32 - try: - import pythoncom - import pywintypes - import win32com.client + onWin32 = True - onWin32 = True + def Dispatch(dispatch): + return win32com.client.Dispatch(dispatch) - def Dispatch(dispatch): - return win32com.client.Dispatch(dispatch) +except ImportError: + import warnings - except ImportError: - import warnings + warnings.warn("pywin32 package required for adodbapi.", ImportWarning) - warnings.warn( - "pywin32 package (or IronPython) required for adodbapi.", ImportWarning - ) - def getIndexedValue(obj, index): - return obj(index) +def getIndexedValue(obj, index): + return obj(index) from collections.abc import Mapping @@ -210,12 +188,7 @@ def _configure_parameter(p, value, adotype, settings_known): p.Size = L # v2.1 Jevon elif isinstance(value, decimal.Decimal): - if api.onIronPython: - s = str(value) - p.Value = s - p.Size = len(s) - else: - p.Value = value + p.Value = value exponent = value.as_tuple()[2] digit_count = len(value.as_tuple()[1]) p.Precision = digit_count @@ -238,10 +211,6 @@ def _configure_parameter(p, value, adotype, settings_known): p.Value = s p.Size = len(s) - elif api.onIronPython and isinstance(value, longType): # Iron Python Long - s = str(value) # feature workaround for IPy 2.0 - p.Value = s - elif adotype == adc.adEmpty: # ADO will not let you specify a null column p.Type = ( adc.adInteger @@ -653,7 +622,7 @@ def build_column_info(self, recordset): self.numberOfColumns = 0 return self.rs = recordset # v2.1.1 bkline - self.recordset_format = api.RS_ARRAY if api.onIronPython else api.RS_WIN_32 + self.recordset_format = api.RS_WIN_32 self.numberOfColumns = recordset.Fields.Count try: varCon = self.connection.variantConversions @@ -790,12 +759,7 @@ def _execute_command(self): print('Executing command="%s"' % self.commandText) try: # ----- the actual SQL is executed here --- - if api.onIronPython: - ra = Reference[int]() - recordset = self.cmd.Execute(ra) - count = ra.Value - else: # pywin32 - recordset, count = self.cmd.Execute() + recordset, count = self.cmd.Execute() # ----- ------------------------------- --- except Exception as e: _message = "" @@ -1180,21 +1144,11 @@ def nextset(self): ) return None - if api.onIronPython: - try: - recordset = self.rs.NextRecordset() - except TypeError: - recordset = None - except api.Error as exc: - self._raiseCursorError(api.NotSupportedError, exc.args) - else: # pywin32 - try: # [begin 2.1 ekelund] - rsTuple = self.rs.NextRecordset() # - except pywintypes.com_error as exc: # return appropriate error - self._raiseCursorError( - api.NotSupportedError, exc.args - ) # [end 2.1 ekelund] - recordset = rsTuple[0] + try: # [begin 2.1 ekelund] + rsTuple = self.rs.NextRecordset() # + except pywintypes.com_error as exc: # return appropriate error + self._raiseCursorError(api.NotSupportedError, exc.args) # [end 2.1 ekelund] + recordset = rsTuple[0] if recordset is None: return None self.build_column_info(recordset) diff --git a/adodbapi/apibase.py b/adodbapi/apibase.py index 50770c96ee..3b37e465cb 100644 --- a/adodbapi/apibase.py +++ b/adodbapi/apibase.py @@ -16,16 +16,6 @@ verbose = False # debugging flag -onIronPython = sys.platform == "cli" -if onIronPython: # we need type definitions for odd data we may need to convert - # noinspection PyUnresolvedReferences - from System import DateTime, DBNull - - NullTypes = (type(None), DBNull) -else: - DateTime = type(NotImplemented) # should never be seen on win32 - NullTypes = type(None) - # --- define objects to smooth out Python3 <-> Python 2.x differences unicodeType = str longType = int @@ -34,7 +24,7 @@ memoryViewType = memoryview _BaseException = Exception -try: # jdhardy -- handle bytes under IronPython & Py3 +try: # jdhardy -- handle bytes under Py3 bytes except NameError: bytes = str # define it for old Pythons @@ -283,8 +273,6 @@ def DateObjectFromCOMDate(self, comDate): new = datetime.datetime.combine(datetime.datetime.fromordinal(odn), tim) return new # return comDate.replace(tzinfo=None) # make non aware - elif isinstance(comDate, DateTime): - fComDate = comDate.ToOADate() # ironPython clr Date/Time else: fComDate = float(comDate) # ComDate is number of days since 1899-12-31 integerPart = int(fComDate) @@ -316,8 +304,6 @@ def DateObjectFromCOMDate(self, comDate): "Returns ticks since 1970" if isinstance(comDate, datetime.datetime): return comDate.timetuple() - elif isinstance(comDate, DateTime): # ironPython clr date/time - fcomDate = comDate.ToOADate() else: fcomDate = float(comDate) secondsperday = 86400 # 24*60*60 @@ -469,11 +455,6 @@ def variantConvertDate(v): def cvtString(variant): # use to get old action of adodbapi v1 if desired - if onIronPython: - try: - return variant.ToString() - except: - pass return str(variant) @@ -523,17 +504,11 @@ def identity(x): def cvtUnusual(variant): if verbose > 1: sys.stderr.write("Conversion called for Unusual data=%s\n" % repr(variant)) - if isinstance(variant, DateTime): # COMdate or System.Date - from .adodbapi import ( # this will only be called when adodbapi is in use, and very rarely - dateconverter, - ) - - return dateconverter.DateObjectFromCOMDate(variant) return variant # cannot find conversion function -- just give the data to the user def convert_to_python(variant, func): # convert DB value into Python value - if isinstance(variant, NullTypes): # IronPython Null or None + if isinstance(variant, type(None)): return None return func(variant) # call the appropriate conversion function diff --git a/adodbapi/is64bit.py b/adodbapi/is64bit.py index 911c61931e..39bcde16b2 100644 --- a/adodbapi/is64bit.py +++ b/adodbapi/is64bit.py @@ -3,15 +3,10 @@ def Python(): - if sys.platform == "cli": # IronPython - import System - - return System.IntPtr.Size == 8 - else: - try: - return sys.maxsize > 2147483647 - except AttributeError: - return sys.maxint > 2147483647 + try: + return sys.maxsize > 2147483647 + except AttributeError: + return sys.maxint > 2147483647 def os(): diff --git a/adodbapi/quick_reference.md b/adodbapi/quick_reference.md index e4bc9f9cfe..19d38ef175 100644 --- a/adodbapi/quick_reference.md +++ b/adodbapi/quick_reference.md @@ -2,10 +2,8 @@ Adodbapi quick reference ======================== -Adodbapi is a Python DB-API 2.0 module that makes it easy to use -Microsoft ADO -for connecting with databases and other data sources -using either CPython or IronPython. +Adodbapi is a Python DB-API 2.0 module that makes it easy to use Microsoft ADO +for connecting with databases and other data sources using CPython. Source home page: https://github.com/mhammond/pywin32/tree/master/adodbapi diff --git a/adodbapi/readme.txt b/adodbapi/readme.txt index 02bb620f4d..954a6ab524 100644 --- a/adodbapi/readme.txt +++ b/adodbapi/readme.txt @@ -3,15 +3,14 @@ Project adodbapi A Python DB-API 2.0 (PEP-249) module that makes it easy to use Microsoft ADO -for connecting with databases and other data sources -using either CPython or IronPython. +for connecting with databases and other data sources using CPython. Home page: Features: * 100% DB-API 2.0 (PEP-249) compliant (including most extensions and recommendations). * Includes pyunit testcases that describe how to use the module. -* Fully implemented in Python. -- runs in Python 2.5+ Python 3.0+ and IronPython 2.6+ +* Fully implemented in Python. -- runs in Python 2.5+ and Python 3.0+ * Licensed under the LGPL license, which means that it can be used freely even in commercial programs subject to certain restrictions. * The user can choose between paramstyles: 'qmark' 'named' 'format' 'pyformat' 'dynamic' * Supports data retrieval by column name e.g.: @@ -22,14 +21,9 @@ Features: Prerequisites: * C Python 2.7 or 3.5 or higher and pywin32 (Mark Hammond's python for windows extensions.) -or - Iron Python 2.7 or higher. (works in IPy2.0 for all data types except BUFFER) Installation: * (C-Python on Windows): Install pywin32 ("pip install pywin32") which includes adodbapi. -* (IronPython on Windows): Download adodbapi from http://sf.net/projects/adodbapi. Unpack the zip. - Open a command window as an administrator. CD to the folder containing the unzipped files. - Run "setup.py install" using the IronPython of your choice. NOTE: ........... If you do not like the new default operation of returning Numeric columns as decimal.Decimal, @@ -87,6 +81,6 @@ and look at the test cases in adodbapi/test directory. Mailing lists ------------- The adodbapi mailing lists have been deactivated. Submit comments to the -pywin32 or IronPython mailing lists. +pywin32 mailing lists. -- the bug tracker on sourceforge.net/projects/adodbapi may be checked, (infrequently). -- please use: https://github.com/mhammond/pywin32/issues diff --git a/adodbapi/remote.py b/adodbapi/remote.py index ae22b5a7ea..bd29a11ea6 100644 --- a/adodbapi/remote.py +++ b/adodbapi/remote.py @@ -23,7 +23,6 @@ DB-API 2.0 specification: http://www.python.org/dev/peps/pep-0249/ This module source should run correctly in CPython versions 2.5 and later, -or IronPython version 2.7 and later, or, after running through 2to3.py, CPython 3.0 or later. """ diff --git a/adodbapi/remote/server.py b/adodbapi/remote/server.py index 3cce1d8ab4..9834e505a2 100644 --- a/adodbapi/remote/server.py +++ b/adodbapi/remote/server.py @@ -20,7 +20,6 @@ DB-API 2.0 specification: http://www.python.org/dev/peps/pep-0249/ This module source should run correctly in CPython versions 2.6 and later, -or IronPython version 2.6 and later, or, after running through 2to3.py, CPython 3.2 or later. """ diff --git a/adodbapi/setup.py b/adodbapi/setup.py index d25869adf9..f0e88d1f11 100644 --- a/adodbapi/setup.py +++ b/adodbapi/setup.py @@ -1,7 +1,6 @@ """adodbapi -- a pure Python PEP 249 DB-API package using Microsoft ADO Adodbapi can be run on CPython 3.5 and later. -or IronPython version 2.6 and later (in theory, possibly no longer in practice!) """ CLASSIFIERS = """\ Development Status :: 5 - Production/Stable diff --git a/adodbapi/test/is64bit.py b/adodbapi/test/is64bit.py index ed390fad00..56f166cf5f 100644 --- a/adodbapi/test/is64bit.py +++ b/adodbapi/test/is64bit.py @@ -3,15 +3,10 @@ def Python(): - if sys.platform == "cli": # IronPython - import System - - return System.IntPtr.Size == 8 - else: - try: - return sys.maxsize > 2147483647 - except AttributeError: - return sys.maxint > 2147483647 + try: + return sys.maxsize > 2147483647 + except AttributeError: + return sys.maxint > 2147483647 def os(): diff --git a/adodbapi/test/setuptestframework.py b/adodbapi/test/setuptestframework.py index 83fe5ca9db..b0f2243fc2 100644 --- a/adodbapi/test/setuptestframework.py +++ b/adodbapi/test/setuptestframework.py @@ -85,12 +85,9 @@ def makemdb(testfolder, mdb_name): from win32com.client.gencache import EnsureDispatch win32 = True - except ImportError: # perhaps we are running IronPython - win32 = False # iron Python - try: - from System import Activator, Type - except: - pass + except ImportError: + win32 = False # assume the worst + pass # Create a brand-new database - what is the story with these? dbe = None From 5d59f040e2152d6984252cbe7b33460bfeddd7c5 Mon Sep 17 00:00:00 2001 From: Avasam Date: Thu, 27 Apr 2023 23:16:48 -0400 Subject: [PATCH 13/24] Address PR comments and simplify more code post IronPython logic removal --- adodbapi/adodbapi.py | 26 +++++---------------- adodbapi/apibase.py | 2 +- adodbapi/is64bit.py | 5 +--- adodbapi/readme.txt | 5 ++-- adodbapi/remote.py | 3 --- adodbapi/test/adodbapitest.py | 15 +++--------- adodbapi/test/is64bit.py | 5 +--- adodbapi/test/setuptestframework.py | 36 +++++++---------------------- 8 files changed, 23 insertions(+), 74 deletions(-) diff --git a/adodbapi/adodbapi.py b/adodbapi/adodbapi.py index 2d2dc36875..ea5886dc50 100644 --- a/adodbapi/adodbapi.py +++ b/adodbapi/adodbapi.py @@ -24,7 +24,7 @@ DB-API 2.0 specification: http://www.python.org/dev/peps/pep-0249/ This module source should run correctly in CPython versions 2.7 and later, -or, after running through 2to3.py, CPython 3.4 or later. +or CPython 3.4 or later. """ __version__ = "2.6.2.0" @@ -36,6 +36,10 @@ import sys import weakref +import pythoncom +import pywintypes +from win32com.client import Dispatch + from . import ado_consts as adc, apibase as api, process_connect_string try: @@ -45,23 +49,6 @@ if verbose: print(version) -# --- define objects to smooth out IronPython <-> CPython differences -onWin32 = False # assume the worst -try: - import pythoncom - import pywintypes - import win32com.client - - onWin32 = True - - def Dispatch(dispatch): - return win32com.client.Dispatch(dispatch) - -except ImportError: - import warnings - - warnings.warn("pywin32 package required for adodbapi.", ImportWarning) - def getIndexedValue(obj, index): return obj(index) @@ -79,8 +66,7 @@ def getIndexedValue(obj, index): # ----------------- The .connect method ----------------- def make_COM_connecter(): try: - if onWin32: - pythoncom.CoInitialize() # v2.1 Paj + pythoncom.CoInitialize() # v2.1 Paj c = Dispatch("ADODB.Connection") # connect _after_ CoIninialize v2.1.1 adamvan except: raise api.InterfaceError( diff --git a/adodbapi/apibase.py b/adodbapi/apibase.py index 3b37e465cb..f578d690fe 100644 --- a/adodbapi/apibase.py +++ b/adodbapi/apibase.py @@ -508,7 +508,7 @@ def cvtUnusual(variant): def convert_to_python(variant, func): # convert DB value into Python value - if isinstance(variant, type(None)): + if variant is None: return None return func(variant) # call the appropriate conversion function diff --git a/adodbapi/is64bit.py b/adodbapi/is64bit.py index 39bcde16b2..e198e9cba8 100644 --- a/adodbapi/is64bit.py +++ b/adodbapi/is64bit.py @@ -3,10 +3,7 @@ def Python(): - try: - return sys.maxsize > 2147483647 - except AttributeError: - return sys.maxint > 2147483647 + return sys.maxsize > 2147483647 def os(): diff --git a/adodbapi/readme.txt b/adodbapi/readme.txt index 954a6ab524..9044d7a8f1 100644 --- a/adodbapi/readme.txt +++ b/adodbapi/readme.txt @@ -10,7 +10,7 @@ Home page: Features: * 100% DB-API 2.0 (PEP-249) compliant (including most extensions and recommendations). * Includes pyunit testcases that describe how to use the module. -* Fully implemented in Python. -- runs in Python 2.5+ and Python 3.0+ +* Fully implemented in Python. -- runs in current versions of Python 3 * Licensed under the LGPL license, which means that it can be used freely even in commercial programs subject to certain restrictions. * The user can choose between paramstyles: 'qmark' 'named' 'format' 'pyformat' 'dynamic' * Supports data retrieval by column name e.g.: @@ -19,11 +19,12 @@ Features: * Supports user-definable system-to-Python data conversion functions (selected by ADO data type, or by column) Prerequisites: -* C Python 2.7 or 3.5 or higher +* C Python 3.6 or higher and pywin32 (Mark Hammond's python for windows extensions.) Installation: * (C-Python on Windows): Install pywin32 ("pip install pywin32") which includes adodbapi. +* (IronPython on Windows): Download adodbapi from http://sf.net/projects/adodbapi. Unpack the zip. NOTE: ........... If you do not like the new default operation of returning Numeric columns as decimal.Decimal, diff --git a/adodbapi/remote.py b/adodbapi/remote.py index bd29a11ea6..8bb22733e3 100644 --- a/adodbapi/remote.py +++ b/adodbapi/remote.py @@ -21,9 +21,6 @@ django adaptations and refactoring thanks to Adam Vandenberg DB-API 2.0 specification: http://www.python.org/dev/peps/pep-0249/ - -This module source should run correctly in CPython versions 2.5 and later, -or, after running through 2to3.py, CPython 3.0 or later. """ __version__ = "2.6.0.4" diff --git a/adodbapi/test/adodbapitest.py b/adodbapi/test/adodbapitest.py index 4b7b352a14..1a4ebb0063 100644 --- a/adodbapi/test/adodbapitest.py +++ b/adodbapi/test/adodbapitest.py @@ -29,18 +29,9 @@ import sys import unittest -try: - import win32com.client - - win32 = True -except ImportError: - win32 = False - -# run the configuration module. -import adodbapitestconfig as config # will set sys.path to find correct version of adodbapi - -# in our code below, all our switches are from config.whatever -import tryconnection +import adodbapitestconfig as config # run the configuration module. # will set sys.path to find correct version of adodbapi +import tryconnection # in our code below, all our switches are from config.whatever +import win32com.client import adodbapi import adodbapi.apibase as api diff --git a/adodbapi/test/is64bit.py b/adodbapi/test/is64bit.py index 56f166cf5f..2cc56ed929 100644 --- a/adodbapi/test/is64bit.py +++ b/adodbapi/test/is64bit.py @@ -3,10 +3,7 @@ def Python(): - try: - return sys.maxsize > 2147483647 - except AttributeError: - return sys.maxint > 2147483647 + return sys.maxsize > 2147483647 def os(): diff --git a/adodbapi/test/setuptestframework.py b/adodbapi/test/setuptestframework.py index b0f2243fc2..91c46e0889 100644 --- a/adodbapi/test/setuptestframework.py +++ b/adodbapi/test/setuptestframework.py @@ -6,11 +6,6 @@ import sys import tempfile -try: - OSErrors = (WindowsError, OSError) -except NameError: # not running on Windows - OSErrors = OSError - def maketemp(): temphome = tempfile.gettempdir() @@ -52,7 +47,7 @@ def makeadopackage(testfolder): newpackage = os.path.join(testfolder, "adodbapi") try: os.mkdir(newpackage) - except OSErrors: + except (WindowsError, OSError): print( "*Note: temporary adodbapi package already exists: may be two versions running?" ) @@ -80,38 +75,23 @@ def makemdb(testfolder, mdb_name): if os.path.isfile(_accessdatasource): print("using JET database=", _accessdatasource) else: - try: - from win32com.client import constants - from win32com.client.gencache import EnsureDispatch - - win32 = True - except ImportError: - win32 = False # assume the worst - pass + from win32com.client import constants + from win32com.client.gencache import EnsureDispatch # Create a brand-new database - what is the story with these? dbe = None for suffix in (".36", ".35", ".30"): try: - if win32: - dbe = EnsureDispatch("DAO.DBEngine" + suffix) - else: - type = Type.GetTypeFromProgID("DAO.DBEngine" + suffix) - dbe = Activator.CreateInstance(type) + dbe = EnsureDispatch("DAO.DBEngine" + suffix) break except: pass if dbe: print(" ...Creating ACCESS db at " + _accessdatasource) - if win32: - workspace = dbe.Workspaces(0) - newdb = workspace.CreateDatabase( - _accessdatasource, constants.dbLangGeneral, constants.dbVersion40 - ) - else: - newdb = dbe.CreateDatabase( - _accessdatasource, ";LANGID=0x0409;CP=1252;COUNTRY=0" - ) + workspace = dbe.Workspaces(0) + newdb = workspace.CreateDatabase( + _accessdatasource, constants.dbLangGeneral, constants.dbVersion40 + ) newdb.Close() else: print(" ...copying test ACCESS db to " + _accessdatasource) From c75634283b8f5e90954c8af5a54eca86345bfc41 Mon Sep 17 00:00:00 2001 From: Avasam Date: Tue, 11 Jul 2023 14:14:05 -0400 Subject: [PATCH 14/24] Fix bad check in _checkItemAttributes --- win32/test/test_win32wnet.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/win32/test/test_win32wnet.py b/win32/test/test_win32wnet.py index f6b21b39da..316c2e29dd 100644 --- a/win32/test/test_win32wnet.py +++ b/win32/test/test_win32wnet.py @@ -57,18 +57,20 @@ def testGetUser(self): def _checkItemAttributes(self, item, attrs): for attr, typ in attrs: val = getattr(item, attr) - if typ is None: - new_val = "new value" - elif typ is int: + if typ is int: self.assertTrue( isinstance(val, int), "Attr %r has value %r" % (attr, val) ) new_val = val + 1 elif typ is str: - self.assertTrue( - isinstance(val, str), "Attr %r has value %r" % (attr, val) - ) - new_val = val + " new value" + if val is not None: + # must be string + self.assertTrue( + isinstance(val, str), "Attr %r has value %r" % (attr, val) + ) + new_val = val + " new value" + else: + new_val = "new value" else: self.fail("Don't know what %s is" % (typ,)) # set the attribute just to make sure we can. From c2991b379f0ba2db1a9504fc8c7f4a49f2b90096 Mon Sep 17 00:00:00 2001 From: Avasam Date: Sun, 23 Jul 2023 15:56:35 -0400 Subject: [PATCH 15/24] Update obsolete Python 1 comments --- Pythonwin/pywin/framework/mdi_pychecker.py | 2 +- Pythonwin/pywin/framework/scriptutils.py | 2 +- Pythonwin/pywin/idle/PyParse.py | 2 +- Pythonwin/pywin/idle/readme.txt | 3 ++- Pythonwin/pywin/tools/browser.py | 2 +- com/win32com/client/makepy.py | 5 +---- com/win32comext/axdebug/src/PyIDebugStackFrame.cpp | 2 +- com/win32comext/taskscheduler/test/test_addtask_1.py | 4 ++-- com/win32comext/taskscheduler/test/test_addtask_2.py | 4 ++-- pywin32_postinstall.py | 2 +- win32/Lib/win32traceutil.py | 2 +- win32/help/win32net.html | 2 +- win32/scripts/regsetup.py | 2 +- win32/scripts/setup_d.py | 4 ++-- 14 files changed, 18 insertions(+), 20 deletions(-) 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 e710f0fcd8..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: diff --git a/Pythonwin/pywin/idle/PyParse.py b/Pythonwin/pywin/idle/PyParse.py index abebbca63f..2a775bffea 100644 --- a/Pythonwin/pywin/idle/PyParse.py +++ b/Pythonwin/pywin/idle/PyParse.py @@ -155,7 +155,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..9f4f9fddcf 100644 --- a/Pythonwin/pywin/idle/readme.txt +++ b/Pythonwin/pywin/idle/readme.txt @@ -6,7 +6,8 @@ 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. -Eg, If you have Python 1.5.2 installed, the files in this + +Eg, If you have Python 3.7 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. diff --git a/Pythonwin/pywin/tools/browser.py b/Pythonwin/pywin/tools/browser.py index 3742582773..a206c3ee2a 100644 --- a/Pythonwin/pywin/tools/browser.py +++ b/Pythonwin/pywin/tools/browser.py @@ -304,7 +304,7 @@ def GetSubList(self): return ret -# In Python 1.6, strings and Unicode have builtin methods, but we dont really want to see these +# strings and Unicode have builtin methods, but we dont really want to see these class HLIString(HLIPythonObject): def IsExpandable(self): return 0 diff --git a/com/win32com/client/makepy.py b/com/win32com/client/makepy.py index 9f65893470..18974305b4 100644 --- a/com/win32com/client/makepy.py +++ b/com/win32com/client/makepy.py @@ -34,10 +34,7 @@ -h -- Do not generate hidden methods. - -u -- Python 1.5 and earlier: Do NOT convert all Unicode objects to - strings. - - Python 1.6 and later: Convert all Unicode objects to strings. + -u -- Convert all Unicode objects to strings. -o -- Create output in a specified output file. If the path leading to the file does not exist, any missing directories will be 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/taskscheduler/test/test_addtask_1.py b/com/win32comext/taskscheduler/test/test_addtask_1.py index 29c9e08d2e..fa4cf5067e 100644 --- a/com/win32comext/taskscheduler/test/test_addtask_1.py +++ b/com/win32comext/taskscheduler/test/test_addtask_1.py @@ -33,12 +33,12 @@ ) new_task.SetIdleWait(1, 10000) new_task.SetComment("test task with idle trigger") -new_task.SetApplicationName("c:\\python23\\python.exe") +new_task.SetApplicationName("c:\\python37\\python.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.SetWorkingDirectory("c:\\Python37") 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/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/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") From 73d5963570ea4dae7a0672a81897585ea70d5b3d Mon Sep 17 00:00:00 2001 From: Avasam Date: Sun, 23 Jul 2023 17:01:53 -0400 Subject: [PATCH 16/24] Update com/win32com/client/genpy.py --- com/win32com/client/genpy.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/com/win32com/client/genpy.py b/com/win32com/client/genpy.py index 3dee10a971..9a5c625c4b 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -38,7 +38,7 @@ pythoncom.VT_I4: "int", pythoncom.VT_R4: "float", pythoncom.VT_R8: "float", - pythoncom.VT_BSTR: "string", + pythoncom.VT_BSTR: "str", pythoncom.VT_BOOL: "int", pythoncom.VT_VARIANT: "type", pythoncom.VT_I1: "int", From a4f02f6b42ac0e93810c3aa0508a7d1be8d837e0 Mon Sep 17 00:00:00 2001 From: Avasam Date: Mon, 24 Jul 2023 14:50:08 -0400 Subject: [PATCH 17/24] Improved HLIFunction.GetSubList --- Pythonwin/pywin/tools/browser.py | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/Pythonwin/pywin/tools/browser.py b/Pythonwin/pywin/tools/browser.py index a206c3ee2a..6dfe3a24fa 100644 --- a/Pythonwin/pywin/tools/browser.py +++ b/Pythonwin/pywin/tools/browser.py @@ -241,16 +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 - code = self.myobject.__code__ - globs = self.myobject.__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 From 2b338a7691500f593e622eb6a7f95ad75bb4f435 Mon Sep 17 00:00:00 2001 From: Avasam Date: Mon, 24 Jul 2023 15:01:01 -0400 Subject: [PATCH 18/24] Missed two comments --- adodbapi/is64bit.py | 2 +- adodbapi/test/is64bit.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/adodbapi/is64bit.py b/adodbapi/is64bit.py index e198e9cba8..a272361ba0 100644 --- a/adodbapi/is64bit.py +++ b/adodbapi/is64bit.py @@ -10,7 +10,7 @@ def os(): import platform pm = platform.machine() - if pm != ".." and pm.endswith("64"): # recent Python (not Iron) + if pm != ".." and pm.endswith("64"): # recent 64 bit Python return True else: import os diff --git a/adodbapi/test/is64bit.py b/adodbapi/test/is64bit.py index 2cc56ed929..339bdaaa6f 100644 --- a/adodbapi/test/is64bit.py +++ b/adodbapi/test/is64bit.py @@ -10,7 +10,7 @@ def os(): import platform pm = platform.machine() - if pm != ".." and pm.endswith("64"): # recent Python (not Iron) + if pm != ".." and pm.endswith("64"): # recent 64 bit Python return True else: import os From 337d9cc1fdc4a6644de24bf4a41bc2ca93ddd29f Mon Sep 17 00:00:00 2001 From: Avasam Date: Mon, 24 Jul 2023 17:17:20 -0400 Subject: [PATCH 19/24] __nonzero__ to __bool__ --- Pythonwin/pywin/mfc/object.py | 2 +- com/win32com/client/__init__.py | 6 +++--- com/win32com/client/genpy.py | 4 ++-- win32/src/PyHANDLE.cpp | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) 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/com/win32com/client/__init__.py b/com/win32com/client/__init__.py index dba5f45ac2..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 diff --git a/com/win32com/client/genpy.py b/com/win32com/client/genpy.py index ae782b04a5..c00a77e190 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -738,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/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; } From 7510c94b32731137911aaec5dc0e2c5b0b9b95f8 Mon Sep 17 00:00:00 2001 From: Avasam Date: Sun, 6 Aug 2023 12:15:27 -0400 Subject: [PATCH 20/24] Revert adodbapi changes --- adodbapi/__init__.py | 2 - adodbapi/adodbapi.py | 124 ++++++++++++++++++++-------- adodbapi/apibase.py | 115 +++++++++++++++++++++----- adodbapi/is64bit.py | 12 ++- adodbapi/quick_reference.md | 28 +++++-- adodbapi/readme.txt | 15 ++-- adodbapi/remote.py | 32 ++++--- adodbapi/remote/server.py | 33 ++++---- adodbapi/setup.py | 1 + adodbapi/test/adodbapitest.py | 119 +++++++++++++++++++++++--- adodbapi/test/adodbapitestconfig.py | 26 ++++-- adodbapi/test/dbapi20.py | 32 ++++--- adodbapi/test/is64bit.py | 12 ++- adodbapi/test/setuptestframework.py | 50 ++++++++--- 14 files changed, 464 insertions(+), 137 deletions(-) diff --git a/adodbapi/__init__.py b/adodbapi/__init__.py index 80d2c061d1..428bdf432a 100644 --- a/adodbapi/__init__.py +++ b/adodbapi/__init__.py @@ -36,8 +36,6 @@ ) -# ----------------------------------------------------------- -# conversion functions mandated by PEP 249 def Binary(aString): """This function constructs an object capable of holding a binary (long) string value.""" return bytes(aString) diff --git a/adodbapi/adodbapi.py b/adodbapi/adodbapi.py index 7c5407da29..36a2c88961 100644 --- a/adodbapi/adodbapi.py +++ b/adodbapi/adodbapi.py @@ -23,35 +23,22 @@ DB-API 2.0 specification: http://www.python.org/dev/peps/pep-0249/ -This module source should run correctly in CPython 3.4 or later. +This module source should run correctly in CPython versions 2.7 and later, +or IronPython version 2.7 and later, +or, after running through 2to3.py, CPython 3.4 or later. """ + +__version__ = "2.6.2.0" +version = "adodbapi v" + __version__ + import copy import decimal import os import sys import weakref -import pythoncom -import pywintypes -from win32com.client import Dispatch - from . import ado_consts as adc, apibase as api, process_connect_string -try: - import pythoncom - import pywintypes - import win32com.client - - onWin32 = True -except ImportError: - import warnings - - warnings.warn("pywin32 package required for adodbapi.", ImportWarning) - onWin32 = False # assume the worst - -__version__ = "3.7.0.0" -version = "adodbapi v" + __version__ - try: verbose = int(os.environ["ADODBAPI_VERBOSE"]) except: @@ -59,18 +46,63 @@ if verbose: print(version) +# --- define objects to smooth out IronPython <-> CPython differences +onWin32 = False # assume the worst +if api.onIronPython: + from clr import Reference + from System import ( + Activator, + Array, + Byte, + DateTime, + DBNull, + Decimal as SystemDecimal, + Type, + ) + + def Dispatch(dispatch): + type = Type.GetTypeFromProgID(dispatch) + return Activator.CreateInstance(type) + + def getIndexedValue(obj, index): + return obj.Item[index] + +else: # try pywin32 + try: + import pythoncom + import pywintypes + import win32com.client + + onWin32 = True -def getIndexedValue(obj, index): - return obj(index) + def Dispatch(dispatch): + return win32com.client.Dispatch(dispatch) + + except ImportError: + import warnings + + warnings.warn( + "pywin32 package (or IronPython) required for adodbapi.", ImportWarning + ) + + def getIndexedValue(obj, index): + return obj(index) from collections.abc import Mapping +# --- define objects to smooth out Python3000 <-> Python 2.x differences +unicodeType = str +longType = int +StringTypes = str +maxint = sys.maxsize + # ----------------- The .connect method ----------------- def make_COM_connecter(): try: - pythoncom.CoInitialize() # v2.1 Paj + if onWin32: + pythoncom.CoInitialize() # v2.1 Paj c = Dispatch("ADODB.Connection") # connect _after_ CoIninialize v2.1.1 adamvan except: raise api.InterfaceError( @@ -166,7 +198,7 @@ def _configure_parameter(p, value, adotype, settings_known): p.Size = len(value) p.AppendChunk(value) - elif isinstance(value, str): # v2.1 Jevon + elif isinstance(value, StringTypes): # v2.1 Jevon L = len(value) if adotype in api.adoStringTypes: # v2.2.1 Cole if settings_known: @@ -178,7 +210,12 @@ def _configure_parameter(p, value, adotype, settings_known): p.Size = L # v2.1 Jevon elif isinstance(value, decimal.Decimal): - p.Value = value + if api.onIronPython: + s = str(value) + p.Value = s + p.Size = len(s) + else: + p.Value = value exponent = value.as_tuple()[2] digit_count = len(value.as_tuple()[1]) p.Precision = digit_count @@ -201,6 +238,10 @@ def _configure_parameter(p, value, adotype, settings_known): p.Value = s p.Size = len(s) + elif api.onIronPython and isinstance(value, longType): # Iron Python Long + s = str(value) # feature workaround for IPy 2.0 + p.Value = s + elif adotype == adc.adEmpty: # ADO will not let you specify a null column p.Type = ( adc.adInteger @@ -213,7 +254,7 @@ def _configure_parameter(p, value, adotype, settings_known): # # # # # ----- the Class that defines a connection ----- # # # # # -class Connection: +class Connection(object): # include connection attributes as class attributes required by api definition. Warning = api.Warning Error = api.Error @@ -524,7 +565,7 @@ def get_table_names(self): # # # # # ----- the Class that defines a cursor ----- # # # # # -class Cursor: +class Cursor(object): ## ** api required attributes: ## description... ## This read-only attribute is a sequence of 7-item sequences. @@ -612,7 +653,7 @@ def build_column_info(self, recordset): self.numberOfColumns = 0 return self.rs = recordset # v2.1.1 bkline - self.recordset_format = api.RS_WIN_32 + self.recordset_format = api.RS_ARRAY if api.onIronPython else api.RS_WIN_32 self.numberOfColumns = recordset.Fields.Count try: varCon = self.connection.variantConversions @@ -749,7 +790,12 @@ def _execute_command(self): print('Executing command="%s"' % self.commandText) try: # ----- the actual SQL is executed here --- - recordset, count = self.cmd.Execute() + if api.onIronPython: + ra = Reference[int]() + recordset = self.cmd.Execute(ra) + count = ra.Value + else: # pywin32 + recordset, count = self.cmd.Execute() # ----- ------------------------------- --- except Exception as e: _message = "" @@ -1134,11 +1180,21 @@ def nextset(self): ) return None - try: # [begin 2.1 ekelund] - rsTuple = self.rs.NextRecordset() # - except pywintypes.com_error as exc: # return appropriate error - self._raiseCursorError(api.NotSupportedError, exc.args) # [end 2.1 ekelund] - recordset = rsTuple[0] + if api.onIronPython: + try: + recordset = self.rs.NextRecordset() + except TypeError: + recordset = None + except api.Error as exc: + self._raiseCursorError(api.NotSupportedError, exc.args) + else: # pywin32 + try: # [begin 2.1 ekelund] + rsTuple = self.rs.NextRecordset() # + except pywintypes.com_error as exc: # return appropriate error + self._raiseCursorError( + api.NotSupportedError, exc.args + ) # [end 2.1 ekelund] + recordset = rsTuple[0] if recordset is None: return None self.build_column_info(recordset) diff --git a/adodbapi/apibase.py b/adodbapi/apibase.py index 5d5b7d3a34..d16265917f 100644 --- a/adodbapi/apibase.py +++ b/adodbapi/apibase.py @@ -16,6 +16,29 @@ verbose = False # debugging flag +onIronPython = sys.platform == "cli" +if onIronPython: # we need type definitions for odd data we may need to convert + # noinspection PyUnresolvedReferences + from System import DateTime, DBNull + + NullTypes = (type(None), DBNull) +else: + DateTime = type(NotImplemented) # should never be seen on win32 + NullTypes = type(None) + +# --- define objects to smooth out Python3 <-> Python 2.x differences +unicodeType = str +longType = int +StringTypes = str +makeByteBuffer = bytes +memoryViewType = memoryview +_BaseException = Exception + +try: # jdhardy -- handle bytes under IronPython & Py3 + bytes +except NameError: + bytes = str # define it for old Pythons + # ------- Error handlers ------ def standardErrorHandler(connection, cursor, errorclass, errorvalue): @@ -32,7 +55,8 @@ def standardErrorHandler(connection, cursor, errorclass, errorvalue): raise errorclass(errorvalue) -class Error(Exception): +# Note: _BaseException is defined differently between Python 2.x and 3.x +class Error(_BaseException): pass # Exception that is the base class of all other error # exceptions. You can use this to catch all errors with one # single 'except' statement. Warnings are not considered @@ -41,7 +65,7 @@ class Error(Exception): # module exceptions). -class Warning(Exception): +class Warning(_BaseException): pass @@ -139,10 +163,10 @@ class FetchFailedError(OperationalError): # # def Binary(aString): # """This function constructs an object capable of holding a binary (long) string value. """ -# b = bytes(aString) +# b = makeByteBuffer(aString) # return b # ----- Time converters ---------------------------------------------- -class TimeConverter: # this is a generic time converter skeleton +class TimeConverter(object): # this is a generic time converter skeleton def __init__(self): # the details will be filled in by instances self._ordinal_1899_12_31 = datetime.date(1899, 12, 31).toordinal() - 1 # Use cls.types to compare if an input parameter is a datetime @@ -169,8 +193,11 @@ def COMDate(self, obj): except: # might be a tuple try: return self.ComDateFromTuple(obj) - except: - raise ValueError('Cannot convert "%s" to COMdate.' % repr(obj)) + except: # try an mxdate + try: + return obj.COMDate() + except: + raise ValueError('Cannot convert "%s" to COMdate.' % repr(obj)) def ComDateFromTuple(self, t, microseconds=0): d = datetime.date(t[0], t[1], t[2]) @@ -204,13 +231,48 @@ def DateObjectToIsoFormatString(self, obj): if isinstance(obj, datetime.date): s = obj.isoformat() + " 00:00:00" # return exact midnight else: - try: # maybe time.struct_time - s = time.strftime("%Y-%m-%d %H:%M:%S", obj) - except: - raise ValueError('Cannot convert "%s" to isoformat' % repr(obj)) + try: # maybe it has a strftime method, like mx + s = obj.strftime("%Y-%m-%d %H:%M:%S") + except AttributeError: + try: # but may be time.struct_time + s = time.strftime("%Y-%m-%d %H:%M:%S", obj) + except: + raise ValueError('Cannot convert "%s" to isoformat' % repr(obj)) return s +# -- Optional: if mx extensions are installed you may use mxDateTime ---- +try: + import mx.DateTime + + mxDateTime = True +except: + mxDateTime = False +if mxDateTime: + + class mxDateTimeConverter(TimeConverter): # used optionally if installed + def __init__(self): + TimeConverter.__init__(self) + self.types.add(type(mx.DateTime)) + + def DateObjectFromCOMDate(self, comDate): + return mx.DateTime.DateTimeFromCOMDate(comDate) + + def Date(self, year, month, day): + return mx.DateTime.Date(year, month, day) + + def Time(self, hour, minute, second): + return mx.DateTime.Time(hour, minute, second) + + def Timestamp(self, year, month, day, hour, minute, second): + return mx.DateTime.Timestamp(year, month, day, hour, minute, second) + +else: + + class mxDateTimeConverter(TimeConverter): + pass # if no mx is installed + + class pythonDateTimeConverter(TimeConverter): # standard since Python 2.3 def __init__(self): TimeConverter.__init__(self) @@ -222,6 +284,8 @@ def DateObjectFromCOMDate(self, comDate): new = datetime.datetime.combine(datetime.datetime.fromordinal(odn), tim) return new # return comDate.replace(tzinfo=None) # make non aware + elif isinstance(comDate, DateTime): + fComDate = comDate.ToOADate() # ironPython clr Date/Time else: fComDate = float(comDate) # ComDate is number of days since 1899-12-31 integerPart = int(fComDate) @@ -253,6 +317,8 @@ def DateObjectFromCOMDate(self, comDate): "Returns ticks since 1970" if isinstance(comDate, datetime.datetime): return comDate.timetuple() + elif isinstance(comDate, DateTime): # ironPython clr date/time + fcomDate = comDate.ToOADate() else: fcomDate = float(comDate) secondsperday = 86400 # 24*60*60 @@ -329,7 +395,7 @@ def Timestamp(self, year, month, day, hour, minute, second): # this class is a trick to determine whether a type is a member of a related group of types. see PEP notes -class DBAPITypeObject: +class DBAPITypeObject(object): def __init__(self, valuesTuple): self.values = frozenset(valuesTuple) @@ -361,7 +427,7 @@ def __ne__(self, other): # ------- utilities for translating python data types to ADO data types --------------------------------- typeMap = { - memoryview: adc.adVarBinary, + memoryViewType: adc.adVarBinary, float: adc.adDouble, type(None): adc.adEmpty, str: adc.adBSTR, @@ -383,7 +449,7 @@ def pyTypeToADOType(d): if tp in dateconverter.types: return adc.adDate # otherwise, attempt to discern the type by probing the data object itself -- to handle duck typing - if isinstance(d, str): + if isinstance(d, StringTypes): return adc.adBSTR if isinstance(d, numbers.Integral): return adc.adBigInt @@ -397,13 +463,17 @@ def pyTypeToADOType(d): # ------------------------------------------------------------------------ # variant type : function converting variant to Python value def variantConvertDate(v): - # this function only called when adodbapi is running - from . import dateconverter + from . import dateconverter # this function only called when adodbapi is running return dateconverter.DateObjectFromCOMDate(v) def cvtString(variant): # use to get old action of adodbapi v1 if desired + if onIronPython: + try: + return variant.ToString() + except: + pass return str(variant) @@ -453,12 +523,19 @@ def identity(x): def cvtUnusual(variant): if verbose > 1: sys.stderr.write("Conversion called for Unusual data=%s\n" % repr(variant)) + if isinstance(variant, DateTime): # COMdate or System.Date + from .adodbapi import ( # this will only be called when adodbapi is in use, and very rarely + dateconverter, + ) + + return dateconverter.DateObjectFromCOMDate(variant) return variant # cannot find conversion function -- just give the data to the user def convert_to_python(variant, func): # convert DB value into Python value - # call the appropriate conversion function - return None if variant is None else func(variant) + if isinstance(variant, NullTypes): # IronPython Null or None + return None + return func(variant) # call the appropriate conversion function class MultiMap(dict): # builds a dictionary from {(sequence,of,keys) : function} @@ -501,7 +578,7 @@ def __setitem__(self, adoType, cvtFn): RS_WIN_32, RS_ARRAY, RS_REMOTE = list(range(1, 4)) -class SQLrow: # a single database row +class SQLrow(object): # a single database row # class to emulate a sequence, so that a column may be retrieved by either number or name def __init__(self, rows, index): # "rows" is an _SQLrows object, index is which row self.rows = rows # parent 'fetch' container object @@ -577,7 +654,7 @@ def __str__(self): # create a pretty human readable representation # # # # -class SQLrows: +class SQLrows(object): # class to emulate a sequence for multiple rows using a container object def __init__(self, ado_results, numberOfRows, cursor): self.ado_results = ado_results # raw result of SQL get diff --git a/adodbapi/is64bit.py b/adodbapi/is64bit.py index a272361ba0..911c61931e 100644 --- a/adodbapi/is64bit.py +++ b/adodbapi/is64bit.py @@ -3,14 +3,22 @@ def Python(): - return sys.maxsize > 2147483647 + if sys.platform == "cli": # IronPython + import System + + return System.IntPtr.Size == 8 + else: + try: + return sys.maxsize > 2147483647 + except AttributeError: + return sys.maxint > 2147483647 def os(): import platform pm = platform.machine() - if pm != ".." and pm.endswith("64"): # recent 64 bit Python + if pm != ".." and pm.endswith("64"): # recent Python (not Iron) return True else: import os diff --git a/adodbapi/quick_reference.md b/adodbapi/quick_reference.md index ce543726bb..e4bc9f9cfe 100644 --- a/adodbapi/quick_reference.md +++ b/adodbapi/quick_reference.md @@ -2,8 +2,10 @@ Adodbapi quick reference ======================== -Adodbapi is a Python DB-API 2.0 module that makes it easy to use Microsoft ADO -for connecting with databases and other data sources using CPython. +Adodbapi is a Python DB-API 2.0 module that makes it easy to use +Microsoft ADO +for connecting with databases and other data sources +using either CPython or IronPython. Source home page: https://github.com/mhammond/pywin32/tree/master/adodbapi @@ -105,19 +107,27 @@ access api specification is found at: The PEP requires several module level attributes. Older versions of adodbapi (which was once all one big file) defined a hundred or two. I hate that, but can\'t break old code, so I decided to fix the problem -for Python 3. The programmer must take the time to pick +for Python 3. If using Python3 the programmer must take the time to pick up the symbols she needs from apibase and ado\_consts. Part of the adodbapi package\'s \_\_init\_\_.py looks something like this: ```python -from .apibase import BINARY, DATETIME, NUMBER, ROWID, STRING, DatabaseError, DataError, Error, FetchFailedError, IntegrityError, InterfaceError, InternalError, NotSupportedError, OperationalError, ProgrammingError, Warning, apilevel, paramstyle, threadsafety - -from .adodbapi import Connection, Cursor, __version__, connect, dateconverter -version = "adodbapi v" + __version__ +if sys.version_info < (3,0): # in Python 2, define all symbols, just like before + from apibase import * # using this is bad + from ado_consts import * # using this is worse +else: + # but if the user is running Python 3, then keep the dictionary clean + from apibase import apilevel, threadsafety, paramstyle + from apibase import Warning, Error, InterfaceError, DatabaseError, DataError + from apibase import OperationalError, IntegrityError + from apibase import InternalError, ProgrammingError, NotSupportedError + from apibase import NUMBER, STRING, BINARY, DATETIME, ROWID + +from adodbapi import connect, Connection, __version__ +version = 'adodbapi v' + __version__ ``` - Please, use only those last four symbols from adodbapi. All others should be imported directly from their own sub-modules. My tests and examples all follow that rule. @@ -771,7 +781,7 @@ Running the tests The test folder contains a set of unittest programs. Setting them up can be a bit complex, because you need several database servers to do a complete test, and each one has a different configuration. Scripts in -this folder try to work in Python 3.5(+) +this folder try to work in Python 2.7 or Python 3.5(+) - dbapi20.py diff --git a/adodbapi/readme.txt b/adodbapi/readme.txt index 3739363939..02bb620f4d 100644 --- a/adodbapi/readme.txt +++ b/adodbapi/readme.txt @@ -3,14 +3,15 @@ Project adodbapi A Python DB-API 2.0 (PEP-249) module that makes it easy to use Microsoft ADO -for connecting with databases and other data sources using CPython. +for connecting with databases and other data sources +using either CPython or IronPython. Home page: Features: * 100% DB-API 2.0 (PEP-249) compliant (including most extensions and recommendations). * Includes pyunit testcases that describe how to use the module. -* Fully implemented in Python. -- runs in current versions of Python 3 +* Fully implemented in Python. -- runs in Python 2.5+ Python 3.0+ and IronPython 2.6+ * Licensed under the LGPL license, which means that it can be used freely even in commercial programs subject to certain restrictions. * The user can choose between paramstyles: 'qmark' 'named' 'format' 'pyformat' 'dynamic' * Supports data retrieval by column name e.g.: @@ -19,16 +20,20 @@ Features: * Supports user-definable system-to-Python data conversion functions (selected by ADO data type, or by column) Prerequisites: -* C Python 3.6 or higher +* C Python 2.7 or 3.5 or higher and pywin32 (Mark Hammond's python for windows extensions.) +or + Iron Python 2.7 or higher. (works in IPy2.0 for all data types except BUFFER) Installation: * (C-Python on Windows): Install pywin32 ("pip install pywin32") which includes adodbapi. * (IronPython on Windows): Download adodbapi from http://sf.net/projects/adodbapi. Unpack the zip. + Open a command window as an administrator. CD to the folder containing the unzipped files. + Run "setup.py install" using the IronPython of your choice. NOTE: ........... If you do not like the new default operation of returning Numeric columns as decimal.Decimal, -you can select other options by the user defined conversion feature. +you can select other options by the user defined conversion feature. Try: adodbapi.apibase.variantConversions[adodbapi.ado_consts.adNumeric] = adodbapi.apibase.cvtString or: @@ -82,6 +87,6 @@ and look at the test cases in adodbapi/test directory. Mailing lists ------------- The adodbapi mailing lists have been deactivated. Submit comments to the -pywin32 mailing lists. +pywin32 or IronPython mailing lists. -- the bug tracker on sourceforge.net/projects/adodbapi may be checked, (infrequently). -- please use: https://github.com/mhammond/pywin32/issues diff --git a/adodbapi/remote.py b/adodbapi/remote.py index 6caf7a9bbe..ae22b5a7ea 100644 --- a/adodbapi/remote.py +++ b/adodbapi/remote.py @@ -21,9 +21,13 @@ django adaptations and refactoring thanks to Adam Vandenberg DB-API 2.0 specification: http://www.python.org/dev/peps/pep-0249/ + +This module source should run correctly in CPython versions 2.5 and later, +or IronPython version 2.7 and later, +or, after running through 2to3.py, CPython 3.0 or later. """ -__version__ = "3.7.0.0" +__version__ = "2.6.0.4" version = "adodbapi.remote v" + __version__ import array @@ -36,7 +40,7 @@ try: import Pyro4 except ImportError: - print('* * * Sorry, server operation requires Pyro4. Please "pip install" it.') + print('* * * Sorry, server operation requires Pyro4. Please "pip import" it.') exit(11) import adodbapi @@ -44,6 +48,8 @@ import adodbapi.process_connect_string from adodbapi.apibase import ProgrammingError +_BaseException = api._BaseException + sys.excepthook = Pyro4.util.excepthook Pyro4.config.PREFER_IP_VERSION = 0 # allow system to prefer IPv6 Pyro4.config.COMMTIMEOUT = 40.0 # a bit longer than the default SQL server Gtimeout @@ -56,12 +62,16 @@ if verbose: print(version) +# --- define objects to smooth out Python3 <-> Python 2.x differences +unicodeType = str # this line will be altered by 2to3.py to '= str' +longType = int # this line will be altered by 2to3.py to '= int' +StringTypes = str +makeByteBuffer = bytes +memoryViewType = memoryview # ----------------------------------------------------------- # conversion functions mandated by PEP 249 -def Binary(aString): - """This function constructs an object capable of holding a binary (long) string value.""" - return bytes(aString) +Binary = makeByteBuffer # override the function from apibase.py def Date(year, month, day): @@ -158,7 +168,7 @@ def connect(*args, **kwargs): # --> a remote db-api connection object raise api.DatabaseError( "Pyro error creating connection to/thru=%s" % repr(kwargs) ) - except Exception as e: + except _BaseException as e: raise api.DatabaseError( "Error creating remote connection to=%s, e=%s, %s" % (repr(kwargs), repr(e), sys.exc_info()[2]) @@ -178,7 +188,7 @@ def fix_uri(uri, kwargs): # # # # # ----- the Class that defines a connection ----- # # # # # -class Connection: +class Connection(object): # include connection attributes required by api definition. Warning = api.Warning Error = api.Error @@ -358,7 +368,7 @@ def fixpickle(x): # for 'named' paramstyle user will pass a mapping newargs = {} for arg, val in list(x.items()): - if isinstance(val, memoryview): + if isinstance(val, memoryViewType): newval = array.array("B") newval.fromstring(val) newargs[arg] = newval @@ -368,7 +378,7 @@ def fixpickle(x): # if not a mapping, then a sequence newargs = [] for arg in x: - if isinstance(arg, memoryview): + if isinstance(arg, memoryViewType): newarg = array.array("B") newarg.fromstring(arg) newargs.append(newarg) @@ -377,7 +387,7 @@ def fixpickle(x): return newargs -class Cursor: +class Cursor(object): def __init__(self, connection): self.command = None self.errorhandler = None ## was: connection.errorhandler @@ -559,7 +569,7 @@ def callproc(self, procname, parameters=None): def fetchone(self): try: f1 = self.proxy.crsr_fetchone(self.id) - except Exception as e: + except _BaseException as e: self._raiseCursorError(api.DatabaseError, e) else: if f1 is None: diff --git a/adodbapi/remote/server.py b/adodbapi/remote/server.py index e35edf74e3..bfba3a7473 100644 --- a/adodbapi/remote/server.py +++ b/adodbapi/remote/server.py @@ -19,14 +19,16 @@ DB-API 2.0 specification: http://www.python.org/dev/peps/pep-0249/ -This module source should run correctly in CPython 3.2 or later. +This module source should run correctly in CPython versions 2.6 and later, +or IronPython version 2.6 and later, +or, after running through 2to3.py, CPython 3.2 or later. """ -__version__ = "3.7.0.0" +__version__ = "2.6.2.0" version = "adodbapi.server v" + __version__ PYRO_HOST = "::0" # '::0' or '0.0.0.0' means any network -PYRO_PORT = 9099 # may be altered below for Python based servers +PYRO_PORT = 9099 # may be altered below for Python 3 based servers PYRO_COMMTIMEOUT = 40 # to be larger than the default database timeout SERVICE_NAME = "ado.connection" @@ -40,12 +42,15 @@ try: import Pyro4 except ImportError: - print('* * * Sorry, server operation requires Pyro4. Please "pip install" it.') + print('* * * Sorry, server operation requires Pyro4. Please "pip import" it.') exit(11) import adodbapi import adodbapi.apibase as api import adodbapi.process_connect_string +makeByteBuffer = bytes +_BaseException = Exception +Binary = bytes try: pyro_host = os.environ["PYRO_HOST"] except: @@ -59,25 +64,25 @@ if arg.lower().startswith("host"): try: pyro_host = arg.split("=")[1] - except Exception: + except _BaseException: raise TypeError('Must supply value for argument="%s"' % arg) if arg.lower().startswith("port"): try: pyro_port = int(arg.split("=")[1]) - except Exception: + except _BaseException: raise TypeError('Must supply numeric value for argument="%s"' % arg) if arg.lower().startswith("timeout"): try: PYRO_COMMTIMEOUT = int(arg.split("=")[1]) - except Exception: + except _BaseException: raise TypeError('Must supply numeric value for argument="%s"' % arg) if arg.lower().startswith("--verbose"): try: verbose = int(arg.split("=")[1]) - except Exception: + except _BaseException: raise TypeError('Must supply numeric value for argument="%s"' % arg) adodbapi.adodbapi.verbose = verbose else: @@ -92,7 +97,7 @@ Pyro4.config.PREFER_IP_VERSION = 0 # allow system to prefer IPv6 Pyro4.config.SERIALIZERS_ACCEPTED = set( ["serpent", "pickle"] -) # TODO: change when Py2.5 retired +) # change when Py2.5 retired connection_list = [] CONNECTION_TIMEOUT = datetime.timedelta(minutes=30) @@ -114,7 +119,7 @@ def unfixpickle(x): newargs = {} for arg, val in list(x.items()): if isinstance(arg, array.array): - newargs[arg] = bytes(val) + newargs[arg] = Binary(val) else: newargs[arg] = val return newargs @@ -122,13 +127,13 @@ def unfixpickle(x): newargs = [] for arg in x: if isinstance(arg, array.array): - newargs.append(bytes(arg)) + newargs.append(Binary(arg)) else: newargs.append(arg) return newargs -class ServerConnection: +class ServerConnection(object): def __init__(self): self.server_connection = None self.cursors = {} @@ -307,14 +312,14 @@ def suicide(self): print("Shutdown request received") -class ConnectionDispatcher: +class ConnectionDispatcher(object): def make_connection(self): new_connection = ServerConnection() pyro_uri = self._pyroDaemon.register(new_connection) return pyro_uri -class Heartbeat_Timer: +class Heartbeat_Timer(object): def __init__(self, interval, work_function, tick_result_function): self.interval = interval self.last_tick = datetime.datetime.now() diff --git a/adodbapi/setup.py b/adodbapi/setup.py index f0e88d1f11..d25869adf9 100644 --- a/adodbapi/setup.py +++ b/adodbapi/setup.py @@ -1,6 +1,7 @@ """adodbapi -- a pure Python PEP 249 DB-API package using Microsoft ADO Adodbapi can be run on CPython 3.5 and later. +or IronPython version 2.6 and later (in theory, possibly no longer in practice!) """ CLASSIFIERS = """\ Development Status :: 5 - Production/Stable diff --git a/adodbapi/test/adodbapitest.py b/adodbapi/test/adodbapitest.py index f33d29d895..d7a4f2c9bc 100644 --- a/adodbapi/test/adodbapitest.py +++ b/adodbapi/test/adodbapitest.py @@ -26,11 +26,21 @@ import decimal import random import string +import sys import unittest -import adodbapitestconfig as config # run the configuration module. # will set sys.path to find correct version of adodbapi -import tryconnection # in our code below, all our switches are from config.whatever -import win32com.client +try: + import win32com.client + + win32 = True +except ImportError: + win32 = False + +# run the configuration module. +import adodbapitestconfig as config # will set sys.path to find correct version of adodbapi + +# in our code below, all our switches are from config.whatever +import tryconnection import adodbapi import adodbapi.apibase as api @@ -44,6 +54,9 @@ from adodbapi import ado_consts +long = int + + def randomstring(length): return "".join([random.choice(string.ascii_letters) for n in range(32)]) @@ -199,6 +212,49 @@ def testUserDefinedConversions(self): pass self.helpRollbackTblTemp() + def testUserDefinedConversionForExactNumericTypes(self): + # variantConversions is a dictionary of conversion functions + # held internally in adodbapi.apibase + # + # !!! this test intentionally alters the value of what should be constant in the module + # !!! no new code should use this example, to is only a test to see that the + # !!! deprecated way of doing this still works. (use connection.variantConversions) + # + if not self.remote and sys.version_info < (3, 0): ### Py3 need different test + oldconverter = adodbapi.variantConversions[ + ado_consts.adNumeric + ] # keep old function to restore later + # By default decimal and "numbers" are returned as decimals. + # Instead, make numbers return as floats + try: + adodbapi.variantConversions[ado_consts.adNumeric] = adodbapi.cvtFloat + self.helpTestDataType( + "decimal(18,2)", "NUMBER", 3.45, compareAlmostEqual=1 + ) + self.helpTestDataType( + "numeric(18,2)", "NUMBER", 3.45, compareAlmostEqual=1 + ) + # now return strings + adodbapi.variantConversions[ado_consts.adNumeric] = adodbapi.cvtString + self.helpTestDataType("numeric(18,2)", "NUMBER", "3.45") + # now a completly weird user defined convertion + adodbapi.variantConversions[ado_consts.adNumeric] = ( + lambda x: "!!This function returns a funny unicode string %s!!" % x + ) + self.helpTestDataType( + "numeric(18,2)", + "NUMBER", + "3.45", + allowedReturnValues=[ + "!!This function returns a funny unicode string 3.45!!" + ], + ) + finally: + # now reset the converter to its original function + adodbapi.variantConversions[ + ado_consts.adNumeric + ] = oldconverter # Restore the original convertion function + def helpTestDataType( self, sqlDataTypeString, @@ -1465,6 +1521,37 @@ def testIsoFormat(self): self.assertEqual(str(iso[:10]), "2003-05-02") +if config.doMxDateTimeTest: + import mx.DateTime + + +class TestMXDateTimeConverter(TimeConverterInterfaceTest): + def setUp(self): + self.tc = api.mxDateTimeConverter() + + def testCOMDate(self): + t = mx.DateTime.DateTime(2002, 6, 28, 18, 15, 2) + cmd = self.tc.COMDate(t) + assert cmd == t.COMDate() + + def testDateObjectFromCOMDate(self): + cmd = self.tc.DateObjectFromCOMDate(37435.7604282) + t = mx.DateTime.DateTime(2002, 6, 28, 18, 15, 0) + t2 = mx.DateTime.DateTime(2002, 6, 28, 18, 15, 2) + assert t2 > cmd > t + + def testDate(self): + assert mx.DateTime.Date(1980, 11, 4) == self.tc.Date(1980, 11, 4) + + def testTime(self): + assert mx.DateTime.Time(13, 11, 4) == self.tc.Time(13, 11, 4) + + def testTimestamp(self): + t = mx.DateTime.DateTime(2002, 6, 28, 18, 15, 1) + obj = self.tc.Timestamp(2002, 6, 28, 18, 15, 1) + assert t == obj + + import time @@ -1552,8 +1639,11 @@ def testTimestamp(self): suites = [] suites.append(unittest.makeSuite(TestPythonDateTimeConverter, "test")) +if config.doMxDateTimeTest: + suites.append(unittest.makeSuite(TestMXDateTimeConverter, "test")) if config.doTimeTest: suites.append(unittest.makeSuite(TestPythonTimeConverter, "test")) + if config.doAccessTest: suites.append(unittest.makeSuite(TestADOwithAccessDB, "test")) if config.doSqlServerTest: @@ -1564,7 +1654,7 @@ def testTimestamp(self): suites.append(unittest.makeSuite(TestADOwithPostgres, "test")) -class cleanup_manager: +class cleanup_manager(object): def __enter__(self): pass @@ -1583,11 +1673,16 @@ def __exit__(self, exc_type, exc_val, exc_tb): tag = "datetime" unittest.TextTestRunner().run(mysuite) - if config.doTimeTest: - mysuite = copy.deepcopy( - suite - ) # work around a side effect of unittest.TextTestRunner - adodbapi.adodbapi.dateconverter = api.pythonTimeConverter() - print("Changed dateconverter to ") - print(adodbapi.adodbapi.dateconverter) - unittest.TextTestRunner().run(mysuite) + if config.iterateOverTimeTests: + for test, dateconverter, tag in ( + (config.doTimeTest, api.pythonTimeConverter, "pythontime"), + (config.doMxDateTimeTest, api.mxDateTimeConverter, "mx"), + ): + if test: + mysuite = copy.deepcopy( + suite + ) # work around a side effect of unittest.TextTestRunner + adodbapi.adodbapi.dateconverter = dateconverter() + print("Changed dateconverter to ") + print(adodbapi.adodbapi.dateconverter) + unittest.TextTestRunner().run(mysuite) diff --git a/adodbapi/test/adodbapitestconfig.py b/adodbapi/test/adodbapitestconfig.py index e3ec196ced..98f254440e 100644 --- a/adodbapi/test/adodbapitestconfig.py +++ b/adodbapi/test/adodbapitestconfig.py @@ -32,14 +32,14 @@ if "--help" in sys.argv: print( """Valid command-line switches are: - --package - create a temporary test package + --package - create a temporary test package, run 2to3 if needed. --all - run all possible tests - --time - do time format test + --time - loop over time format tests (including mxdatetime if present) --nojet - do not test against an ACCESS database file --mssql - test against Microsoft SQL server --pg - test against PostgreSQL --mysql - test against MariaDB - --remote= - test using remote server at= (experimental) + --remote= - test unsing remote server at= (experimental) """ ) exit() @@ -77,8 +77,13 @@ # function to clean up the temporary folder -- calling program must run this function before exit. cleanup = setuptestframework.getcleanupfunction() -import adodbapi # will (hopefully) be imported using the "pth" discovered above - +try: + import adodbapi # will (hopefully) be imported using the "pth" discovered above +except SyntaxError: + print( + '\n* * * Are you trying to run Python2 code using Python3? Re-run this test using the "--package" switch.' + ) + sys.exit(11) try: print(adodbapi.version) # show version except: @@ -101,12 +106,21 @@ doSqlServerTest = "--mssql" in sys.argv or doAllTests doMySqlTest = "--mysql" in sys.argv or doAllTests doPostgresTest = "--pg" in sys.argv or doAllTests -doTimeTest = ("--time" in sys.argv or doAllTests) and onWindows +iterateOverTimeTests = ("--time" in sys.argv or doAllTests) and onWindows # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # start your environment setup here v v v SQL_HOST_NODE = "testsql.2txt.us,1430" +try: # If mx extensions are installed, use mxDateTime + import mx.DateTime + + doMxDateTimeTest = True +except: + doMxDateTimeTest = False # Requires eGenixMXExtensions + +doTimeTest = True # obsolete python time format + if doAccessTest: if proxy_host: # determine the (probably remote) database file folder c = {"macro_find_temp_test_path": ["mdb", mdb_name], "proxy_host": proxy_host} diff --git a/adodbapi/test/dbapi20.py b/adodbapi/test/dbapi20.py index e4f7b55829..5f983cdc8d 100644 --- a/adodbapi/test/dbapi20.py +++ b/adodbapi/test/dbapi20.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -""" Python DB API 2.0 driver compliance unit test suite. - +""" Python DB API 2.0 driver compliance unit test suite. + This software is Public Domain and may be used without restrictions. "Now we have booze and barflies entering the discussion, plus rumours of @@ -11,23 +11,29 @@ -- Ian Bicking """ -__version__ = "$Revision: 1.16.0 $"[11:-2] +__version__ = "$Revision: 1.15.0 $"[11:-2] __author__ = "Stuart Bishop " +import sys import time import unittest +if sys.version[0] >= "3": # python 3.x + _BaseException = Exception + + def _failUnless(self, expr, msg=None): + self.assertTrue(expr, msg) + +else: # python 2.x + from exceptions import Exception as _BaseException -def _failUnless(self, expr, msg=None): - self.assertTrue(expr, msg) + def _failUnless(self, expr, msg=None): + self.failUnless(expr, msg) ## deprecated since Python 2.6 # set this to "True" to follow API 2.0 to the letter TEST_FOR_NON_IDEMPOTENT_CLOSE = False -# Revision 1.16 2022/12/07 22:00:00 Avasam -# Drop support for EOL Python 3.6 and below - # Revision 1.15 2019/11/22 00:50:00 kf7xm # Make Turn off IDEMPOTENT_CLOSE a proper skipTest @@ -160,7 +166,7 @@ def tearDown(self): pass finally: con.close() - except Exception: + except _BaseException: pass def _connect(self): @@ -206,8 +212,12 @@ def test_paramstyle(self): def test_Exceptions(self): # Make sure required exceptions exist, and are in the # defined heirarchy. - self.assertTrue(issubclass(self.driver.Warning, Exception)) - self.assertTrue(issubclass(self.driver.Error, Exception)) + if sys.version[0] == "3": # under Python 3 StardardError no longer exists + self.assertTrue(issubclass(self.driver.Warning, Exception)) + self.assertTrue(issubclass(self.driver.Error, Exception)) + else: + self.failUnless(issubclass(self.driver.Warning, Exception)) + self.failUnless(issubclass(self.driver.Error, Exception)) _failUnless(self, issubclass(self.driver.InterfaceError, self.driver.Error)) _failUnless(self, issubclass(self.driver.DatabaseError, self.driver.Error)) diff --git a/adodbapi/test/is64bit.py b/adodbapi/test/is64bit.py index 339bdaaa6f..ed390fad00 100644 --- a/adodbapi/test/is64bit.py +++ b/adodbapi/test/is64bit.py @@ -3,14 +3,22 @@ def Python(): - return sys.maxsize > 2147483647 + if sys.platform == "cli": # IronPython + import System + + return System.IntPtr.Size == 8 + else: + try: + return sys.maxsize > 2147483647 + except AttributeError: + return sys.maxint > 2147483647 def os(): import platform pm = platform.machine() - if pm != ".." and pm.endswith("64"): # recent 64 bit Python + if pm != ".." and pm.endswith("64"): # recent Python (not Iron) return True else: import os diff --git a/adodbapi/test/setuptestframework.py b/adodbapi/test/setuptestframework.py index 90d1fd740a..83fe5ca9db 100644 --- a/adodbapi/test/setuptestframework.py +++ b/adodbapi/test/setuptestframework.py @@ -1,10 +1,16 @@ -#!/usr/bin/python3 +#!/usr/bin/python2 # Configure this in order to run the testcases. -"setuptestframework.py v 3.7.0.0" +"setuptestframework.py v 2.6.0.8" import os import shutil +import sys import tempfile +try: + OSErrors = (WindowsError, OSError) +except NameError: # not running on Windows + OSErrors = OSError + def maketemp(): temphome = tempfile.gettempdir() @@ -46,14 +52,20 @@ def makeadopackage(testfolder): newpackage = os.path.join(testfolder, "adodbapi") try: os.mkdir(newpackage) - except (WindowsError, OSError): + except OSErrors: print( "*Note: temporary adodbapi package already exists: may be two versions running?" ) for f in os.listdir(adoPath): if f.endswith(".py"): shutil.copy(os.path.join(adoPath, f), newpackage) + if sys.version_info >= (3, 0): # only when running Py3.n + save = sys.stdout + sys.stdout = None + from lib2to3.main import main # use 2to3 to make test package + main("lib2to3.fixes", args=["-n", "-w", newpackage]) + sys.stdout = save return testfolder else: raise EnvironmentError("Connot find source of adodbapi to test.") @@ -68,23 +80,41 @@ def makemdb(testfolder, mdb_name): if os.path.isfile(_accessdatasource): print("using JET database=", _accessdatasource) else: - from win32com.client import constants - from win32com.client.gencache import EnsureDispatch + try: + from win32com.client import constants + from win32com.client.gencache import EnsureDispatch + + win32 = True + except ImportError: # perhaps we are running IronPython + win32 = False # iron Python + try: + from System import Activator, Type + except: + pass # Create a brand-new database - what is the story with these? dbe = None for suffix in (".36", ".35", ".30"): try: - dbe = EnsureDispatch("DAO.DBEngine" + suffix) + if win32: + dbe = EnsureDispatch("DAO.DBEngine" + suffix) + else: + type = Type.GetTypeFromProgID("DAO.DBEngine" + suffix) + dbe = Activator.CreateInstance(type) break except: pass if dbe: print(" ...Creating ACCESS db at " + _accessdatasource) - workspace = dbe.Workspaces(0) - newdb = workspace.CreateDatabase( - _accessdatasource, constants.dbLangGeneral, constants.dbVersion40 - ) + if win32: + workspace = dbe.Workspaces(0) + newdb = workspace.CreateDatabase( + _accessdatasource, constants.dbLangGeneral, constants.dbVersion40 + ) + else: + newdb = dbe.CreateDatabase( + _accessdatasource, ";LANGID=0x0409;CP=1252;COUNTRY=0" + ) newdb.Close() else: print(" ...copying test ACCESS db to " + _accessdatasource) From 0ecc5ab268c152b43d2baa21ffdcd3c360fd13a6 Mon Sep 17 00:00:00 2001 From: Avasam Date: Tue, 8 Aug 2023 21:27:06 -0400 Subject: [PATCH 21/24] Update Pythonwin/Scintilla/src/LexGen.py --- Pythonwin/Scintilla/src/LexGen.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Pythonwin/Scintilla/src/LexGen.py b/Pythonwin/Scintilla/src/LexGen.py index 0594f70659..2c227aacf4 100644 --- a/Pythonwin/Scintilla/src/LexGen.py +++ b/Pythonwin/Scintilla/src/LexGen.py @@ -4,7 +4,7 @@ # Regenerate the Scintilla and SciTE source files that list # all the lexers and all the properties files. # Should be run whenever a new lexer is added or removed. -# Requires Python 3.0 or later +# Requires Python 2.4 or later # Most files are regenerated in place with templates stored in comments. # The VS .NET project file is generated into a different file as the # VS .NET environment will not retain comments when modifying the file. From 0ed39d0752b9633487fbb338b8207b79055605b8 Mon Sep 17 00:00:00 2001 From: Avasam Date: Wed, 9 Aug 2023 13:16:30 -0400 Subject: [PATCH 22/24] Address some PR comments --- Pythonwin/Scintilla/src/LexGen.py | 4 +--- Pythonwin/pywin/framework/app.py | 3 +-- Pythonwin/pywin/mfc/dialog.py | 6 +++--- com/win32com/client/build.py | 1 - com/win32comext/axscript/test/testHost.py | 7 +++---- com/win32comext/taskscheduler/test/test_addtask_1.py | 3 +-- setup.py | 1 - win32/Lib/winnt.py | 6 +++--- 8 files changed, 12 insertions(+), 19 deletions(-) diff --git a/Pythonwin/Scintilla/src/LexGen.py b/Pythonwin/Scintilla/src/LexGen.py index 0594f70659..c635e509ac 100644 --- a/Pythonwin/Scintilla/src/LexGen.py +++ b/Pythonwin/Scintilla/src/LexGen.py @@ -201,9 +201,7 @@ def FindProperties(lexFile): def ciCompare(a, b): - a_lower = a.lower() - b_lower = b.lower() - return (a_lower > b_lower) - (a_lower < b_lower) + return cmp(a.lower(), b.lower()) def RegenerateAll(): diff --git a/Pythonwin/pywin/framework/app.py b/Pythonwin/pywin/framework/app.py index 53fea9337c..298a79b4fb 100644 --- a/Pythonwin/pywin/framework/app.py +++ b/Pythonwin/pywin/framework/app.py @@ -430,8 +430,7 @@ def HaveGoodGUI(): def CreateDefaultGUI(appClass=None): """Creates a default GUI environment""" if appClass is None: - # Bring in the default app - could be param'd later. - from . import intpyapp + from . import intpyapp # Bring in the default app - could be param'd later. appClass = intpyapp.InteractivePythonApp # Create and init the app. diff --git a/Pythonwin/pywin/mfc/dialog.py b/Pythonwin/pywin/mfc/dialog.py index 6118972495..280c025aa1 100644 --- a/Pythonwin/pywin/mfc/dialog.py +++ b/Pythonwin/pywin/mfc/dialog.py @@ -90,11 +90,11 @@ def items(self): def values(self): return list(self.data.values()) - # TODO - # 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/com/win32com/client/build.py b/com/win32com/client/build.py index 09c59513fa..84dacb566a 100644 --- a/com/win32com/client/build.py +++ b/com/win32com/client/build.py @@ -629,7 +629,6 @@ def _BuildArgList(fdesc, names): names.append("arg%d" % (len(names),)) # As per BuildCallList(), avoid huge lines. # Hack a "\n" at the end of every 5th name - # TODO: "strides" would be handy here but don't exist in 2.2 for i in range(0, len(names), 5): names[i] = names[i] + "\n\t\t\t" return "," + ", ".join(names) diff --git a/com/win32comext/axscript/test/testHost.py b/com/win32comext/axscript/test/testHost.py index 466a484707..9503706903 100644 --- a/com/win32comext/axscript/test/testHost.py +++ b/com/win32comext/axscript/test/testHost.py @@ -134,10 +134,9 @@ def testcollection(): test.fail("Didn't get the collection") pass """ -# TODO -# 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! +# Throwing a bytes string with an extended char doesn't make much sense, +# but Python 2 allowed it. What it gets upset with +# is a real unicode arg - which is the only thing Python 3 allows! PyScript_Exc = """\ def hello(arg1): raise RuntimeError("exc with extended \xa9har") diff --git a/com/win32comext/taskscheduler/test/test_addtask_1.py b/com/win32comext/taskscheduler/test/test_addtask_1.py index fa4cf5067e..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:\\python37\\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:\\Python37") 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/setup.py b/setup.py index 0ca4c61743..ff02296cca 100644 --- a/setup.py +++ b/setup.py @@ -814,7 +814,6 @@ def swig_sources(self, sources, ext=None): new_sources = [] swig_sources = [] swig_targets = {} - # TODO # XXX this drops generated C/C++ files into the source tree, which # is fine for developers who want to distribute the generated # source -- but there should be an option to put SWIG output in diff --git a/win32/Lib/winnt.py b/win32/Lib/winnt.py index f4319cd939..e997527c97 100644 --- a/win32/Lib/winnt.py +++ b/win32/Lib/winnt.py @@ -180,15 +180,15 @@ def SORTIDFROMLCID(lcid): def UNREFERENCED_PARAMETER(P): - return P + return def DBG_UNREFERENCED_PARAMETER(P): - return P + return def DBG_UNREFERENCED_LOCAL_VARIABLE(V): - return V + return MAXIMUM_WAIT_OBJECTS = 64 From 44c3a53e3550a325e76a1ea75a66b956298b233c Mon Sep 17 00:00:00 2001 From: Avasam Date: Wed, 9 Aug 2023 15:29:31 -0400 Subject: [PATCH 23/24] More PR comments --- Pythonwin/pywin/idle/readme.txt | 14 ++++++-------- com/win32comext/axscript/test/testHost.py | 11 ----------- win32/Lib/winnt.py | 20 ++++---------------- 3 files changed, 10 insertions(+), 35 deletions(-) diff --git a/Pythonwin/pywin/idle/readme.txt b/Pythonwin/pywin/idle/readme.txt index 9f4f9fddcf..9a28195a22 100644 --- a/Pythonwin/pywin/idle/readme.txt +++ b/Pythonwin/pywin/idle/readme.txt @@ -2,16 +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 3.7 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/com/win32comext/axscript/test/testHost.py b/com/win32comext/axscript/test/testHost.py index 9503706903..466bdb3ac5 100644 --- a/com/win32comext/axscript/test/testHost.py +++ b/com/win32comext/axscript/test/testHost.py @@ -134,13 +134,6 @@ def testcollection(): test.fail("Didn't get the collection") pass """ -# Throwing a bytes string with an extended char doesn't make much sense, -# but Python 2 allowed it. What it gets upset with -# is a real unicode arg - which is the only thing Python 3 allows! -PyScript_Exc = """\ -def hello(arg1): - raise RuntimeError("exc with extended \xa9har") -""" ErrScript = """\ bad code for everyone! @@ -247,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/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 From 6b60a57a9118b3b3271af2b467d8453a6ae8d4ec Mon Sep 17 00:00:00 2001 From: Avasam Date: Wed, 9 Aug 2023 15:39:02 -0400 Subject: [PATCH 24/24] Remove todo comment we won't touch --- setup.py | 1 - 1 file changed, 1 deletion(-) diff --git a/setup.py b/setup.py index ff02296cca..ecaa7a692b 100644 --- a/setup.py +++ b/setup.py @@ -879,7 +879,6 @@ def swig_sources(self, sources, ext=None): # A class deriving from other than the default swig_cmd.extend(["-com_interface_parent", interface_parent]) - # TODO # This 'newer' check helps python 2.2 builds, which otherwise # *always* regenerate the .cpp files, meaning every future # build for any platform sees these as dirty.