Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove __file__ try-catch hack + Comment about __file__ always being absolute in 3.9 #2410

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions Pythonwin/pywin/test/_exetestscript.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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!")
Expand Down
4 changes: 2 additions & 2 deletions Pythonwin/pywin/test/all.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__":
Expand Down
4 changes: 2 additions & 2 deletions Pythonwin/pywin/test/test_exe.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"


Expand Down
8 changes: 4 additions & 4 deletions Pythonwin/pywin/test/test_pywin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion adodbapi/test/setuptestframework.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions com/win32com/test/pippo_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand Down
19 changes: 9 additions & 10 deletions com/win32com/test/testall.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 !
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ref #2208

# 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
Expand Down Expand Up @@ -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)

Expand All @@ -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)

Expand Down
3 changes: 2 additions & 1 deletion com/win32comext/shell/demos/servers/empty_volume_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
):
Expand Down
4 changes: 2 additions & 2 deletions isapi/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
20 changes: 6 additions & 14 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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...
Expand Down Expand Up @@ -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)}",
Expand Down Expand Up @@ -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(
Expand Down
8 changes: 4 additions & 4 deletions win32/Demos/win32rcparser_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}')")
Expand Down
11 changes: 3 additions & 8 deletions win32/test/test_clipboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
17 changes: 5 additions & 12 deletions win32/test/test_win32api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import datetime
import os
import sys
import tempfile
import time
import unittest
Expand Down Expand Up @@ -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(
Expand All @@ -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(
Expand Down
9 changes: 1 addition & 8 deletions win32/test/test_win32trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
11 changes: 4 additions & 7 deletions win32/test/testall.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
Loading