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

Prefer os.path.exists over os.stat try-catch #2463

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
6 changes: 2 additions & 4 deletions AutoDuck/fixHelpCompression.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@

fname = sys.argv[1]

try:
os.stat(fname)
except OSError:
sys.stderr.write("The project file '%s' was not found\n" % (fname))
if not os.path.exists(fname):
sys.stderr.write(f"The project file '{fname}' was not found\n")
sys.exit(1)

win32api.WriteProfileVal("options", "COMPRESS", "12 Hall Zeck", fname)
7 changes: 2 additions & 5 deletions Pythonwin/pywin/Demos/hiertest.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,12 +101,9 @@ def __init__(self, filename):

def GetText(self):
try:
return "%-20s %d bytes" % (
os.path.basename(self.filename),
os.stat(self.filename)[6],
)
return f"{os.path.basename(self.filename):<20} {os.stat(self.filename)[6]} bytes"
except OSError as details:
return "%-20s - %s" % (self.filename, details[1])
return f"{self.filename:<20} - {details[1]}"

def IsExpandable(self):
return os.path.isdir(self.filename)
Expand Down
9 changes: 3 additions & 6 deletions Pythonwin/pywin/framework/scriptutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,10 +284,9 @@ def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None):
# If no path specified, try and locate the file
path, fnameonly = os.path.split(script)
if len(path) == 0:
try:
os.stat(fnameonly) # See if it is OK as is...
if os.path.exists(fnameonly): # See if it is OK as is...
script = fnameonly
except OSError:
else:
fullScript = LocatePythonFile(script)
if fullScript is None:
win32ui.MessageBox("The file '%s' can not be located" % script)
Expand Down Expand Up @@ -637,9 +636,7 @@ def FindTabNanny():
print(" The file '%s' can not be located" % (filename))
return None
fname = os.path.join(path, "Tools\\Scripts\\%s" % filename)
try:
os.stat(fname)
except OSError:
if not os.path.exists(fname):
print(f"WARNING - The file '{filename}' can not be located in path '{path}'")
return None

Expand Down
12 changes: 3 additions & 9 deletions com/win32com/client/gencache.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,15 +168,9 @@ def GetGeneratePath():
Checks the directory is OK.
"""
assert not is_readonly, "Why do you want the genpath for a readonly store?"
try:
os.makedirs(win32com.__gen_path__)
# os.mkdir(win32com.__gen_path__)
except OSError:
pass
try:
fname = os.path.join(win32com.__gen_path__, "__init__.py")
os.stat(fname)
except OSError:
os.makedirs(win32com.__gen_path__, exist_ok=True)
fname = os.path.join(win32com.__gen_path__, "__init__.py")
if not os.path.exists(fname):
f = open(fname, "w")
f.write(
"# Generated file - this directory may be deleted to reset the COM cache...\n"
Expand Down
8 changes: 2 additions & 6 deletions com/win32com/server/register.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,18 +133,14 @@ def _find_localserver_module():
path = next(iter(win32com.server.__path__))
baseName = "localserver"
pyfile = os.path.join(path, baseName + ".py")
try:
os.stat(pyfile)
except OSError:
if not os.path.exists(pyfile):
# See if we have a compiled extension
if __debug__:
ext = ".pyc"
else:
ext = ".pyo"
pyfile = os.path.join(path, baseName + ext)
try:
os.stat(pyfile)
except OSError:
if not os.path.exists(pyfile):
raise RuntimeError(
"Can not locate the Python module 'win32com.server.%s'" % baseName
)
Expand Down
5 changes: 1 addition & 4 deletions com/win32com/test/GenTestScripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,7 @@ def GetGenPath():
def GenerateFromRegistered(fname, *loadArgs):
# tlb = apply(pythoncom.LoadRegTypeLib, loadArgs)
genPath = GetGenPath()
try:
os.stat(genPath)
except OSError:
os.mkdir(genPath)
os.makedirs(genPath, exist_ok=True)
# Ensure an __init__ exists.
open(os.path.join(genPath, "__init__.py"), "w").close()
print(fname, ": generating -", end=" ")
Expand Down
3 changes: 1 addition & 2 deletions com/win32comext/shell/demos/servers/column_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,7 @@ def GetItemData(self, colid, colData):
ext = ".pyo"
check_file = os.path.splitext(name)[0] + ext
try:
st = os.stat(check_file)
return st[stat.ST_SIZE]
return os.stat(check_file)[stat.ST_SIZE]
except OSError:
# No file
return None
Expand Down
15 changes: 8 additions & 7 deletions win32/Lib/regcheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This module has been marked as deprecated for the past 18 years. A comment set it for removal around "2009 or so".
Would it be better to just remove it?

However it is used by win32/scripts/regsetup.py (checks the registry after Python registration). I'm not sure about a modern use case for the regsetup.py script either.

def CheckRegisteredExe(exename):
try:
os.stat(
if os.path.exists(
win32api.RegQueryValue(
regutil.GetRootKey(), regutil.GetAppPathsKey() + "\\" + exename
)
)
except (OSError, win32api.error):
print("Registration of %s - Not registered correctly" % exename)
):
return
except win32api.error:
pass
print(f"Registration of {exename} - Not registered correctly")


def CheckPathString(pathString):
Expand Down Expand Up @@ -110,11 +112,10 @@ def CheckHelpFiles(verbose):
if verbose:
print("\t" + helpDesc + ":", end=" ")
# query the os section.
try:
os.stat(helpFile)
if os.path.exists(helpFile):
if verbose:
print(helpFile)
except OSError:
else:
print("** Help file %s does not exist" % helpFile)
keyNo += 1
except win32api.error as exc:
Expand Down
21 changes: 6 additions & 15 deletions win32/Lib/regutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,11 +145,7 @@ def RegisterModule(modName, modPath):
modName -- The name of the module, as used by import.
modPath -- The full path and file name of the module.
"""
try:
import os

os.stat(modPath)
except OSError:
if not os.path.exists(modPath):
print("Warning: Registering non-existant module %s" % modPath)
win32api.RegSetValue(
GetRootKey(),
Expand Down Expand Up @@ -204,11 +200,9 @@ def RegisterHelpFile(helpFile, helpPath, helpDesc=None, bCheckFile=1):
if helpDesc is None:
helpDesc = helpFile
fullHelpFile = os.path.join(helpPath, helpFile)
try:
if bCheckFile:
os.stat(fullHelpFile)
except OSError:
raise ValueError("Help file does not exist")
if bCheckFile:
if not os.path.exists(fullHelpFile):
raise ValueError("Help file does not exist")
# Now register with Python itself.
win32api.RegSetValue(
GetRootKey(),
Expand Down Expand Up @@ -264,11 +258,8 @@ def RegisterCoreDLL(coredllName=None):
if coredllName is None:
coredllName = win32api.GetModuleFileName(sys.dllhandle)
# must exist!
else:
try:
os.stat(coredllName)
except OSError:
print("Warning: Registering non-existant core DLL %s" % coredllName)
elif not os.path.exists(coredllName):
print(f"Warning: Registering non-existant core DLL {coredllName}")

hKey = win32api.RegCreateKey(GetRootKey(), BuildDefaultPythonKey())
try:
Expand Down
8 changes: 3 additions & 5 deletions win32/scripts/VersionStamp/BrandProject.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,10 @@ def usage(msg):
usage("You must specify the required arguments")
vssProjectName = "$\\" + args[0]
descFile = args[1]
if not os.path.exists(descFile):
usage(f"The description file '{descFile}' can not be found")
path = args[2]
try:
os.stat(descFile)
except OSError:
usage("The description file '%s' can not be found" % (descFile))
if not os.path.isdir(path):
usage("The path to the files to stamp '%s' does not exist" % (path))
usage(f"The path to the files to stamp '{path}' does not exist")

BrandProject(vssProjectName, descFile, path, stampFiles, desc, bAuto, bRebrand)
22 changes: 8 additions & 14 deletions win32/scripts/backupEventLog.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,15 @@

def BackupClearLog(logType):
datePrefix = time.strftime("%Y%m%d", time.localtime(time.time()))
fileExists = 1
retry = 0
while fileExists:
if retry == 0:
index = ""
else:
index = "-%d" % retry
try:
fname = os.path.join(
win32api.GetTempPath(),
f"{datePrefix}{index}-{logType}" + ".evt",
)
os.stat(fname)
except OSError:
fileExists = 0
while True: # file exists
index = "" if retry == 0 else f"-{retry}"
fname = os.path.join(
win32api.GetTempPath(),
f"{datePrefix}{index}-{logType}.evt",
)
if not os.path.exists(fname):
break
retry += 1
# OK - have unique file name.
try:
Expand Down
13 changes: 4 additions & 9 deletions win32/scripts/regsetup.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,7 @@ def FileExists(fname):
"""Check if a file exists. Returns true or false."""
import os

try:
os.stat(fname)
return 1
except OSError as details:
return 0
return os.path.exists(fname)


def IsPackageDir(path, packageName, knownFileName):
Expand Down Expand Up @@ -188,11 +184,10 @@ def LocateFileName(fileNamesString, searchPaths):
fileNames = fileNamesString.split(";")
for path in searchPaths:
for fileName in fileNames:
try:
retPath = os.path.join(path, fileName)
os.stat(retPath)
retPath = os.path.join(path, fileName)
if os.path.exists(retPath):
break
except OSError:
else:
retPath = None
if retPath:
break
Expand Down