Skip to content

Commit 40caf46

Browse files
committed
Prefer os.path.exists over os.stat try-catch
Fixes a few reportPossiblyUnboundVariable and possibly-undefined
1 parent 0ea624e commit 40caf46

File tree

12 files changed

+43
-86
lines changed

12 files changed

+43
-86
lines changed

AutoDuck/fixHelpCompression.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,8 @@
77

88
fname = sys.argv[1]
99

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

1614
win32api.WriteProfileVal("options", "COMPRESS", "12 Hall Zeck", fname)

Pythonwin/pywin/Demos/hiertest.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -101,12 +101,9 @@ def __init__(self, filename):
101101

102102
def GetText(self):
103103
try:
104-
return "%-20s %d bytes" % (
105-
os.path.basename(self.filename),
106-
os.stat(self.filename)[6],
107-
)
104+
return f"{os.path.basename(self.filename):<20} {os.stat(self.filename)[6]} bytes"
108105
except OSError as details:
109-
return "%-20s - %s" % (self.filename, details[1])
106+
return f"{self.filename:<20} - {details[1]}"
110107

111108
def IsExpandable(self):
112109
return os.path.isdir(self.filename)

Pythonwin/pywin/framework/scriptutils.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -284,10 +284,9 @@ def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None):
284284
# If no path specified, try and locate the file
285285
path, fnameonly = os.path.split(script)
286286
if len(path) == 0:
287-
try:
288-
os.stat(fnameonly) # See if it is OK as is...
287+
if os.path.exists(fnameonly): # See if it is OK as is...
289288
script = fnameonly
290-
except OSError:
289+
else:
291290
fullScript = LocatePythonFile(script)
292291
if fullScript is None:
293292
win32ui.MessageBox("The file '%s' can not be located" % script)
@@ -637,9 +636,7 @@ def FindTabNanny():
637636
print(" The file '%s' can not be located" % (filename))
638637
return None
639638
fname = os.path.join(path, "Tools\\Scripts\\%s" % filename)
640-
try:
641-
os.stat(fname)
642-
except OSError:
639+
if not os.path.exists(fname):
643640
print(f"WARNING - The file '{filename}' can not be located in path '{path}'")
644641
return None
645642

