From 605ee2d32d2210e75aec38e152556d68b3aff24e Mon Sep 17 00:00:00 2001 From: Avasam Date: Wed, 16 Oct 2024 02:18:59 -0400 Subject: [PATCH] Remove __file__ try-catch hack + Comment about __file__ always being absolute in 3.9 --- Pythonwin/pywin/test/_exetestscript.py | 7 ++++--- Pythonwin/pywin/test/all.py | 4 ++-- Pythonwin/pywin/test/test_exe.py | 4 ++-- Pythonwin/pywin/test/test_pywin.py | 8 ++++---- adodbapi/test/setuptestframework.py | 3 ++- com/win32com/test/pippo_server.py | 5 +++-- com/win32com/test/testall.py | 19 +++++++++--------- .../shell/demos/servers/empty_volume_cache.py | 3 ++- isapi/install.py | 4 ++-- setup.py | 20 ++++++------------- win32/Demos/win32rcparser_demo.py | 8 ++++---- win32/test/test_clipboard.py | 11 +++------- win32/test/test_win32api.py | 17 +++++----------- win32/test/test_win32trace.py | 9 +-------- win32/test/testall.py | 11 ++++------ 15 files changed, 53 insertions(+), 80 deletions(-) diff --git a/Pythonwin/pywin/test/_exetestscript.py b/Pythonwin/pywin/test/_exetestscript.py index ef59d4036..b9fd7098f 100644 --- a/Pythonwin/pywin/test/_exetestscript.py +++ b/Pythonwin/pywin/test/_exetestscript.py @@ -21,8 +21,9 @@ _clock = time.perf_counter print("Start!", file=out) mf = win32ui.GetMainFrame() - file_abs = os.path.abspath(__file__) - src_dir = os.path.dirname(file_abs) + + __file__ = os.path.abspath(__file__) # __file__ can be relative before Python 3.9 + src_dir = os.path.dirname(__file__) # open a source file some_fn = src_dir + "\\_dbgscript.py" @@ -35,7 +36,7 @@ scriptutils.JumpToDocument(__file__) win32ui.PumpWaitingMessages(0, -1) v = scriptutils.GetActiveEditControl() - assert file_abs == v.GetDocument().GetPathName() + assert __file__ == v.GetDocument().GetPathName() t = v.GetTextRange() assert "t = v.GetTextRange()" in t print("Success!") diff --git a/Pythonwin/pywin/test/all.py b/Pythonwin/pywin/test/all.py index f1eaaf894..aabfaf8ec 100644 --- a/Pythonwin/pywin/test/all.py +++ b/Pythonwin/pywin/test/all.py @@ -10,8 +10,8 @@ user_interaction = False _indebugger = "pywin.debugger" in sys.modules -file_abs = os.path.abspath(__file__) -src_dir = os.path.dirname(file_abs) +__file__ = os.path.abspath(__file__) # __file__ can be relative before Python 3.9 +src_dir = os.path.dirname(__file__) if __name__ == "__main__": diff --git a/Pythonwin/pywin/test/test_exe.py b/Pythonwin/pywin/test/test_exe.py index d545bc636..0f93e4200 100644 --- a/Pythonwin/pywin/test/test_exe.py +++ b/Pythonwin/pywin/test/test_exe.py @@ -14,8 +14,8 @@ user_interaction = False _indebugger = "pywin.debugger" in sys.modules -file_abs = os.path.abspath(__file__) -src_dir = os.path.dirname(file_abs) +__file__ = os.path.abspath(__file__) # __file__ can be relative before Python 3.9 +src_dir = os.path.dirname(__file__) pythonwinexe_path = os.path.dirname(win32ui.__file__) + "\\Pythonwin.exe" diff --git a/Pythonwin/pywin/test/test_pywin.py b/Pythonwin/pywin/test/test_pywin.py index 6cf973a92..c8f474b3c 100644 --- a/Pythonwin/pywin/test/test_pywin.py +++ b/Pythonwin/pywin/test/test_pywin.py @@ -20,8 +20,8 @@ from pywin.framework import scriptutils user_interaction = getattr(__main__, "user_interaction", False) # from all.py maybe -file_abs = os.path.abspath(__file__) -src_dir = os.path.dirname(file_abs) +__file__ = os.path.abspath(__file__) # __file__ can be relative before Python 3.9 +src_dir = os.path.dirname(__file__) pywin_path = next(iter(pywin.__path__)) pythonwinpy_path = os.path.dirname(pywin_path) + "\\start_pythonwin.py" Object = argparse.Namespace @@ -72,7 +72,7 @@ def test_1_pydocs_and_finddlg(self): # open a source file some_fn = src_dir + "\\_dbgscript.py" - self.assertNotEqual(some_fn, file_abs) + self.assertNotEqual(some_fn, __file__) scriptutils.JumpToDocument(some_fn) a = scriptutils.GetActiveFileName() self.assertEqual(some_fn, a) @@ -87,7 +87,7 @@ def test_1_pydocs_and_finddlg(self): f"Hello from test_pydocs() args={sys.argv} {os.getcwd()}" ) v = scriptutils.GetActiveEditControl() - self.assertEqual(file_abs, v.GetDocument().GetPathName()) + self.assertEqual(__file__, v.GetDocument().GetPathName()) t = v.GetTextRange() testpat = "self.app = thisApp" self.assertIn(testpat, t) diff --git a/adodbapi/test/setuptestframework.py b/adodbapi/test/setuptestframework.py index 65b99e990..8863d9205 100644 --- a/adodbapi/test/setuptestframework.py +++ b/adodbapi/test/setuptestframework.py @@ -1,6 +1,7 @@ #!/usr/bin/python2 # Configure this in order to run the testcases. "setuptestframework.py v 2.6.0.8" + import os import shutil import tempfile @@ -87,7 +88,7 @@ def makemdb(testfolder, mdb_name): newdb.Close() else: print(" ...copying test ACCESS db to " + _accessdatasource) - mdbName = os.path.abspath( + mdbName = os.path.abspath( # __file__ can be relative before Python 3.9 os.path.join(os.path.dirname(__file__), "..", "examples", "test.mdb") ) import shutil diff --git a/com/win32com/test/pippo_server.py b/com/win32com/test/pippo_server.py index c5ae2df40..20a87678f 100644 --- a/com/win32com/test/pippo_server.py +++ b/com/win32com/test/pippo_server.py @@ -46,8 +46,9 @@ def BuildTypelib(): else: from distutils.dep_util import newer - this_dir = os.path.dirname(__file__) - idl = os.path.abspath(os.path.join(this_dir, "pippo.idl")) + # __file__ can be relative before Python 3.9 + this_dir = os.path.dirname(os.path.abspath(__file__)) + idl = os.path.join(this_dir, "pippo.idl") tlb = os.path.splitext(idl)[0] + ".tlb" if newer(idl, tlb): print(f"Compiling {idl}") diff --git a/com/win32com/test/testall.py b/com/win32com/test/testall.py index db30a0a8e..883841083 100644 --- a/com/win32com/test/testall.py +++ b/com/win32com/test/testall.py @@ -5,20 +5,19 @@ import traceback import unittest -try: - this_file = __file__ -except NameError: - this_file = sys.argv[0] - -win32com_src_dir = os.path.abspath(os.path.join(this_file, "../..")) - import win32com # We'd prefer the win32com namespace to be the parent of __file__ - ie, our source-tree, # rather than the version installed - otherwise every .py change needs a full install to # test! +# TODO: That sounds like a use-case for editable installs ! # We can't patch win32comext as most of them have a .pyd in their root :( -# This clearly ins't ideal or perfect :) +# This clearly isn't ideal or perfect :) +win32com_src_dir = os.path.dirname( + os.path.dirname( + os.path.abspath(__file__) # __file__ can be relative before Python 3.9 + ) +) win32com.__path__[0] = win32com_src_dir import pythoncom @@ -99,7 +98,7 @@ def testit(self): # Execute testPyComTest in its own process so it can play # with the Python thread state - fname = os.path.join(os.path.dirname(this_file), "testPyComTest.py") + fname = os.path.join(os.path.dirname(__file__), "testPyComTest.py") cmd = f'{sys.executable} "{fname}" -q 2>&1' data = ExecuteSilentlyIfOK(cmd, self) @@ -112,7 +111,7 @@ def testit(self): RegisterPythonServer(pippo_server.__file__, "Python.Test.Pippo") python = sys.executable - fname = os.path.join(os.path.dirname(this_file), "testPippo.py") + fname = os.path.join(os.path.dirname(__file__), "testPippo.py") cmd = f'{python} "{fname}" 2>&1' ExecuteSilentlyIfOK(cmd, self) diff --git a/com/win32comext/shell/demos/servers/empty_volume_cache.py b/com/win32comext/shell/demos/servers/empty_volume_cache.py index b5fb32e15..902af2144 100644 --- a/com/win32comext/shell/demos/servers/empty_volume_cache.py +++ b/com/win32comext/shell/demos/servers/empty_volume_cache.py @@ -76,7 +76,8 @@ def InitializeEx(self, hkey, volume, key_name, flags): ) def _GetDirectories(self): - root_dir = os.path.abspath(os.path.dirname(os.path.dirname(win32gui.__file__))) + # __file__ can be relative before Python 3.9 + root_dir = os.path.dirname(os.path.dirname(os.path.abspath(win32gui.__file__))) if self.volume is not None and not root_dir.lower().startswith( self.volume.lower() ): diff --git a/isapi/install.py b/isapi/install.py index aa861bbfc..42d1bcd3e 100644 --- a/isapi/install.py +++ b/isapi/install.py @@ -40,8 +40,8 @@ _DEFAULT_CONTENT_INDEXED = False _DEFAULT_ENABLE_DIR_BROWSING = False _DEFAULT_ENABLE_DEFAULT_DOC = False - -this_dir = os.path.abspath(os.path.dirname(__file__)) +# __file__ can be relative before Python 3.9 +this_dir = os.path.dirname(os.path.abspath(__file__)) class FilterParameters: diff --git a/setup.py b/setup.py index ce0120e24..6496481a0 100644 --- a/setup.py +++ b/setup.py @@ -62,16 +62,11 @@ ) print("Building pywin32", pywin32_version) -try: - this_file = __file__ -except NameError: - this_file = sys.argv[0] - -this_file = os.path.abspath(this_file) +__file__ = os.path.abspath(__file__) # __file__ can be relative before Python 3.9 +project_root = Path(__file__).parent # We get upset if the cwd is not our source dir, but it is a PITA to # insist people manually CD there first! -if os.path.dirname(this_file): - os.chdir(os.path.dirname(this_file)) +os.chdir(project_root) # Start address we assign base addresses from. See comment re # dll_base_address later in this file... @@ -971,7 +966,7 @@ def link( args = [ sys.executable, # NOTE: On Python 3.7, all args must be str - str(Path(__file__).parent / "win32" / "Lib" / "win32verstamp.py"), + str(project_root / "win32" / "Lib" / "win32verstamp.py"), f"--version={pywin32_version}", "--comments=https://github.com/mhammond/pywin32", f"--original-filename={os.path.basename(output_filename)}", @@ -2196,11 +2191,8 @@ def maybe_fixup_exes(): ) long_description_content_type = "text/plain" else: - # For wheels, the readme makes more sense as pypi does something sane - # with it. - my_dir = os.path.abspath(os.path.dirname(__file__)) - with open(os.path.join(my_dir, "README.md")) as f: - long_description = f.read() + # For wheels, the readme makes more sense as pypi does something sane with it. + long_description = (project_root / "README.md").read_text() long_description_content_type = "text/markdown" dist = setup( diff --git a/win32/Demos/win32rcparser_demo.py b/win32/Demos/win32rcparser_demo.py index 8f88e3dd6..7688fd71e 100644 --- a/win32/Demos/win32rcparser_demo.py +++ b/win32/Demos/win32rcparser_demo.py @@ -8,10 +8,10 @@ import win32gui import win32rcparser -this_dir = os.path.abspath(os.path.dirname(__file__)) -g_rcname = os.path.abspath( - os.path.join(this_dir, "..", "test", "win32rcparser", "test.rc") -) +# __file__ can be relative before Python 3.9 +this_dir = os.path.dirname(os.path.abspath(__file__)) +g_rcname = os.path.join(os.path.dirname(this_dir), "test", "win32rcparser", "test.rc") + if not os.path.isfile(g_rcname): raise RuntimeError(f"Can't locate test.rc (should be at '{g_rcname}')") diff --git a/win32/test/test_clipboard.py b/win32/test/test_clipboard.py index 0c89d4bab..8ff31277b 100644 --- a/win32/test/test_clipboard.py +++ b/win32/test/test_clipboard.py @@ -41,14 +41,9 @@ class crasher: class TestBitmap(unittest.TestCase): def setUp(self): self.bmp_handle = None - try: - this_file = __file__ - except NameError: - this_file = sys.argv[0] - this_dir = os.path.dirname(this_file) - self.bmp_name = os.path.join( - os.path.abspath(this_dir), "..", "Demos", "images", "smiley.bmp" - ) + # __file__ can be relative before Python 3.9 + this_dir = os.path.dirname(os.path.abspath(__file__)) + self.bmp_name = os.path.join(this_dir, "..", "Demos", "images", "smiley.bmp") self.assertTrue(os.path.isfile(self.bmp_name), self.bmp_name) flags = win32con.LR_DEFAULTSIZE | win32con.LR_LOADFROMFILE self.bmp_handle = win32gui.LoadImage( diff --git a/win32/test/test_win32api.py b/win32/test/test_win32api.py index 446315f54..fd0c8053f 100644 --- a/win32/test/test_win32api.py +++ b/win32/test/test_win32api.py @@ -2,7 +2,6 @@ import datetime import os -import sys import tempfile import time import unittest @@ -141,11 +140,8 @@ def change(): class FileNames(unittest.TestCase): def testShortLongPathNames(self): - try: - me = __file__ - except NameError: - me = sys.argv[0] - fname = os.path.abspath(me).lower() + # __file__ can be relative before Python 3.9 + fname = os.path.abspath(__file__).lower() short_name = win32api.GetShortPathName(fname).lower() long_name = win32api.GetLongPathName(short_name).lower() self.assertTrue( @@ -164,13 +160,10 @@ def testShortLongPathNames(self): ) def testShortUnicodeNames(self): - try: - me = __file__ - except NameError: - me = sys.argv[0] - fname = os.path.abspath(me).lower() + # __file__ can be relative before Python 3.9 + fname = os.path.abspath(__file__).lower() # passing unicode should cause GetShortPathNameW to be called. - short_name = win32api.GetShortPathName(str(fname)).lower() + short_name = win32api.GetShortPathName(fname).lower() self.assertTrue(isinstance(short_name, str)) long_name = win32api.GetLongPathName(short_name).lower() self.assertTrue( diff --git a/win32/test/test_win32trace.py b/win32/test/test_win32trace.py index 8cd79dbf3..879e3e9be 100644 --- a/win32/test/test_win32trace.py +++ b/win32/test/test_win32trace.py @@ -7,11 +7,6 @@ import win32trace from pywin32_testutil import TestSkipped -if __name__ == "__main__": - this_file = sys.argv[0] -else: - this_file = __file__ - def SkipIfCI(): # This test often fails in CI, probably when it is being run multiple times @@ -258,9 +253,7 @@ def __init__(self, threadCount): def start(self): procHandle, threadHandle, procId, threadId = win32process.CreateProcess( None, # appName - 'python.exe "{}" /run_test_process {} {}'.format( - this_file, self.BucketCount, self.threadCount - ), + f'python.exe "{__file__}" /run_test_process {self.BucketCount} {self.threadCount}', None, # process security None, # thread security 0, # inherit handles diff --git a/win32/test/testall.py b/win32/test/testall.py index 7862bc6f5..0d6e6ea53 100644 --- a/win32/test/testall.py +++ b/win32/test/testall.py @@ -6,6 +6,8 @@ import pywin32_testutil +__file__ = os.path.abspath(__file__) # __file__ can be relative before Python 3.9 + # A list of demos that depend on user-interface of *any* kind. Tests listed # here are not suitable for unattended testing. ui_demos = """GetSaveFileName print_desktop win32cred_demo win32gui_demo @@ -160,17 +162,12 @@ def import_all(): def suite(): # Loop over all .py files here, except me :) - try: - me = __file__ - except NameError: - me = sys.argv[0] - me = os.path.abspath(me) - files = os.listdir(os.path.dirname(me)) + files = os.listdir(os.path.dirname(__file__)) suite = unittest.TestSuite() suite.addTest(unittest.FunctionTestCase(import_all)) for file in files: base, ext = os.path.splitext(file) - if ext == ".py" and os.path.basename(me) != file: + if ext == ".py" and os.path.basename(__file__) != file: try: mod = __import__(base) except: