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

Stop using printf-style string formatting for direct string interpolation (%s) #2277

Draft
wants to merge 13 commits 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
4 changes: 2 additions & 2 deletions AutoDuck/Dump2HHC.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ def genCategoryHTML(output_dir, cats):


def _genItemsFromDict(dict, cat, output, target, do_children=1):
CHM = "mk:@MSITStore:%s.chm::/" % target
CHM = "mk:@MSITStore:{}.chm::/".format(target)
for k in sorted(dict):
context = dict[k].context
name = dict[k].name
Expand Down Expand Up @@ -318,7 +318,7 @@ def _genItemsFromDict(dict, cat, output, target, do_children=1):


def genTOC(cats, output, title, target):
CHM = "mk:@MSITStore:%s.chm::/" % target
CHM = "mk:@MSITStore:{}.chm::/".format(target)
output.write(
"""
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
Expand Down
2 changes: 1 addition & 1 deletion AutoDuck/InsertExternalOverviews.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def main():
processFile(input, out, linksHTML, extTopicHTML, importantHTML)
input.close()
out.close()
sCmd = 'del "%s"' % file
sCmd = 'del "{}"'.format(file)
os.unlink(file)
os.rename(file + ".2", file)

Expand Down
2 changes: 1 addition & 1 deletion AutoDuck/fixHelpCompression.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
try:
os.stat(fname)
except OSError:
sys.stderr.write("The project file '%s' was not found\n" % (fname))
sys.stderr.write("The project file '{}' was not found\n".format(fname))
sys.exit(1)

win32api.WriteProfileVal("options", "COMPRESS", "12 Hall Zeck", fname)
13 changes: 7 additions & 6 deletions AutoDuck/makedfromi.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def make_doc_summary(inFile, outFile):
for meth, extras in these_methods:
fields = meth.split("|")
if len(fields) != 3:
print("**Error - %s does not have enough fields" % meth)
print("**Error - {} does not have enough fields".format(meth))
else:
outFile.write(
f"// @pymethod {fields[0]}|{thisModName}|{fields[1]}|{fields[2]}\n"
Expand All @@ -123,7 +123,7 @@ def make_doc_summary(inFile, outFile):
outFile.write(extra)
if g_com_parent:
outFile.write(f"\n// @object {thisModName}|{modDoc}")
outFile.write("\n// <nl>Derived from <o %s>\n" % (g_com_parent))
outFile.write("\n// <nl>Derived from <o {}>\n".format(g_com_parent))
else:
outFile.write(f"\n// @module {thisModName}|{modDoc}\n")
for meth, extras in these_methods:
Expand All @@ -134,7 +134,7 @@ def make_doc_summary(inFile, outFile):

outFile.write("\n")
for extra in extra_tags:
outFile.write("%s\n" % (extra))
outFile.write("{}\n".format(extra))
for cname, doc in constants:
outFile.write(f"// @const {modName}|{cname}|{doc}\n")

Expand All @@ -153,7 +153,7 @@ def doit():
except getopt.error:
_, msg, _ = sys.exc_info()
print(msg)
print("Usage: %s [-o output_name] [-p com_parent] filename" % sys.argv[0])
print("Usage: {} [-o output_name] [-p com_parent] filename".format(sys.argv[0]))
return

inName = args[0]
Expand All @@ -162,8 +162,9 @@ def doit():
inFile = open(inName)
outFile = open(outName, "w")
outFile.write(
"// @doc\n// Generated file - built from %s\n// DO NOT CHANGE - CHANGES WILL BE LOST!\n\n"
% inName
"// @doc\n// Generated file - built from {}\n// DO NOT CHANGE - CHANGES WILL BE LOST!\n\n".format(
inName
)
)
make_doc_summary(inFile, outFile)
inFile.close()
Expand Down
4 changes: 2 additions & 2 deletions Pythonwin/pywin/Demos/app/demoutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,10 @@ def NeedApp():
try:
parent = win32ui.GetMainFrame().GetSafeHwnd()
win32api.ShellExecute(
parent, None, "pythonwin.exe", '/app "%s"' % sys.argv[0], None, 1
parent, None, "pythonwin.exe", '/app "{}"'.format(sys.argv[0]), None, 1
)
except win32api.error as details:
win32ui.MessageBox("Error executing command - %s" % (details), "Demos")
win32ui.MessageBox("Error executing command - {}".format(details), "Demos")


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/Demos/app/dlgappdemo.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def write(self, str):
# translate \n to \n\r
self.edit.ReplaceSel(str.replace("\n", "\r\n"))
else:
win32ui.OutputDebug("dlgapp - no edit control! >>\n%s\n<<\n" % str)
win32ui.OutputDebug("dlgapp - no edit control! >>\n{}\n<<\n".format(str))


app = TestDialogApp()
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/Demos/cmdserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def StartServer(cmd, title=None, bCloseOnEnd=0, serverFlags=flags.SERVER_BEST):
def ServerThread(myout, cmd, title, bCloseOnEnd):
try:
writer.register(myout)
print('Executing "%s"\n' % cmd)
print('Executing "{}"\n'.format(cmd))
bOK = 1
try:
import __main__
Expand Down
4 changes: 2 additions & 2 deletions Pythonwin/pywin/Demos/demoutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,10 @@ def NeedApp():
try:
parent = win32ui.GetMainFrame().GetSafeHwnd()
win32api.ShellExecute(
parent, None, "pythonwin.exe", '/app "%s"' % sys.argv[0], None, 1
parent, None, "pythonwin.exe", '/app "{}"'.format(sys.argv[0]), None, 1
)
except win32api.error as details:
win32ui.MessageBox("Error executing command - %s" % (details), "Demos")
win32ui.MessageBox("Error executing command - {}".format(details), "Demos")


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions Pythonwin/pywin/Demos/ocx/demoutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,10 @@ def NeedApp():
try:
parent = win32ui.GetMainFrame().GetSafeHwnd()
win32api.ShellExecute(
parent, None, "pythonwin.exe", '/app "%s"' % sys.argv[0], None, 1
parent, None, "pythonwin.exe", '/app "{}"'.format(sys.argv[0]), None, 1
)
except win32api.error as details:
win32ui.MessageBox("Error executing command - %s" % (details), "Demos")
win32ui.MessageBox("Error executing command - {}".format(details), "Demos")


if __name__ == "__main__":
Expand Down
7 changes: 4 additions & 3 deletions Pythonwin/pywin/Demos/ocx/ocxserialtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,9 @@ def OnInitDialog(self):
self.olectl.PortOpen = 1
except pythoncom.com_error as details:
print(
"Could not open the specified serial port - %s"
% (details.excepinfo[2])
"Could not open the specified serial port - {}".format(
details.excepinfo[2]
)
)
self.EndDialog(win32con.IDCANCEL)
return rc
Expand All @@ -116,7 +117,7 @@ def OnDestroy(self, msg):
try:
self.olectl.PortOpen = 0
except pythoncom.com_error as details:
print("Error closing port - %s" % (details.excepinfo[2]))
print("Error closing port - {}".format(details.excepinfo[2]))
return dialog.Dialog.OnDestroy(self, msg)


Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/dialogs/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,4 +152,4 @@ def GetPassword(title="Password", password=""):
what = ""
if newpassword != password:
what = "not "
print("The passwords did %smatch" % (what))
print("The passwords did {}match".format(what))
6 changes: 3 additions & 3 deletions Pythonwin/pywin/docking/DockingBar.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,9 @@ def CreateWindow(
self.dialog = childCreator(*(self,) + childCreatorArgs)

# use the dialog dimensions as default base dimensions
assert self.dialog.IsWindow(), (
"The childCreator function %s did not create a window!" % childCreator
)
assert (
self.dialog.IsWindow()
), "The childCreator function {} did not create a window!".format(childCreator)
rect = self.dialog.GetWindowRect()
self.sizeHorz = self.sizeVert = self.sizeFloat = (
rect[2] - rect[0],
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/framework/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ def OnInitDialog(self):
version_path = os.path.join(site_packages, "pywin32.version.txt")
try:
with open(version_path) as f:
ver = "pywin32 build %s" % f.read().strip()
ver = "pywin32 build {}".format(f.read().strip())
except OSError:
ver = None
if not ver:
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/framework/bitmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def OnOpenDocument(self, filename):
try:
self.bitmap.LoadBitmapFile(f)
except OSError:
win32ui.MessageBox("Could not load the bitmap from %s" % filename)
win32ui.MessageBox("Could not load the bitmap from {}".format(filename))
return 0
finally:
f.close()
Expand Down
16 changes: 7 additions & 9 deletions Pythonwin/pywin/framework/editor/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,11 @@ def OnSaveDocument(self, fileName):
try:
self.SaveFile(fileName)
except OSError as details:
win32ui.MessageBox("Error - could not save file\r\n\r\n%s" % details)
win32ui.MessageBox("Error - could not save file\r\n\r\n{}".format(details))
return 0
except (UnicodeEncodeError, LookupError) as details:
rc = win32ui.MessageBox(
"Encoding failed: \r\n%s" % details
"Encoding failed: \r\n{}".format(details)
+ "\r\nPlease add desired source encoding as first line of file, eg \r\n"
+ "# -*- coding: mbcs -*-\r\n\r\n"
+ "If you continue, the file will be saved as binary and will\r\n"
Expand All @@ -100,7 +100,7 @@ def OnSaveDocument(self, fileName):
self.SaveFile(fileName, encoding="latin-1")
except OSError as details:
win32ui.MessageBox(
"Error - could not save file\r\n\r\n%s" % details
"Error - could not save file\r\n\r\n{}".format(details)
)
return 0
else:
Expand Down Expand Up @@ -182,16 +182,14 @@ def CheckExternalDocumentUpdated(self):
if changed:
question = None
if self.IsModified():
question = (
"%s\r\n\r\nThis file has been modified outside of the source editor.\r\nDo you want to reload it and LOSE THE CHANGES in the source editor?"
% self.GetPathName()
question = "{}\r\n\r\nThis file has been modified outside of the source editor.\r\nDo you want to reload it and LOSE THE CHANGES in the source editor?".format(
self.GetPathName()
)
mbStyle = win32con.MB_YESNO | win32con.MB_DEFBUTTON2 # Default to "No"
else:
if not self.bAutoReload:
question = (
"%s\r\n\r\nThis file has been modified outside of the source editor.\r\nDo you want to reload it?"
% self.GetPathName()
question = "{}\r\n\r\nThis file has been modified outside of the source editor.\r\nDo you want to reload it?".format(
self.GetPathName()
)
mbStyle = win32con.MB_YESNO # Default to "Yes"
if question:
Expand Down
4 changes: 2 additions & 2 deletions Pythonwin/pywin/framework/editor/editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ def OnRClick(self, params):
matchResult = patImport.match(line)
if matchResult and matchResult[0] == line:
menu.AppendMenu(
flags, ID_LOCATE_FILE, "&Locate %s.py" % matchResult.group("name")
flags, ID_LOCATE_FILE, "&Locate {}.py".format(matchResult.group("name"))
)
menu.AppendMenu(win32con.MF_SEPARATOR)
menu.AppendMenu(flags, win32ui.ID_EDIT_UNDO, "&Undo")
Expand All @@ -393,7 +393,7 @@ def OnCmdLocateFile(self, cmd, code):

fileName = pywin.framework.scriptutils.LocatePythonFile(modName)
if fileName is None:
win32ui.SetStatusText("Can't locate module %s" % modName)
win32ui.SetStatusText("Can't locate module {}".format(modName))
else:
win32ui.GetApp().OpenDocumentFile(fileName)
return 0
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/framework/editor/vss.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def FindVssProjectInfo(fullfname):
retPaths.insert(0, addpath)
if not project:
win32ui.MessageBox(
"%s\r\n\r\nThis directory is not configured for Python/VSS" % origPath
"{}\r\n\r\nThis directory is not configured for Python/VSS".format(origPath)
)
return
return project, "/".join(retPaths), database
Expand Down
6 changes: 3 additions & 3 deletions Pythonwin/pywin/framework/interact.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ def Init(self):
)
except:
sys.stderr.write(
">>> \nError executing PYTHONSTARTUP script %r\n" % (rcfile)
">>> \nError executing PYTHONSTARTUP script {!r}\n".format(rcfile)
)
traceback.print_exc(file=sys.stderr)
self.AppendToPrompt([])
Expand All @@ -370,8 +370,8 @@ def SetContext(self, globals, locals, name="Dbg"):
sys.ps2 = "... "
locals = globals = __main__.__dict__
else:
sys.ps1 = "[%s]>>> " % name
sys.ps2 = "[%s]... " % name
sys.ps1 = "[{}]>>> ".format(name)
sys.ps2 = "[{}]... ".format(name)
self.interp.locals = locals
self.interp.globals = globals
self.AppendToPrompt([], oldPrompt)
Expand Down
12 changes: 8 additions & 4 deletions Pythonwin/pywin/framework/intpyapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ def ProcessArgs(self, args, dde=None):
dde.Exec(
"from pywin.framework import scriptutils\n"
"ed = scriptutils.GetActiveEditControl()\n"
"if ed: ed.SetSel(ed.LineIndex(%s - 1))" % gotoline
"if ed: ed.SetSel(ed.LineIndex({} - 1))".format(gotoline)
)
else:
from . import scriptutils
Expand Down Expand Up @@ -363,7 +363,9 @@ def ProcessArgs(self, args, dde=None):
)
i += 1
else:
raise ValueError("Command line argument not recognised: %s" % argType)
raise ValueError(
"Command line argument not recognised: {}".format(argType)
)

def LoadSystemModules(self):
self.DoLoadModules("pywin.framework.editor,pywin.framework.stdin")
Expand All @@ -384,7 +386,7 @@ def DoLoadModules(self, moduleNames): # ", sep string of module names.
__import__(module)
except: # Catch em all, else the app itself dies! 'ImportError:
traceback.print_exc()
msg = 'Startup import of user module "%s" failed' % module
msg = 'Startup import of user module "{}" failed'.format(module)
print(msg)
win32ui.MessageBox(msg)

Expand Down Expand Up @@ -461,7 +463,9 @@ def OnFileLocate(self, id, code):
lastLocateFileName = lastLocateFileName.replace(".", "\\")
newName = scriptutils.LocatePythonFile(lastLocateFileName)
if newName is None:
win32ui.MessageBox("The file '%s' can not be located" % lastLocateFileName)
win32ui.MessageBox(
"The file '{}' can not be located".format(lastLocateFileName)
)
else:
win32ui.GetApp().OpenDocumentFile(newName)

Expand Down
14 changes: 7 additions & 7 deletions Pythonwin/pywin/framework/scriptutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None):
except OSError:
fullScript = LocatePythonFile(script)
if fullScript is None:
win32ui.MessageBox("The file '%s' can not be located" % script)
win32ui.MessageBox("The file '{}' can not be located".format(script))
return
script = fullScript
else:
Expand Down Expand Up @@ -334,7 +334,7 @@ def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None):
base = os.path.split(script)[1]
# Allow windows to repaint before starting.
win32ui.PumpWaitingMessages()
win32ui.SetStatusText("Running script %s..." % base, 1)
win32ui.SetStatusText("Running script {}...".format(base), 1)
exitCode = 0
from pywin.framework import interact

Expand Down Expand Up @@ -399,7 +399,7 @@ def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None):
if bWorked:
win32ui.SetStatusText(f"Script '{script}' returned exit code {exitCode}")
else:
win32ui.SetStatusText("Exception raised while running script %s" % base)
win32ui.SetStatusText("Exception raised while running script {}".format(base))
try:
sys.stdout.flush()
except AttributeError:
Expand Down Expand Up @@ -483,7 +483,7 @@ def ImportFile():
+ what
+ "ed module '"
+ modName
+ "': %s" % getattr(mod, "__file__", "<unkown file>")
+ "': {}".format(getattr(mod, "__file__", "<unkown file>"))
)
except:
_HandlePythonFailure(what)
Expand Down Expand Up @@ -630,13 +630,13 @@ def FindTabNanny():
try:
path = win32api.RegQueryValue(
win32con.HKEY_LOCAL_MACHINE,
"SOFTWARE\\Python\\PythonCore\\%s\\InstallPath" % (sys.winver),
"SOFTWARE\\Python\\PythonCore\\{}\\InstallPath".format(sys.winver),
)
except win32api.error:
print("WARNING - The Python registry does not have an 'InstallPath' setting")
print(" The file '%s' can not be located" % (filename))
print(" The file '{}' can not be located".format(filename))
return None
fname = os.path.join(path, "Tools\\Scripts\\%s" % filename)
fname = os.path.join(path, "Tools\\Scripts\\{}".format(filename))
try:
os.stat(fname)
except OSError:
Expand Down
Loading
Loading