com/win32com/client/gencache.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -168,15 +168,9 @@ def GetGeneratePath():
168168
Checks the directory is OK.
169169
"""
170170
assert not is_readonly, "Why do you want the genpath for a readonly store?"
171-
try:
172-
os.makedirs(win32com.__gen_path__)
173-
# os.mkdir(win32com.__gen_path__)
174-
except OSError:
175-
pass
176-
try:
177-
fname = os.path.join(win32com.__gen_path__, "__init__.py")
178-
os.stat(fname)
179-
except OSError:
171+
os.makedirs(win32com.__gen_path__, exist_ok=True)
172+
fname = os.path.join(win32com.__gen_path__, "__init__.py")
173+
if not os.path.exists(fname):
180174
f = open(fname, "w")
181175
f.write(
182176
"# Generated file - this directory may be deleted to reset the COM cache...\n"

com/win32com/server/register.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -133,18 +133,14 @@ def _find_localserver_module():
133133
path = next(iter(win32com.server.__path__))
134134
baseName = "localserver"
135135
pyfile = os.path.join(path, baseName + ".py")
136-
try:
137-
os.stat(pyfile)
138-
except OSError:
136+
if not os.path.exists(pyfile):
139137
# See if we have a compiled extension
140138
if __debug__:
141139
ext = ".pyc"
142140
else:
143141
ext = ".pyo"
144142
pyfile = os.path.join(path, baseName + ext)
145-
try:
146-
os.stat(pyfile)
147-
except OSError:
143+
if not os.path.exists(pyfile):
148144
raise RuntimeError(
149145
"Can not locate the Python module 'win32com.server.%s'" % baseName
150146
)

com/win32com/test/GenTestScripts.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,7 @@ def GetGenPath():
2828
def GenerateFromRegistered(fname, *loadArgs):
2929
# tlb = apply(pythoncom.LoadRegTypeLib, loadArgs)
3030
genPath = GetGenPath()
31-
try:
32-
os.stat(genPath)
33-
except OSError:
34-
os.mkdir(genPath)
31+
os.makedirs(genPath, exist_ok=True)
3532
# Ensure an __init__ exists.
3633
open(os.path.join(genPath, "__init__.py"), "w").close()
3734
print(fname, ": generating -", end=" ")

com/win32comext/shell/demos/servers/column_provider.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,7 @@ def GetItemData(self, colid, colData):
8080
ext = ".pyo"
8181
check_file = os.path.splitext(name)[0] + ext
8282
try:
83-
st = os.stat(check_file)
84-
return st[stat.ST_SIZE]
83+
return os.stat(check_file)[stat.ST_SIZE]
8584
except OSError:
8685
# No file
8786
return None

win32/Lib/regcheck.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,15 @@
1818

1919
def CheckRegisteredExe(exename):
2020
try:
21-
os.stat(
21+
if os.path.exists(
2222
win32api.RegQueryValue(
2323
regutil.GetRootKey(), regutil.GetAppPathsKey() + "\\" + exename
2424
)
25-
)
26-
except (OSError, win32api.error):
27-
print("Registration of %s - Not registered correctly" % exename)
25+
):
26+
return
27+
except win32api.error:
28+
pass
29+
print(f"Registration of {exename} - Not registered correctly")
2830

2931

3032
def CheckPathString(pathString):
@@ -110,11 +112,10 @@ def CheckHelpFiles(verbose):
110112
if verbose:
111113
print("\t" + helpDesc + ":", end=" ")
112114
# query the os section.
113-
try:
114-
os.stat(helpFile)
115+
if os.path.exists(helpFile):
115116
if verbose:
116117
print(helpFile)
117-
except OSError:
118+
else:
118119
print("** Help file %s does not exist" % helpFile)
119120
keyNo += 1
120121
except win32api.error as exc:

win32/Lib/regutil.py

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -145,11 +145,7 @@ def RegisterModule(modName, modPath):
145145
modName -- The name of the module, as used by import.
146146
modPath -- The full path and file name of the module.
147147
"""
148-
try:
149-
import os
150-
151-
os.stat(modPath)
152-
except OSError:
148+
if not os.path.exists(modPath):
153149
print("Warning: Registering non-existant module %s" % modPath)
154150
win32api.RegSetValue(
155151
GetRootKey(),
@@ -204,11 +200,9 @@ def RegisterHelpFile(helpFile, helpPath, helpDesc=None, bCheckFile=1):
204200
if helpDesc is None:
205201
helpDesc = helpFile
206202
fullHelpFile = os.path.join(helpPath, helpFile)
207-
try:
208-
if bCheckFile:
209-
os.stat(fullHelpFile)
210-
except OSError:
211-
raise ValueError("Help file does not exist")
203+
if bCheckFile:
204+
if not os.path.exists(fullHelpFile):
205+
raise ValueError("Help file does not exist")
212206
# Now register with Python itself.
213207
win32api.RegSetValue(
214208
GetRootKey(),
@@ -264,11 +258,8 @@ def RegisterCoreDLL(coredllName=None):
264258
if coredllName is None:
265259
coredllName = win32api.GetModuleFileName(sys.dllhandle)
266260
# must exist!
267-
else:
268-
try:
269-
os.stat(coredllName)
270-
except OSError:
271-
print("Warning: Registering non-existant core DLL %s" % coredllName)
261+
elif not os.path.exists(coredllName):
262+
print(f"Warning: Registering non-existant core DLL {coredllName}")
272263

273264
hKey = win32api.RegCreateKey(GetRootKey(), BuildDefaultPythonKey())
274265
try:

win32/scripts/VersionStamp/BrandProject.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -86,12 +86,10 @@ def usage(msg):
8686
usage("You must specify the required arguments")
8787
vssProjectName = "$\\" + args[0]
8888
descFile = args[1]
89+
if not os.path.exists(descFile):
90+
usage(f"The description file '{descFile}' can not be found")
8991
path = args[2]
90-
try:
91-
os.stat(descFile)
92-
except OSError:
93-
usage("The description file '%s' can not be found" % (descFile))
9492
if not os.path.isdir(path):
95-
usage("The path to the files to stamp '%s' does not exist" % (path))
93+
usage(f"The path to the files to stamp '{path}' does not exist")
9694

9795
BrandProject(vssProjectName, descFile, path, stampFiles, desc, bAuto, bRebrand)

0 commit comments

Comments
 (0)