Commit df2208e1 authored by Georg Brandl's avatar Georg Brandl

More 2to3 fixes in the Tools directory. Fixes #2893.

parent d4cd02da
...@@ -88,7 +88,7 @@ def stringify(str): ...@@ -88,7 +88,7 @@ def stringify(str):
res = '"' res = '"'
map = _stringify_map map = _stringify_map
for c in str: for c in str:
if map.has_key(c): res = res + map[c] if c in map: res = res + map[c]
elif ' ' <= c <= '~': res = res + c elif ' ' <= c <= '~': res = res + c
else: res = res + '\\%03o' % ord(c) else: res = res + '\\%03o' % ord(c)
res = res + '"' res = res + '"'
......
...@@ -182,7 +182,7 @@ def Out(text): ...@@ -182,7 +182,7 @@ def Out(text):
line = line[n:] line = line[n:]
else: else:
for c in indent: for c in indent:
if line[:1] <> c: break if line[:1] != c: break
line = line[1:] line = line[1:]
VaOutput("%s", line) VaOutput("%s", line)
......
...@@ -126,23 +126,20 @@ class Scanner: ...@@ -126,23 +126,20 @@ class Scanner:
self.usedtypes = {} self.usedtypes = {}
def typeused(self, type, mode): def typeused(self, type, mode):
if not self.usedtypes.has_key(type): if type not in self.usedtypes:
self.usedtypes[type] = {} self.usedtypes[type] = {}
self.usedtypes[type][mode] = None self.usedtypes[type][mode] = None
def reportusedtypes(self): def reportusedtypes(self):
types = self.usedtypes.keys() types = sorted(self.usedtypes.keys())
types.sort()
for type in types: for type in types:
modes = self.usedtypes[type].keys() modes = sorted(self.usedtypes[type].keys())
modes.sort()
self.report("%s %s", type, " ".join(modes)) self.report("%s %s", type, " ".join(modes))
def gentypetest(self, file): def gentypetest(self, file):
fp = open(file, "w") fp = open(file, "w")
fp.write("types=[\n") fp.write("types=[\n")
types = self.usedtypes.keys() types = sorted(self.usedtypes.keys())
types.sort()
for type in types: for type in types:
fp.write("\t'%s',\n"%type) fp.write("\t'%s',\n"%type)
fp.write("]\n") fp.write("]\n")
...@@ -236,7 +233,7 @@ if missing: raise "Missing Types" ...@@ -236,7 +233,7 @@ if missing: raise "Missing Types"
if i >= 0: line = line[:i] if i >= 0: line = line[:i]
words = [s.strip() for s in line.split(':')] words = [s.strip() for s in line.split(':')]
if words == ['']: continue if words == ['']: continue
if len(words) <> 3: if len(words) != 3:
print("Line", startlineno, end=' ') print("Line", startlineno, end=' ')
print(": bad line (not 3 colon-separated fields)") print(": bad line (not 3 colon-separated fields)")
print(repr(line)) print(repr(line))
...@@ -703,7 +700,7 @@ if missing: raise "Missing Types" ...@@ -703,7 +700,7 @@ if missing: raise "Missing Types"
return arglist return arglist
def matcharg(self, patarg, arg): def matcharg(self, patarg, arg):
return len(filter(None, map(fnmatch.fnmatchcase, arg, patarg))) == 3 return len(f for f in map(fnmatch.fnmatchcase, arg, patarg) if f) == 3
def substituteargs(self, pattern, replacement, old): def substituteargs(self, pattern, replacement, old):
new = [] new = []
...@@ -739,7 +736,7 @@ if missing: raise "Missing Types" ...@@ -739,7 +736,7 @@ if missing: raise "Missing Types"
self.typeused(atype, amode) self.typeused(atype, amode)
self.specfile.write(" (%s, %r, %s),\n" % self.specfile.write(" (%s, %r, %s),\n" %
(atype, aname, amode)) (atype, aname, amode))
if self.greydictnames.has_key(name): if name in self.greydictnames:
self.specfile.write(" condition=%r,\n"%(self.greydictnames[name],)) self.specfile.write(" condition=%r,\n"%(self.greydictnames[name],))
self.generatemodifiers(classname, name, modifiers) self.generatemodifiers(classname, name, modifiers)
self.specfile.write(")\n") self.specfile.write(")\n")
......
...@@ -120,7 +120,7 @@ def log(text): ...@@ -120,7 +120,7 @@ def log(text):
logfile.close() logfile.close()
def load_cookies(): def load_cookies():
if not os.environ.has_key('HTTP_COOKIE'): if 'HTTP_COOKIE' not in os.environ:
return {} return {}
raw = os.environ['HTTP_COOKIE'] raw = os.environ['HTTP_COOKIE']
words = [s.strip() for s in raw.split(';')] words = [s.strip() for s in raw.split(';')]
...@@ -359,7 +359,7 @@ class FaqDir: ...@@ -359,7 +359,7 @@ class FaqDir:
self.open(file).show(edit=edit) self.open(file).show(edit=edit)
def new(self, section): def new(self, section):
if not SECTION_TITLES.has_key(section): if section not in SECTION_TITLES:
raise NoSuchSection(section) raise NoSuchSection(section)
maxnum = 0 maxnum = 0
for file in self.list(): for file in self.list():
...@@ -426,11 +426,11 @@ class FaqWizard: ...@@ -426,11 +426,11 @@ class FaqWizard:
query = re.escape(query) query = re.escape(query)
queries = [query] queries = [query]
elif self.ui.querytype in ('anykeywords', 'allkeywords'): elif self.ui.querytype in ('anykeywords', 'allkeywords'):
words = filter(None, re.split('\W+', query)) words = [_f for _f in re.split('\W+', query) if _f]
if not words: if not words:
self.error("No keywords specified!") self.error("No keywords specified!")
return return
words = map(lambda w: r'\b%s\b' % w, words) words = [r'\b%s\b' % w for w in words]
if self.ui.querytype[:3] == 'any': if self.ui.querytype[:3] == 'any':
queries = ['|'.join(words)] queries = ['|'.join(words)]
else: else:
...@@ -577,7 +577,7 @@ class FaqWizard: ...@@ -577,7 +577,7 @@ class FaqWizard:
emit(ONE_RECENT, period=period) emit(ONE_RECENT, period=period)
else: else:
emit(SOME_RECENT, period=period, count=len(list)) emit(SOME_RECENT, period=period, count=len(list))
self.format_all(map(lambda (mtime, file): file, list), headers=0) self.format_all([mtime_file[1] for mtime_file in list], headers=0)
emit(TAIL_RECENT) emit(TAIL_RECENT)
def do_roulette(self): def do_roulette(self):
...@@ -603,8 +603,7 @@ class FaqWizard: ...@@ -603,8 +603,7 @@ class FaqWizard:
def do_add(self): def do_add(self):
self.prologue(T_ADD) self.prologue(T_ADD)
emit(ADD_HEAD) emit(ADD_HEAD)
sections = SECTION_TITLES.items() sections = sorted(SECTION_TITLES.items())
sections.sort()
for section, title in sections: for section, title in sections:
emit(ADD_SECTION, section=section, title=title) emit(ADD_SECTION, section=section, title=title)
emit(ADD_TAIL) emit(ADD_TAIL)
......
...@@ -10,11 +10,6 @@ from framer.util import cstring, unindent ...@@ -10,11 +10,6 @@ from framer.util import cstring, unindent
from types import FunctionType from types import FunctionType
def sortitems(dict):
L = dict.items()
L.sort()
return L
# The Module and Type classes are implemented using metaclasses, # The Module and Type classes are implemented using metaclasses,
# because most of the methods are class methods. It is easier to use # because most of the methods are class methods. It is easier to use
# metaclasses than the cumbersome classmethod() builtin. They have # metaclasses than the cumbersome classmethod() builtin. They have
...@@ -32,7 +27,7 @@ class BaseMetaclass(type): ...@@ -32,7 +27,7 @@ class BaseMetaclass(type):
if not functions: if not functions:
return return
p(template.methoddef_start) p(template.methoddef_start)
for name, func in sortitems(functions): for name, func in sorted(functions.items()):
if func.__doc__: if func.__doc__:
p(template.methoddef_def_doc, func.vars) p(template.methoddef_def_doc, func.vars)
else: else:
...@@ -55,7 +50,7 @@ class ModuleMetaclass(BaseMetaclass): ...@@ -55,7 +50,7 @@ class ModuleMetaclass(BaseMetaclass):
self.__types = {} self.__types = {}
self.__members = False self.__members = False
for name, obj in self.__dict__.iteritems(): for name, obj in self.__dict__.items():
if isinstance(obj, FunctionType): if isinstance(obj, FunctionType):
self.__functions[name] = Function(obj, self) self.__functions[name] = Function(obj, self)
elif isinstance(obj, TypeMetaclass): elif isinstance(obj, TypeMetaclass):
...@@ -87,16 +82,16 @@ class ModuleMetaclass(BaseMetaclass): ...@@ -87,16 +82,16 @@ class ModuleMetaclass(BaseMetaclass):
if self.__doc__: if self.__doc__:
p(template.module_doc) p(template.module_doc)
for name, type in sortitems(self.__types): for name, type in sorted(self.__types.items()):
type.dump(f) type.dump(f)
for name, func in sortitems(self.__functions): for name, func in sorted(self.__functions.items()):
func.dump(f) func.dump(f)
self.dump_methoddef(f, self.__functions, self.__vars) self.dump_methoddef(f, self.__functions, self.__vars)
p(template.module_init_start) p(template.module_init_start)
for name, type in sortitems(self.__types): for name, type in sorted(self.__types.items()):
type.dump_init(f) type.dump_init(f)
p("}") p("}")
...@@ -119,7 +114,7 @@ class TypeMetaclass(BaseMetaclass): ...@@ -119,7 +114,7 @@ class TypeMetaclass(BaseMetaclass):
if self.__doc__: if self.__doc__:
p(template.docstring) p(template.docstring)
for name, func in sortitems(self.__methods): for name, func in sorted(self.__methods.items()):
func.dump(f) func.dump(f)
self.dump_methoddef(f, self.__methods, self.__vars) self.dump_methoddef(f, self.__methods, self.__vars)
...@@ -143,7 +138,7 @@ class TypeMetaclass(BaseMetaclass): ...@@ -143,7 +138,7 @@ class TypeMetaclass(BaseMetaclass):
self.__methods = {} self.__methods = {}
self.__members = {} self.__members = {}
for cls in self.__mro__: for cls in self.__mro__:
for k, v in cls.__dict__.iteritems(): for k, v in cls.__dict__.items():
if isinstance(v, FunctionType): if isinstance(v, FunctionType):
self.__methods[k] = Method(v, self) self.__methods[k] = Method(v, self)
if isinstance(v, member): if isinstance(v, member):
...@@ -190,7 +185,7 @@ class TypeMetaclass(BaseMetaclass): ...@@ -190,7 +185,7 @@ class TypeMetaclass(BaseMetaclass):
if not self.__members: if not self.__members:
return return
p(template.memberdef_start) p(template.memberdef_start)
for name, slot in sortitems(self.__members): for name, slot in sorted(self.__members.items()):
slot.dump(f) slot.dump(f)
p(template.memberdef_end) p(template.memberdef_end)
......
...@@ -45,7 +45,7 @@ class _ArgumentList(object): ...@@ -45,7 +45,7 @@ class _ArgumentList(object):
fmt = None fmt = None
def __init__(self, args): def __init__(self, args):
self.args = map(Argument, args) self.args = list(map(Argument, args))
def __len__(self): def __len__(self):
return len(self.args) return len(self.args)
...@@ -99,15 +99,15 @@ class VarArgs(_ArgumentList): ...@@ -99,15 +99,15 @@ class VarArgs(_ArgumentList):
print(" %s" % a.decl(), file=f) print(" %s" % a.decl(), file=f)
def ArgumentList(func, method): def ArgumentList(func, method):
code = func.func_code code = func.__code__
args = code.co_varnames[:code.co_argcount] args = code.co_varnames[:code.co_argcount]
if method: if method:
args = args[1:] args = args[1:]
pyarg = getattr(func, "pyarg", None) pyarg = getattr(func, "pyarg", None)
if pyarg is not None: if pyarg is not None:
args = VarArgs(args, pyarg) args = VarArgs(args, pyarg)
if func.func_defaults: if func.__defaults__:
L = list(func.func_defaults) L = list(func.__defaults__)
ndefault = len(L) ndefault = len(L)
i = len(args) - ndefault i = len(args) - ndefault
while L: while L:
......
...@@ -25,7 +25,7 @@ def parse(s): ...@@ -25,7 +25,7 @@ def parse(s):
The parser is very restricted in what it will accept. The parser is very restricted in what it will accept.
""" """
lines = filter(None, s.split("\n")) # get non-empty lines lines = [_f for _f in s.split("\n") if _f] # get non-empty lines
assert lines[0].strip() == "typedef struct {" assert lines[0].strip() == "typedef struct {"
pyhead = lines[1].strip() pyhead = lines[1].strip()
assert (pyhead.startswith("PyObject") and assert (pyhead.startswith("PyObject") and
......
...@@ -19,7 +19,7 @@ def parse(s): ...@@ -19,7 +19,7 @@ def parse(s):
The parser is very restricted in what it will accept. The parser is very restricted in what it will accept.
""" """
lines = filter(None, s.split("\n")) # get non-empty lines lines = [_f for _f in s.split("\n") if _f] # get non-empty lines
assert lines[0].strip() == "typedef struct {" assert lines[0].strip() == "typedef struct {"
pyhead = lines[1].strip() pyhead = lines[1].strip()
assert (pyhead.startswith("PyObject") and assert (pyhead.startswith("PyObject") and
......
...@@ -18,7 +18,7 @@ def checkextensions(unknown, extensions): ...@@ -18,7 +18,7 @@ def checkextensions(unknown, extensions):
for mod in unknown: for mod in unknown:
for e in extensions: for e in extensions:
(mods, vars), liba = edict[e] (mods, vars), liba = edict[e]
if not mods.has_key(mod): if mod not in mods:
continue continue
modules.append(mod) modules.append(mod)
if liba: if liba:
...@@ -28,7 +28,7 @@ def checkextensions(unknown, extensions): ...@@ -28,7 +28,7 @@ def checkextensions(unknown, extensions):
if liba in files: if liba in files:
break break
files.append(liba) files.append(liba)
for m in mods.keys(): for m in list(mods.keys()):
files = files + select(e, mods, vars, files = files + select(e, mods, vars,
m, 1) m, 1)
break break
...@@ -84,7 +84,7 @@ def expandvars(str, vars): ...@@ -84,7 +84,7 @@ def expandvars(str, vars):
break break
var = str[i:j] var = str[i:j]
i = j+1 i = j+1
if vars.has_key(var): if var in vars:
str = str[:k] + vars[var] + str[i:] str = str[:k] + vars[var] + str[i:]
i = k i = k
return str return str
...@@ -460,7 +460,7 @@ def main(): ...@@ -460,7 +460,7 @@ def main():
somevars = {} somevars = {}
if os.path.exists(makefile_in): if os.path.exists(makefile_in):
makevars = parsesetup.getmakevars(makefile_in) makevars = parsesetup.getmakevars(makefile_in)
for key in makevars.keys(): for key in makevars:
somevars[key] = makevars[key] somevars[key] = makevars[key]
somevars['CFLAGS'] = ' '.join(cflags) # override somevars['CFLAGS'] = ' '.join(cflags) # override
......
...@@ -45,18 +45,14 @@ def parse(filename): ...@@ -45,18 +45,14 @@ def parse(filename):
return data return data
def pprint(data): def pprint(data):
items = sorted(data.items())
items = data.items() for k, v in items:
items.sort()
for k,v in items:
print(' %-40s%r,' % ('%r:' % k, v)) print(' %-40s%r,' % ('%r:' % k, v))
def print_differences(data, olddata): def print_differences(data, olddata):
items = sorted(olddata.items())
items = olddata.items()
items.sort()
for k, v in items: for k, v in items:
if not data.has_key(k): if k not in data:
print('# removed %r' % k) print('# removed %r' % k)
elif olddata[k] != data[k]: elif olddata[k] != data[k]:
print('# updated %r -> %r to %r' % \ print('# updated %r -> %r to %r' % \
......
...@@ -56,9 +56,8 @@ def add(id, str, fuzzy): ...@@ -56,9 +56,8 @@ def add(id, str, fuzzy):
def generate(): def generate():
"Return the generated output." "Return the generated output."
global MESSAGES global MESSAGES
keys = MESSAGES.keys()
# the keys are sorted in the .mo file # the keys are sorted in the .mo file
keys.sort() keys = sorted(MESSAGES.keys())
offsets = [] offsets = []
ids = strs = '' ids = strs = ''
for id in keys: for id in keys:
......
...@@ -265,7 +265,7 @@ def containsAny(str, set): ...@@ -265,7 +265,7 @@ def containsAny(str, set):
def _visit_pyfiles(list, dirname, names): def _visit_pyfiles(list, dirname, names):
"""Helper for getFilesForName().""" """Helper for getFilesForName()."""
# get extension for python source files # get extension for python source files
if not globals().has_key('_py_ext'): if '_py_ext' not in globals():
global _py_ext global _py_ext
_py_ext = [triple[0] for triple in imp.get_suffixes() _py_ext = [triple[0] for triple in imp.get_suffixes()
if triple[2] == imp.PY_SOURCE][0] if triple[2] == imp.PY_SOURCE][0]
......
...@@ -19,7 +19,7 @@ class ScrolledListbox(Listbox): ...@@ -19,7 +19,7 @@ class ScrolledListbox(Listbox):
fcnf = {} fcnf = {}
vcnf = {'name': 'vbar', vcnf = {'name': 'vbar',
Pack: {'side': 'right', 'fill': 'y'},} Pack: {'side': 'right', 'fill': 'y'},}
for k in cnf.keys(): for k in list(cnf.keys()):
if type(k) == ClassType or k == 'name': if type(k) == ClassType or k == 'name':
fcnf[k] = cnf[k] fcnf[k] = cnf[k]
del cnf[k] del cnf[k]
...@@ -32,6 +32,6 @@ class ScrolledListbox(Listbox): ...@@ -32,6 +32,6 @@ class ScrolledListbox(Listbox):
self.vbar['command'] = (self, 'yview') self.vbar['command'] = (self, 'yview')
# Copy Pack methods of self.frame -- hack! # Copy Pack methods of self.frame -- hack!
for m in Pack.__dict__.keys(): for m in Pack.__dict__:
if m[0] != '_' and m != 'config': if m[0] != '_' and m != 'config':
setattr(self, m, getattr(self.frame, m)) setattr(self, m, getattr(self.frame, m))
...@@ -40,7 +40,7 @@ class writer: ...@@ -40,7 +40,7 @@ class writer:
def makesubst(self): def makesubst(self):
if not self._subst: if not self._subst:
if not self.__dict__.has_key('abbrev'): if 'abbrev' not in self.__dict__:
self.abbrev = self.name self.abbrev = self.name
self.Abbrev = self.abbrev[0].upper()+self.abbrev[1:] self.Abbrev = self.abbrev[0].upper()+self.abbrev[1:]
subst = varsubst.Varsubst(self.__dict__) subst = varsubst.Varsubst(self.__dict__)
......
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
# #
import sys, os import sys, os
if os.name <> 'mac': if os.name != 'mac':
sys.path.append(os.path.join(os.environ['HOME'], sys.path.append(os.path.join(os.environ['HOME'],
'src/python/Tools/modulator')) 'src/python/Tools/modulator'))
......
...@@ -28,7 +28,7 @@ class Varsubst: ...@@ -28,7 +28,7 @@ class Varsubst:
s = s[2:] s = s[2:]
continue continue
name = m.group(1) name = m.group(1)
if not self.dict.has_key(name): if name not in self.dict:
raise error('No such variable: '+name) raise error('No such variable: '+name)
value = self.dict[name] value = self.dict[name]
if self.do_useindent and '\n' in value: if self.do_useindent and '\n' in value:
......
...@@ -19,23 +19,23 @@ def merge(msi, feature, rootdir, modules): ...@@ -19,23 +19,23 @@ def merge(msi, feature, rootdir, modules):
# Step 1: Merge databases, extract cabfiles # Step 1: Merge databases, extract cabfiles
m = msilib.MakeMerge2() m = msilib.MakeMerge2()
m.OpenLog("merge.log") m.OpenLog("merge.log")
print "Opened Log" print("Opened Log")
m.OpenDatabase(msi) m.OpenDatabase(msi)
print "Opened DB" print("Opened DB")
for module in modules: for module in modules:
print module print(module)
m.OpenModule(module,0) m.OpenModule(module,0)
print "Opened Module",module print("Opened Module",module)
m.Merge(feature, rootdir) m.Merge(feature, rootdir)
print "Errors:" print("Errors:")
for e in m.Errors: for e in m.Errors:
print e.Type, e.ModuleTable, e.DatabaseTable print(e.Type, e.ModuleTable, e.DatabaseTable)
print " Modkeys:", print(" Modkeys:", end=' ')
for s in e.ModuleKeys: print s, for s in e.ModuleKeys: print(s, end=' ')
print print()
print " DBKeys:", print(" DBKeys:", end=' ')
for s in e.DatabaseKeys: print s, for s in e.DatabaseKeys: print(s, end=' ')
print print()
cabname = tempfile.mktemp(suffix=".cab") cabname = tempfile.mktemp(suffix=".cab")
m.ExtractCAB(cabname) m.ExtractCAB(cabname)
cab_and_filecount.append((cabname, len(m.ModuleFiles))) cab_and_filecount.append((cabname, len(m.ModuleFiles)))
...@@ -56,7 +56,7 @@ def merge(msi, feature, rootdir, modules): ...@@ -56,7 +56,7 @@ def merge(msi, feature, rootdir, modules):
seq = r.IntegerData(1) seq = r.IntegerData(1)
if seq > maxmedia: if seq > maxmedia:
maxmedia = seq maxmedia = seq
print "Start of Media", maxmedia print("Start of Media", maxmedia)
for cabname, count in cab_and_filecount: for cabname, count in cab_and_filecount:
stream = "merged%d" % maxmedia stream = "merged%d" % maxmedia
......
...@@ -205,7 +205,7 @@ def build_database(): ...@@ -205,7 +205,7 @@ def build_database():
schema, ProductName="Python "+full_current_version, schema, ProductName="Python "+full_current_version,
ProductCode=product_code, ProductCode=product_code,
ProductVersion=current_version, ProductVersion=current_version,
Manufacturer=u"Python Software Foundation") Manufacturer="Python Software Foundation")
# The default sequencing of the RemoveExistingProducts action causes # The default sequencing of the RemoveExistingProducts action causes
# removal of files that got just installed. Place it after # removal of files that got just installed. Place it after
# InstallInitialize, so we first uninstall everything, but still roll # InstallInitialize, so we first uninstall everything, but still roll
...@@ -335,7 +335,7 @@ def add_ui(db): ...@@ -335,7 +335,7 @@ def add_ui(db):
# Bitmaps # Bitmaps
if not os.path.exists(srcdir+r"\PC\python_icon.exe"): if not os.path.exists(srcdir+r"\PC\python_icon.exe"):
raise "Run icons.mak in PC directory" raise RuntimeError("Run icons.mak in PC directory")
add_data(db, "Binary", add_data(db, "Binary",
[("PythonWin", msilib.Binary(r"%s\PCbuild\installer.bmp" % srcdir)), # 152x328 pixels [("PythonWin", msilib.Binary(r"%s\PCbuild\installer.bmp" % srcdir)), # 152x328 pixels
("py.ico",msilib.Binary(srcdir+r"\PC\py.ico")), ("py.ico",msilib.Binary(srcdir+r"\PC\py.ico")),
...@@ -349,7 +349,7 @@ def add_ui(db): ...@@ -349,7 +349,7 @@ def add_ui(db):
# the installed/uninstalled state according to both the # the installed/uninstalled state according to both the
# Extensions and TclTk features. # Extensions and TclTk features.
if os.system("nmake /nologo /c /f msisupport.mak") != 0: if os.system("nmake /nologo /c /f msisupport.mak") != 0:
raise "'nmake /f msisupport.mak' failed" raise RuntimeError("'nmake /f msisupport.mak' failed")
add_data(db, "Binary", [("Script", msilib.Binary("msisupport.dll"))]) add_data(db, "Binary", [("Script", msilib.Binary("msisupport.dll"))])
# See "Custom Action Type 1" # See "Custom Action Type 1"
if msilib.Win64: if msilib.Win64:
...@@ -845,7 +845,7 @@ class PyDirectory(Directory): ...@@ -845,7 +845,7 @@ class PyDirectory(Directory):
"""By default, all components in the Python installer """By default, all components in the Python installer
can run from source.""" can run from source."""
def __init__(self, *args, **kw): def __init__(self, *args, **kw):
if not kw.has_key("componentflags"): if "componentflags" not in kw:
kw['componentflags'] = 2 #msidbComponentAttributesOptional kw['componentflags'] = 2 #msidbComponentAttributesOptional
Directory.__init__(self, *args, **kw) Directory.__init__(self, *args, **kw)
......
...@@ -7,11 +7,6 @@ import pythoncom, pywintypes ...@@ -7,11 +7,6 @@ import pythoncom, pywintypes
from win32com.client import constants from win32com.client import constants
import re, string, os, sets, glob, subprocess, sys, _winreg, struct import re, string, os, sets, glob, subprocess, sys, _winreg, struct
try:
basestring
except NameError:
basestring = (str, unicode)
# Partially taken from Wine # Partially taken from Wine
datasizemask= 0x00ff datasizemask= 0x00ff
type_valid= 0x0100 type_valid= 0x0100
...@@ -173,14 +168,14 @@ def gen_schema(destpath, schemapath): ...@@ -173,14 +168,14 @@ def gen_schema(destpath, schemapath):
r = v.Fetch() r = v.Fetch()
if not r:break if not r:break
# Table, Column, Nullable # Table, Column, Nullable
f.write("(%s,%s,%s," % f.write("(%r,%r,%r," %
(`r.StringData(1)`, `r.StringData(2)`, `r.StringData(3)`)) (r.StringData(1), r.StringData(2), r.StringData(3)))
def put_int(i): def put_int(i):
if r.IsNull(i):f.write("None, ") if r.IsNull(i):f.write("None, ")
else:f.write("%d," % r.IntegerData(i)) else:f.write("%d," % r.IntegerData(i))
def put_str(i): def put_str(i):
if r.IsNull(i):f.write("None, ") if r.IsNull(i):f.write("None, ")
else:f.write("%s," % `r.StringData(i)`) else:f.write("%r," % r.StringData(i))
put_int(4) # MinValue put_int(4) # MinValue
put_int(5) # MaxValue put_int(5) # MaxValue
put_str(6) # KeyTable put_str(6) # KeyTable
...@@ -235,12 +230,12 @@ def gen_sequence(destpath, msipath): ...@@ -235,12 +230,12 @@ def gen_sequence(destpath, msipath):
else: else:
rec.append(bytes) rec.append(bytes)
else: else:
raise "Unsupported column type", info.StringData(i) raise ValueError("Unsupported column type", info.StringData(i))
f.write(repr(tuple(rec))+",\n") f.write(repr(tuple(rec))+",\n")
v1.Close() v1.Close()
f.write("]\n\n") f.write("]\n\n")
v.Close() v.Close()
f.write("tables=%s\n" % repr(map(str,tables))) f.write("tables=%s\n" % repr(list(map(str,tables))))
f.close() f.close()
class _Unspecified:pass class _Unspecified:pass
...@@ -265,9 +260,9 @@ def add_data(db, table, values): ...@@ -265,9 +260,9 @@ def add_data(db, table, values):
assert len(value) == count, value assert len(value) == count, value
for i in range(count): for i in range(count):
field = value[i] field = value[i]
if isinstance(field, (int, long)): if isinstance(field, int):
r.SetIntegerData(i+1,field) r.SetIntegerData(i+1,field)
elif isinstance(field, basestring): elif isinstance(field, str):
r.SetStringData(i+1,field) r.SetStringData(i+1,field)
elif field is None: elif field is None:
pass pass
...@@ -522,7 +517,7 @@ class Directory: ...@@ -522,7 +517,7 @@ class Directory:
file = os.path.basename(file) file = os.path.basename(file)
absolute = os.path.join(self.absolute, src) absolute = os.path.join(self.absolute, src)
assert not re.search(r'[\?|><:/*]"', file) # restrictions on long names assert not re.search(r'[\?|><:/*]"', file) # restrictions on long names
if self.keyfiles.has_key(file): if file in self.keyfiles:
logical = self.keyfiles[file] logical = self.keyfiles[file]
else: else:
logical = None logical = None
......
This source diff could not be displayed because it is too large. You can view the blob instead.
AdminExecuteSequence = [ AdminExecuteSequence = [
(u'InstallInitialize', None, 1500), ('InstallInitialize', None, 1500),
(u'InstallFinalize', None, 6600), ('InstallFinalize', None, 6600),
(u'InstallFiles', None, 4000), ('InstallFiles', None, 4000),
(u'InstallAdminPackage', None, 3900), ('InstallAdminPackage', None, 3900),
(u'FileCost', None, 900), ('FileCost', None, 900),
(u'CostInitialize', None, 800), ('CostInitialize', None, 800),
(u'CostFinalize', None, 1000), ('CostFinalize', None, 1000),
(u'InstallValidate', None, 1400), ('InstallValidate', None, 1400),
] ]
AdminUISequence = [ AdminUISequence = [
(u'FileCost', None, 900), ('FileCost', None, 900),
(u'CostInitialize', None, 800), ('CostInitialize', None, 800),
(u'CostFinalize', None, 1000), ('CostFinalize', None, 1000),
(u'ExecuteAction', None, 1300), ('ExecuteAction', None, 1300),
(u'ExitDialog', None, -1), ('ExitDialog', None, -1),
(u'FatalError', None, -3), ('FatalError', None, -3),
(u'UserExit', None, -2), ('UserExit', None, -2),
] ]
AdvtExecuteSequence = [ AdvtExecuteSequence = [
(u'InstallInitialize', None, 1500), ('InstallInitialize', None, 1500),
(u'InstallFinalize', None, 6600), ('InstallFinalize', None, 6600),
(u'CostInitialize', None, 800), ('CostInitialize', None, 800),
(u'CostFinalize', None, 1000), ('CostFinalize', None, 1000),
(u'InstallValidate', None, 1400), ('InstallValidate', None, 1400),
(u'CreateShortcuts', None, 4500), ('CreateShortcuts', None, 4500),
(u'MsiPublishAssemblies', None, 6250), ('MsiPublishAssemblies', None, 6250),
(u'PublishComponents', None, 6200), ('PublishComponents', None, 6200),
(u'PublishFeatures', None, 6300), ('PublishFeatures', None, 6300),
(u'PublishProduct', None, 6400), ('PublishProduct', None, 6400),
(u'RegisterClassInfo', None, 4600), ('RegisterClassInfo', None, 4600),
(u'RegisterExtensionInfo', None, 4700), ('RegisterExtensionInfo', None, 4700),
(u'RegisterMIMEInfo', None, 4900), ('RegisterMIMEInfo', None, 4900),
(u'RegisterProgIdInfo', None, 4800), ('RegisterProgIdInfo', None, 4800),
] ]
InstallExecuteSequence = [ InstallExecuteSequence = [
(u'InstallInitialize', None, 1500), ('InstallInitialize', None, 1500),
(u'InstallFinalize', None, 6600), ('InstallFinalize', None, 6600),
(u'InstallFiles', None, 4000), ('InstallFiles', None, 4000),
(u'FileCost', None, 900), ('FileCost', None, 900),
(u'CostInitialize', None, 800), ('CostInitialize', None, 800),
(u'CostFinalize', None, 1000), ('CostFinalize', None, 1000),
(u'InstallValidate', None, 1400), ('InstallValidate', None, 1400),
(u'CreateShortcuts', None, 4500), ('CreateShortcuts', None, 4500),
(u'MsiPublishAssemblies', None, 6250), ('MsiPublishAssemblies', None, 6250),
(u'PublishComponents', None, 6200), ('PublishComponents', None, 6200),
(u'PublishFeatures', None, 6300), ('PublishFeatures', None, 6300),
(u'PublishProduct', None, 6400), ('PublishProduct', None, 6400),
(u'RegisterClassInfo', None, 4600), ('RegisterClassInfo', None, 4600),
(u'RegisterExtensionInfo', None, 4700), ('RegisterExtensionInfo', None, 4700),
(u'RegisterMIMEInfo', None, 4900), ('RegisterMIMEInfo', None, 4900),
(u'RegisterProgIdInfo', None, 4800), ('RegisterProgIdInfo', None, 4800),
(u'AllocateRegistrySpace', u'NOT Installed', 1550), ('AllocateRegistrySpace', 'NOT Installed', 1550),
(u'AppSearch', None, 400), ('AppSearch', None, 400),
(u'BindImage', None, 4300), ('BindImage', None, 4300),
(u'CCPSearch', u'NOT Installed', 500), ('CCPSearch', 'NOT Installed', 500),
(u'CreateFolders', None, 3700), ('CreateFolders', None, 3700),
(u'DeleteServices', u'VersionNT', 2000), ('DeleteServices', 'VersionNT', 2000),
(u'DuplicateFiles', None, 4210), ('DuplicateFiles', None, 4210),
(u'FindRelatedProducts', None, 200), ('FindRelatedProducts', None, 200),
(u'InstallODBC', None, 5400), ('InstallODBC', None, 5400),
(u'InstallServices', u'VersionNT', 5800), ('InstallServices', 'VersionNT', 5800),
(u'IsolateComponents', None, 950), ('IsolateComponents', None, 950),
(u'LaunchConditions', None, 100), ('LaunchConditions', None, 100),
(u'MigrateFeatureStates', None, 1200), ('MigrateFeatureStates', None, 1200),
(u'MoveFiles', None, 3800), ('MoveFiles', None, 3800),
(u'PatchFiles', None, 4090), ('PatchFiles', None, 4090),
(u'ProcessComponents', None, 1600), ('ProcessComponents', None, 1600),
(u'RegisterComPlus', None, 5700), ('RegisterComPlus', None, 5700),
(u'RegisterFonts', None, 5300), ('RegisterFonts', None, 5300),
(u'RegisterProduct', None, 6100), ('RegisterProduct', None, 6100),
(u'RegisterTypeLibraries', None, 5500), ('RegisterTypeLibraries', None, 5500),
(u'RegisterUser', None, 6000), ('RegisterUser', None, 6000),
(u'RemoveDuplicateFiles', None, 3400), ('RemoveDuplicateFiles', None, 3400),
(u'RemoveEnvironmentStrings', None, 3300), ('RemoveEnvironmentStrings', None, 3300),
(u'RemoveExistingProducts', None, 6700), ('RemoveExistingProducts', None, 6700),
(u'RemoveFiles', None, 3500), ('RemoveFiles', None, 3500),
(u'RemoveFolders', None, 3600), ('RemoveFolders', None, 3600),
(u'RemoveIniValues', None, 3100), ('RemoveIniValues', None, 3100),
(u'RemoveODBC', None, 2400), ('RemoveODBC', None, 2400),
(u'RemoveRegistryValues', None, 2600), ('RemoveRegistryValues', None, 2600),
(u'RemoveShortcuts', None, 3200), ('RemoveShortcuts', None, 3200),
(u'RMCCPSearch', u'NOT Installed', 600), ('RMCCPSearch', 'NOT Installed', 600),
(u'SelfRegModules', None, 5600), ('SelfRegModules', None, 5600),
(u'SelfUnregModules', None, 2200), ('SelfUnregModules', None, 2200),
(u'SetODBCFolders', None, 1100), ('SetODBCFolders', None, 1100),
(u'StartServices', u'VersionNT', 5900), ('StartServices', 'VersionNT', 5900),
(u'StopServices', u'VersionNT', 1900), ('StopServices', 'VersionNT', 1900),
(u'MsiUnpublishAssemblies', None, 1750), ('MsiUnpublishAssemblies', None, 1750),
(u'UnpublishComponents', None, 1700), ('UnpublishComponents', None, 1700),
(u'UnpublishFeatures', None, 1800), ('UnpublishFeatures', None, 1800),
(u'UnregisterClassInfo', None, 2700), ('UnregisterClassInfo', None, 2700),
(u'UnregisterComPlus', None, 2100), ('UnregisterComPlus', None, 2100),
(u'UnregisterExtensionInfo', None, 2800), ('UnregisterExtensionInfo', None, 2800),
(u'UnregisterFonts', None, 2500), ('UnregisterFonts', None, 2500),
(u'UnregisterMIMEInfo', None, 3000), ('UnregisterMIMEInfo', None, 3000),
(u'UnregisterProgIdInfo', None, 2900), ('UnregisterProgIdInfo', None, 2900),
(u'UnregisterTypeLibraries', None, 2300), ('UnregisterTypeLibraries', None, 2300),
(u'ValidateProductID', None, 700), ('ValidateProductID', None, 700),
(u'WriteEnvironmentStrings', None, 5200), ('WriteEnvironmentStrings', None, 5200),
(u'WriteIniValues', None, 5100), ('WriteIniValues', None, 5100),
(u'WriteRegistryValues', None, 5000), ('WriteRegistryValues', None, 5000),
] ]
InstallUISequence = [ InstallUISequence = [
(u'FileCost', None, 900), ('FileCost', None, 900),
(u'CostInitialize', None, 800), ('CostInitialize', None, 800),
(u'CostFinalize', None, 1000), ('CostFinalize', None, 1000),
(u'ExecuteAction', None, 1300), ('ExecuteAction', None, 1300),
(u'ExitDialog', None, -1), ('ExitDialog', None, -1),
(u'FatalError', None, -3), ('FatalError', None, -3),
(u'UserExit', None, -2), ('UserExit', None, -2),
(u'AppSearch', None, 400), ('AppSearch', None, 400),
(u'CCPSearch', u'NOT Installed', 500), ('CCPSearch', 'NOT Installed', 500),
(u'FindRelatedProducts', None, 200), ('FindRelatedProducts', None, 200),
(u'IsolateComponents', None, 950), ('IsolateComponents', None, 950),
(u'LaunchConditions', None, 100), ('LaunchConditions', None, 100),
(u'MigrateFeatureStates', None, 1200), ('MigrateFeatureStates', None, 1200),
(u'RMCCPSearch', u'NOT Installed', 600), ('RMCCPSearch', 'NOT Installed', 600),
(u'ValidateProductID', None, 700), ('ValidateProductID', None, 700),
] ]
tables=['AdminExecuteSequence', 'AdminUISequence', 'AdvtExecuteSequence', 'InstallExecuteSequence', 'InstallUISequence'] tables=['AdminExecuteSequence', 'AdminUISequence', 'AdvtExecuteSequence', 'InstallExecuteSequence', 'InstallUISequence']
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -537,9 +537,9 @@ class Application: ...@@ -537,9 +537,9 @@ class Application:
if not options: if not options:
print(' None') print(' None')
return return
long = filter(lambda x: x.prefix == '--', options) int = [x for x in options if x.prefix == '--']
short = filter(lambda x: x.prefix == '-', options) short = [x for x in options if x.prefix == '-']
items = short + long items = short + int
for o in options: for o in options:
print(' ',o) print(' ',o)
print() print()
......
...@@ -157,8 +157,8 @@ class ListSlicing(Test): ...@@ -157,8 +157,8 @@ class ListSlicing(Test):
def calibrate(self): def calibrate(self):
n = range(100) n = list(range(100))
r = range(25) r = list(range(25))
for i in range(self.rounds): for i in range(self.rounds):
for j in r: for j in r:
......
...@@ -17,7 +17,7 @@ class WithFinally(Test): ...@@ -17,7 +17,7 @@ class WithFinally(Test):
cm = self.ContextManager() cm = self.ContextManager()
for i in xrange(self.rounds): for i in range(self.rounds):
with cm: pass with cm: pass
with cm: pass with cm: pass
with cm: pass with cm: pass
...@@ -43,7 +43,7 @@ class WithFinally(Test): ...@@ -43,7 +43,7 @@ class WithFinally(Test):
cm = self.ContextManager() cm = self.ContextManager()
for i in xrange(self.rounds): for i in range(self.rounds):
pass pass
...@@ -65,7 +65,7 @@ class TryFinally(Test): ...@@ -65,7 +65,7 @@ class TryFinally(Test):
cm = self.ContextManager() cm = self.ContextManager()
for i in xrange(self.rounds): for i in range(self.rounds):
cm.__enter__() cm.__enter__()
try: pass try: pass
finally: cm.__exit__() finally: cm.__exit__()
...@@ -150,7 +150,7 @@ class TryFinally(Test): ...@@ -150,7 +150,7 @@ class TryFinally(Test):
cm = self.ContextManager() cm = self.ContextManager()
for i in xrange(self.rounds): for i in range(self.rounds):
pass pass
...@@ -171,12 +171,12 @@ class WithRaiseExcept(Test): ...@@ -171,12 +171,12 @@ class WithRaiseExcept(Test):
error = ValueError error = ValueError
be = self.BlockExceptions() be = self.BlockExceptions()
for i in xrange(self.rounds): for i in range(self.rounds):
with be: raise error with be: raise error
with be: raise error with be: raise error
with be: raise error,"something" with be: raise error("something")
with be: raise error,"something" with be: raise error("something")
with be: raise error,"something" with be: raise error("something")
with be: raise error("something") with be: raise error("something")
with be: raise error("something") with be: raise error("something")
with be: raise error("something") with be: raise error("something")
...@@ -186,5 +186,5 @@ class WithRaiseExcept(Test): ...@@ -186,5 +186,5 @@ class WithRaiseExcept(Test):
error = ValueError error = ValueError
be = self.BlockExceptions() be = self.BlockExceptions()
for i in xrange(self.rounds): for i in range(self.rounds):
pass pass
...@@ -23,8 +23,7 @@ def clockres(timer): ...@@ -23,8 +23,7 @@ def clockres(timer):
break break
for i in spin_loops: for i in spin_loops:
d[timer()] = 1 d[timer()] = 1
values = d.keys() values = sorted(d.keys())
values.sort()
min_diff = TEST_TIME min_diff = TEST_TIME
for i in range(len(values) - 1): for i in range(len(values) - 1):
diff = values[i+1] - values[i] diff = values[i+1] - values[i]
......
...@@ -107,15 +107,13 @@ def get_machine_details(): ...@@ -107,15 +107,13 @@ def get_machine_details():
buildno, builddate = platform.python_build() buildno, builddate = platform.python_build()
python = platform.python_version() python = platform.python_version()
try: try:
unichr(100000) chr(100000)
except ValueError: except ValueError:
# UCS2 build (standard) # UCS2 build (standard)
unicode = 'UCS2' unitype = 'UCS2'
except NameError:
unicode = None
else: else:
# UCS4 build (most recent Linux distros) # UCS4 build (most recent Linux distros)
unicode = 'UCS4' unitype = 'UCS4'
bits, linkage = platform.architecture() bits, linkage = platform.architecture()
return { return {
'platform': platform.platform(), 'platform': platform.platform(),
...@@ -127,7 +125,7 @@ def get_machine_details(): ...@@ -127,7 +125,7 @@ def get_machine_details():
'compiler': platform.python_compiler(), 'compiler': platform.python_compiler(),
'buildno': buildno, 'buildno': buildno,
'builddate': builddate, 'builddate': builddate,
'unicode': unicode, 'unicode': unitype,
'bits': bits, 'bits': bits,
} }
......
...@@ -66,7 +66,7 @@ class ColorDB: ...@@ -66,7 +66,7 @@ class ColorDB:
# version the `name', or the CapitalizedVersion, etc. # version the `name', or the CapitalizedVersion, etc.
key = (red, green, blue) key = (red, green, blue)
foundname, aliases = self.__byrgb.get(key, (name, [])) foundname, aliases = self.__byrgb.get(key, (name, []))
if foundname <> name and foundname not in aliases: if foundname != name and foundname not in aliases:
aliases.append(name) aliases.append(name)
self.__byrgb[key] = (foundname, aliases) self.__byrgb[key] = (foundname, aliases)
# add to byname lookup # add to byname lookup
...@@ -122,7 +122,7 @@ class ColorDB: ...@@ -122,7 +122,7 @@ class ColorDB:
self.__allnames = [] self.__allnames = []
for name, aliases in self.__byrgb.values(): for name, aliases in self.__byrgb.values():
self.__allnames.append(name) self.__allnames.append(name)
self.__allnames.sort(key=unicode.lower) self.__allnames.sort(key=str.lower)
return self.__allnames return self.__allnames
def aliases_of(self, red, green, blue): def aliases_of(self, red, green, blue):
...@@ -209,7 +209,7 @@ def rrggbb_to_triplet(color): ...@@ -209,7 +209,7 @@ def rrggbb_to_triplet(color):
"""Converts a #rrggbb color to the tuple (red, green, blue).""" """Converts a #rrggbb color to the tuple (red, green, blue)."""
rgbtuple = _namedict.get(color) rgbtuple = _namedict.get(color)
if rgbtuple is None: if rgbtuple is None:
if color[0] <> '#': if color[0] != '#':
raise BadColor(color) raise BadColor(color)
red = color[1:3] red = color[1:3]
green = color[3:5] green = color[3:5]
...@@ -232,7 +232,7 @@ def triplet_to_rrggbb(rgbtuple): ...@@ -232,7 +232,7 @@ def triplet_to_rrggbb(rgbtuple):
_maxtuple = (256.0,) * 3 _maxtuple = (256.0,) * 3
def triplet_to_fractional_rgb(rgbtuple): def triplet_to_fractional_rgb(rgbtuple):
return map(operator.__div__, rgbtuple, _maxtuple) return list(map(operator.__div__, rgbtuple, _maxtuple))
def triplet_to_brightness(rgbtuple): def triplet_to_brightness(rgbtuple):
......
...@@ -62,32 +62,32 @@ def constant(numchips): ...@@ -62,32 +62,32 @@ def constant(numchips):
# red variations, green+blue = cyan constant # red variations, green+blue = cyan constant
def constant_red_generator(numchips, red, green, blue): def constant_red_generator(numchips, red, green, blue):
seq = constant(numchips) seq = constant(numchips)
return map(None, [red] * numchips, seq, seq) return list(map(None, [red] * numchips, seq, seq))
# green variations, red+blue = magenta constant # green variations, red+blue = magenta constant
def constant_green_generator(numchips, red, green, blue): def constant_green_generator(numchips, red, green, blue):
seq = constant(numchips) seq = constant(numchips)
return map(None, seq, [green] * numchips, seq) return list(map(None, seq, [green] * numchips, seq))
# blue variations, red+green = yellow constant # blue variations, red+green = yellow constant
def constant_blue_generator(numchips, red, green, blue): def constant_blue_generator(numchips, red, green, blue):
seq = constant(numchips) seq = constant(numchips)
return map(None, seq, seq, [blue] * numchips) return list(map(None, seq, seq, [blue] * numchips))
# red variations, green+blue = cyan constant # red variations, green+blue = cyan constant
def constant_cyan_generator(numchips, red, green, blue): def constant_cyan_generator(numchips, red, green, blue):
seq = constant(numchips) seq = constant(numchips)
return map(None, seq, [green] * numchips, [blue] * numchips) return list(map(None, seq, [green] * numchips, [blue] * numchips))
# green variations, red+blue = magenta constant # green variations, red+blue = magenta constant
def constant_magenta_generator(numchips, red, green, blue): def constant_magenta_generator(numchips, red, green, blue):
seq = constant(numchips) seq = constant(numchips)
return map(None, [red] * numchips, seq, [blue] * numchips) return list(map(None, [red] * numchips, seq, [blue] * numchips))
# blue variations, red+green = yellow constant # blue variations, red+green = yellow constant
def constant_yellow_generator(numchips, red, green, blue): def constant_yellow_generator(numchips, red, green, blue):
seq = constant(numchips) seq = constant(numchips)
return map(None, [red] * numchips, [green] * numchips, seq) return list(map(None, [red] * numchips, [green] * numchips, seq))
......
...@@ -28,7 +28,7 @@ class Chooser: ...@@ -28,7 +28,7 @@ class Chooser:
dbfile = options.get('databasefile', self.__databasefile) dbfile = options.get('databasefile', self.__databasefile)
# load the database file # load the database file
colordb = None colordb = None
if dbfile <> self.__databasefile: if dbfile != self.__databasefile:
colordb = ColorDB.get_colordb(dbfile) colordb = ColorDB.get_colordb(dbfile)
if not self.__master: if not self.__master:
from Tkinter import Tk from Tkinter import Tk
......
...@@ -15,7 +15,7 @@ def compare_codecs(encoding1, encoding2): ...@@ -15,7 +15,7 @@ def compare_codecs(encoding1, encoding2):
mismatch = 0 mismatch = 0
# Check encoding # Check encoding
for i in range(sys.maxunicode): for i in range(sys.maxunicode):
u = unichr(i) u = chr(i)
try: try:
c1 = u.encode(encoding1) c1 = u.encode(encoding1)
except UnicodeError as reason: except UnicodeError as reason:
...@@ -34,11 +34,11 @@ def compare_codecs(encoding1, encoding2): ...@@ -34,11 +34,11 @@ def compare_codecs(encoding1, encoding2):
try: try:
u1 = c.decode(encoding1) u1 = c.decode(encoding1)
except UnicodeError: except UnicodeError:
u1 = u'<undefined>' u1 = '<undefined>'
try: try:
u2 = c.decode(encoding2) u2 = c.decode(encoding2)
except UnicodeError: except UnicodeError:
u2 = u'<undefined>' u2 = '<undefined>'
if u1 != u2: if u1 != u2:
print(' * decoding mismatch for 0x%04X: %-14r != %r' % \ print(' * decoding mismatch for 0x%04X: %-14r != %r' % \
(i, u1, u2)) (i, u1, u2))
......
...@@ -55,7 +55,7 @@ def getregentry(): ...@@ -55,7 +55,7 @@ def getregentry():
""") """)
def gencodecs(prefix): def gencodecs(prefix):
for loc, encodings in codecs.iteritems(): for loc, encodings in codecs.items():
for enc in encodings: for enc in encodings:
code = TEMPLATE.substitute(ENCODING=enc.upper(), code = TEMPLATE.substitute(ENCODING=enc.upper(),
encoding=enc.lower(), encoding=enc.lower(),
......
...@@ -32,7 +32,7 @@ import re, os, marshal, codecs ...@@ -32,7 +32,7 @@ import re, os, marshal, codecs
MAX_TABLE_SIZE = 8192 MAX_TABLE_SIZE = 8192
# Standard undefined Unicode code point # Standard undefined Unicode code point
UNI_UNDEFINED = unichr(0xFFFE) UNI_UNDEFINED = chr(0xFFFE)
mapRE = re.compile('((?:0x[0-9a-fA-F]+\+?)+)' mapRE = re.compile('((?:0x[0-9a-fA-F]+\+?)+)'
'\s+' '\s+'
...@@ -62,7 +62,7 @@ def parsecodes(codes, ...@@ -62,7 +62,7 @@ def parsecodes(codes,
l[i] = int(l[i],16) l[i] = int(l[i],16)
except ValueError: except ValueError:
l[i] = None l[i] = None
l = filter(lambda x: x is not None, l) l = [x for x in l if x is not None]
if len(l) == 1: if len(l) == 1:
return l[0] return l[0]
else: else:
...@@ -75,12 +75,12 @@ def readmap(filename): ...@@ -75,12 +75,12 @@ def readmap(filename):
f.close() f.close()
enc2uni = {} enc2uni = {}
identity = [] identity = []
unmapped = range(256) unmapped = list(range(256))
# UTC mapping tables per convention don't include the identity # UTC mapping tables per convention don't include the identity
# mappings for code points 0x00 - 0x1F and 0x7F, unless these are # mappings for code points 0x00 - 0x1F and 0x7F, unless these are
# explicitly mapped to different characters or undefined # explicitly mapped to different characters or undefined
for i in range(32) + [127]: for i in list(range(32)) + [127]:
identity.append(i) identity.append(i)
unmapped.remove(i) unmapped.remove(i)
enc2uni[i] = (i, 'CONTROL CHARACTER') enc2uni[i] = (i, 'CONTROL CHARACTER')
...@@ -138,7 +138,7 @@ def python_mapdef_code(varname, map, comments=1, precisions=(2, 4)): ...@@ -138,7 +138,7 @@ def python_mapdef_code(varname, map, comments=1, precisions=(2, 4)):
l = [] l = []
append = l.append append = l.append
if map.has_key("IDENTITY"): if "IDENTITY" in map:
append("%s = codecs.make_identity_dict(range(%d))" % append("%s = codecs.make_identity_dict(range(%d))" %
(varname, map["IDENTITY"])) (varname, map["IDENTITY"]))
append("%s.update({" % varname) append("%s.update({" % varname)
...@@ -150,8 +150,7 @@ def python_mapdef_code(varname, map, comments=1, precisions=(2, 4)): ...@@ -150,8 +150,7 @@ def python_mapdef_code(varname, map, comments=1, precisions=(2, 4)):
splits = 0 splits = 0
identity = 0 identity = 0
mappings = map.items() mappings = sorted(map.items())
mappings.sort()
i = 0 i = 0
key_precision, value_precision = precisions key_precision, value_precision = precisions
for mapkey, mapvalue in mappings: for mapkey, mapvalue in mappings:
...@@ -199,11 +198,10 @@ def python_tabledef_code(varname, map, comments=1, key_precision=2): ...@@ -199,11 +198,10 @@ def python_tabledef_code(varname, map, comments=1, key_precision=2):
append('%s = (' % varname) append('%s = (' % varname)
# Analyze map and create table dict # Analyze map and create table dict
mappings = map.items() mappings = sorted(map.items())
mappings.sort()
table = {} table = {}
maxkey = 0 maxkey = 0
if map.has_key('IDENTITY'): if 'IDENTITY' in map:
for key in range(256): for key in range(256):
table[key] = (key, '') table[key] = (key, '')
maxkey = 255 maxkey = 255
...@@ -237,7 +235,7 @@ def python_tabledef_code(varname, map, comments=1, key_precision=2): ...@@ -237,7 +235,7 @@ def python_tabledef_code(varname, map, comments=1, key_precision=2):
# 1-n mappings not supported # 1-n mappings not supported
return None return None
else: else:
mapchar = unichr(mapvalue) mapchar = chr(mapvalue)
if mapcomment and comments: if mapcomment and comments:
append(' %r\t# %s -> %s' % (mapchar, append(' %r\t# %s -> %s' % (mapchar,
hexrepr(key, key_precision), hexrepr(key, key_precision),
......
...@@ -71,7 +71,7 @@ def maketables(trace=0): ...@@ -71,7 +71,7 @@ def maketables(trace=0):
EASTASIAN_WIDTH % version, EASTASIAN_WIDTH % version,
DERIVED_CORE_PROPERTIES % version) DERIVED_CORE_PROPERTIES % version)
print(len(list(filter(None, unicode.table))), "characters") print(len(filter(None, unicode.table)), "characters")
for version in old_versions: for version in old_versions:
print("--- Reading", UNICODE_DATA % ("-"+version), "...") print("--- Reading", UNICODE_DATA % ("-"+version), "...")
...@@ -79,7 +79,7 @@ def maketables(trace=0): ...@@ -79,7 +79,7 @@ def maketables(trace=0):
COMPOSITION_EXCLUSIONS % ("-"+version), COMPOSITION_EXCLUSIONS % ("-"+version),
EASTASIAN_WIDTH % ("-"+version), EASTASIAN_WIDTH % ("-"+version),
DERIVED_CORE_PROPERTIES % ("-"+version)) DERIVED_CORE_PROPERTIES % ("-"+version))
print(len(list(filter(None, old_unicode.table))), "characters") print(len(filter(None, old_unicode.table)), "characters")
merge_old_version(version, unicode, old_unicode) merge_old_version(version, unicode, old_unicode)
makeunicodename(unicode, trace) makeunicodename(unicode, trace)
...@@ -152,8 +152,7 @@ def makeunicodedata(unicode, trace): ...@@ -152,8 +152,7 @@ def makeunicodedata(unicode, trace):
prefix = i prefix = i
assert prefix < 256 assert prefix < 256
# content # content
decomp = [prefix + (len(decomp)<<8)] +\ decomp = [prefix + (len(decomp)<<8)] + [int(s, 16) for s in decomp]
list(map(lambda s: int(s, 16), decomp))
# Collect NFC pairs # Collect NFC pairs
if not prefix and len(decomp) == 3 and \ if not prefix and len(decomp) == 3 and \
char not in unicode.exclusions and \ char not in unicode.exclusions and \
...@@ -466,7 +465,7 @@ def makeunicodename(unicode, trace): ...@@ -466,7 +465,7 @@ def makeunicodename(unicode, trace):
if name and name[0] != "<": if name and name[0] != "<":
names[char] = name + chr(0) names[char] = name + chr(0)
print(len(list(filter(lambda n: n is not None, names))), "distinct names") print(len(n for n in names if n is not None), "distinct names")
# collect unique words from names (note that we differ between # collect unique words from names (note that we differ between
# words inside a sentence, and words ending a sentence. the # words inside a sentence, and words ending a sentence. the
...@@ -740,7 +739,7 @@ class UnicodeData: ...@@ -740,7 +739,7 @@ class UnicodeData:
# public attributes # public attributes
self.filename = filename self.filename = filename
self.table = table self.table = table
self.chars = range(0x110000) # unicode 3.2 self.chars = list(range(0x110000)) # unicode 3.2
file = open(exclusions) file = open(exclusions)
self.exclusions = {} self.exclusions = {}
...@@ -763,7 +762,7 @@ class UnicodeData: ...@@ -763,7 +762,7 @@ class UnicodeData:
s = s.split()[0].split(';') s = s.split()[0].split(';')
if '..' in s[0]: if '..' in s[0]:
first, last = [int(c, 16) for c in s[0].split('..')] first, last = [int(c, 16) for c in s[0].split('..')]
chars = range(first, last+1) chars = list(range(first, last+1))
else: else:
chars = [int(s[0], 16)] chars = [int(s[0], 16)]
for char in chars: for char in chars:
...@@ -785,7 +784,7 @@ class UnicodeData: ...@@ -785,7 +784,7 @@ class UnicodeData:
p = p.strip() p = p.strip()
if ".." in r: if ".." in r:
first, last = [int(c, 16) for c in r.split('..')] first, last = [int(c, 16) for c in r.split('..')]
chars = range(first, last+1) chars = list(range(first, last+1))
else: else:
chars = [int(r, 16)] chars = [int(r, 16)]
for char in chars: for char in chars:
...@@ -796,7 +795,7 @@ class UnicodeData: ...@@ -796,7 +795,7 @@ class UnicodeData:
def uselatin1(self): def uselatin1(self):
# restrict character range to ISO Latin 1 # restrict character range to ISO Latin 1
self.chars = range(256) self.chars = list(range(256))
# hash table tools # hash table tools
......
...@@ -5,12 +5,12 @@ if sys.maxunicode == 65535: ...@@ -5,12 +5,12 @@ if sys.maxunicode == 65535:
def gen_category(cats): def gen_category(cats):
for i in range(0, 0x110000): for i in range(0, 0x110000):
if unicodedata.category(unichr(i)) in cats: if unicodedata.category(chr(i)) in cats:
yield(i) yield(i)
def gen_bidirectional(cats): def gen_bidirectional(cats):
for i in range(0, 0x110000): for i in range(0, 0x110000):
if unicodedata.bidirectional(unichr(i)) in cats: if unicodedata.bidirectional(chr(i)) in cats:
yield(i) yield(i)
def compact_set(l): def compact_set(l):
...@@ -63,14 +63,14 @@ for l in data: ...@@ -63,14 +63,14 @@ for l in data:
if m: if m:
if m.group(1) == "Start": if m.group(1) == "Start":
if curname: if curname:
raise "Double Start",(curname, l) raise RuntimeError("Double Start", (curname, l))
curname = m.group(2) curname = m.group(2)
table = {} table = {}
tables.append((curname, table)) tables.append((curname, table))
continue continue
else: else:
if not curname: if not curname:
raise "End without start", l raise RuntimeError("End without start", l)
curname = None curname = None
continue continue
if not curname: if not curname:
...@@ -87,7 +87,7 @@ for l in data: ...@@ -87,7 +87,7 @@ for l in data:
try: try:
start, end = fields start, end = fields
except ValueError: except ValueError:
raise "Unpacking problem", l raise RuntimeError("Unpacking problem", l)
else: else:
start = end = fields[0] start = end = fields[0]
start = int(start, 16) start = int(start, 16)
...@@ -146,8 +146,7 @@ def in_table_a1(code): ...@@ -146,8 +146,7 @@ def in_table_a1(code):
name, table = tables[0] name, table = tables[0]
del tables[0] del tables[0]
assert name == "B.1" assert name == "B.1"
table = table.keys() table = sorted(table.keys())
table.sort()
print(""" print("""
b1_set = """ + compact_set(table) + """ b1_set = """ + compact_set(table) + """
def in_table_b1(code): def in_table_b1(code):
...@@ -177,8 +176,7 @@ for k,v in table_b2.items(): ...@@ -177,8 +176,7 @@ for k,v in table_b2.items():
if map(ord, unichr(k).lower()) != v: if map(ord, unichr(k).lower()) != v:
b3_exceptions[k] = u"".join(map(unichr,v)) b3_exceptions[k] = u"".join(map(unichr,v))
b3 = b3_exceptions.items() b3 = sorted(b3_exceptions.items())
b3.sort()
print(""" print("""
b3_exceptions = {""") b3_exceptions = {""")
...@@ -207,7 +205,7 @@ def map_table_b3(code): ...@@ -207,7 +205,7 @@ def map_table_b3(code):
def map_table_b2(a): def map_table_b2(a):
al = map_table_b3(a) al = map_table_b3(a)
b = unicodedata.normalize("NFKC", al) b = unicodedata.normalize("NFKC", al)
bl = u"".join([map_table_b3(ch) for ch in b]) bl = "".join([map_table_b3(ch) for ch in b])
c = unicodedata.normalize("NFKC", bl) c = unicodedata.normalize("NFKC", bl)
if b != c: if b != c:
return c return c
...@@ -216,7 +214,7 @@ def map_table_b2(a): ...@@ -216,7 +214,7 @@ def map_table_b2(a):
specials = {} specials = {}
for k,v in table_b2.items(): for k,v in table_b2.items():
if map(ord, map_table_b2(unichr(k))) != v: if list(map(ord, map_table_b2(chr(k)))) != v:
specials[k] = v specials[k] = v
# B.3 should not add any additional special cases # B.3 should not add any additional special cases
...@@ -321,9 +319,9 @@ name, table = tables[0] ...@@ -321,9 +319,9 @@ name, table = tables[0]
del tables[0] del tables[0]
assert name == "C.4" assert name == "C.4"
nonchar = set(range(0xFDD0,0xFDF0) + nonchar = set(range(0xFDD0,0xFDF0))
range(0xFFFE,0x110000,0x10000) + nonchar.update(range(0xFFFE,0x110000,0x10000))
range(0xFFFF,0x110000,0x10000)) nonchar.update(range(0xFFFF,0x110000,0x10000))
table = set(table.keys()) table = set(table.keys())
assert table == nonchar assert table == nonchar
...@@ -353,8 +351,7 @@ name, table = tables[0] ...@@ -353,8 +351,7 @@ name, table = tables[0]
del tables[0] del tables[0]
assert name == "C.6" assert name == "C.6"
table = table.keys() table = sorted(table.keys())
table.sort()
print(""" print("""
c6_set = """ + compact_set(table) + """ c6_set = """ + compact_set(table) + """
...@@ -367,8 +364,7 @@ name, table = tables[0] ...@@ -367,8 +364,7 @@ name, table = tables[0]
del tables[0] del tables[0]
assert name == "C.7" assert name == "C.7"
table = table.keys() table = sorted(table.keys())
table.sort()
print(""" print("""
c7_set = """ + compact_set(table) + """ c7_set = """ + compact_set(table) + """
...@@ -381,8 +377,7 @@ name, table = tables[0] ...@@ -381,8 +377,7 @@ name, table = tables[0]
del tables[0] del tables[0]
assert name == "C.8" assert name == "C.8"
table = table.keys() table = sorted(table.keys())
table.sort()
print(""" print("""
c8_set = """ + compact_set(table) + """ c8_set = """ + compact_set(table) + """
...@@ -395,8 +390,7 @@ name, table = tables[0] ...@@ -395,8 +390,7 @@ name, table = tables[0]
del tables[0] del tables[0]
assert name == "C.9" assert name == "C.9"
table = table.keys() table = sorted(table.keys())
table.sort()
print(""" print("""
c9_set = """ + compact_set(table) + """ c9_set = """ + compact_set(table) + """
......
...@@ -257,20 +257,20 @@ class CheckerWindow(webchecker.Checker): ...@@ -257,20 +257,20 @@ class CheckerWindow(webchecker.Checker):
d = self.__details d = self.__details
d.clear() d.clear()
d.put("URL: %s\n" % self.format_url(url)) d.put("URL: %s\n" % self.format_url(url))
if self.bad.has_key(url): if url in self.bad:
d.put("Error: %s\n" % str(self.bad[url])) d.put("Error: %s\n" % str(self.bad[url]))
if url in self.roots: if url in self.roots:
d.put("Note: This is a root URL\n") d.put("Note: This is a root URL\n")
if self.done.has_key(url): if url in self.done:
d.put("Status: checked\n") d.put("Status: checked\n")
o = self.done[url] o = self.done[url]
elif self.todo.has_key(url): elif url in self.todo:
d.put("Status: to check\n") d.put("Status: to check\n")
o = self.todo[url] o = self.todo[url]
else: else:
d.put("Status: unknown (!)\n") d.put("Status: unknown (!)\n")
o = [] o = []
if (not url[1]) and self.errors.has_key(url[0]): if (not url[1]) and url[0] in self.errors:
d.put("Bad links from this page:\n") d.put("Bad links from this page:\n")
for triple in self.errors[url[0]]: for triple in self.errors[url[0]]:
link, rawlink, msg = triple link, rawlink, msg = triple
...@@ -298,9 +298,9 @@ class CheckerWindow(webchecker.Checker): ...@@ -298,9 +298,9 @@ class CheckerWindow(webchecker.Checker):
def newlink(self, url, origin): def newlink(self, url, origin):
webchecker.Checker.newlink(self, url, origin) webchecker.Checker.newlink(self, url, origin)
if self.done.has_key(url): if url in self.done:
self.__done.insert(url) self.__done.insert(url)
elif self.todo.has_key(url): elif url in self.todo:
self.__todo.insert(url) self.__todo.insert(url)
self.newstatus() self.newstatus()
...@@ -351,7 +351,7 @@ class ListPanel: ...@@ -351,7 +351,7 @@ class ListPanel:
def selectedindices(self): def selectedindices(self):
l = self.list.curselection() l = self.list.curselection()
if not l: return [] if not l: return []
return map(int, l) return list(map(int, l))
def insert(self, url): def insert(self, url):
if url not in self.items: if url not in self.items:
......
...@@ -265,7 +265,7 @@ class Checker: ...@@ -265,7 +265,7 @@ class Checker:
self.reset() self.reset()
def setflags(self, **kw): def setflags(self, **kw):
for key in kw.keys(): for key in kw:
if key not in self.validflags: if key not in self.validflags:
raise NameError("invalid keyword argument: %s" % str(key)) raise NameError("invalid keyword argument: %s" % str(key))
for key, value in kw.items(): for key, value in kw.items():
...@@ -307,7 +307,7 @@ class Checker: ...@@ -307,7 +307,7 @@ class Checker:
(self.roots, self.todo, self.done, self.bad, self.round) = state (self.roots, self.todo, self.done, self.bad, self.round) = state
for root in self.roots: for root in self.roots:
self.addrobot(root) self.addrobot(root)
for url in self.bad.keys(): for url in self.bad:
self.markerror(url) self.markerror(url)
def addroot(self, root, add_to_do = 1): def addroot(self, root, add_to_do = 1):
...@@ -327,7 +327,7 @@ class Checker: ...@@ -327,7 +327,7 @@ class Checker:
def addrobot(self, root): def addrobot(self, root):
root = urlparse.urljoin(root, "/") root = urlparse.urljoin(root, "/")
if self.robots.has_key(root): return if root in self.robots: return
url = urlparse.urljoin(root, "/robots.txt") url = urlparse.urljoin(root, "/robots.txt")
self.robots[root] = rp = robotparser.RobotFileParser() self.robots[root] = rp = robotparser.RobotFileParser()
self.note(2, "Parsing %s", url) self.note(2, "Parsing %s", url)
...@@ -342,8 +342,7 @@ class Checker: ...@@ -342,8 +342,7 @@ class Checker:
while self.todo: while self.todo:
self.round = self.round + 1 self.round = self.round + 1
self.note(0, "\nRound %d (%s)\n", self.round, self.status()) self.note(0, "\nRound %d (%s)\n", self.round, self.status())
urls = self.todo.keys() urls = sorted(self.todo.keys())
urls.sort()
del urls[self.roundsize:] del urls[self.roundsize:]
for url in urls: for url in urls:
self.dopage(url) self.dopage(url)
...@@ -366,8 +365,7 @@ class Checker: ...@@ -366,8 +365,7 @@ class Checker:
self.message("\nNo errors") self.message("\nNo errors")
return return
self.message("\nError Report:") self.message("\nError Report:")
sources = self.errors.keys() sources = sorted(self.errors.keys())
sources.sort()
for source in sources: for source in sources:
triples = self.errors[source] triples = self.errors[source]
self.message("") self.message("")
...@@ -432,7 +430,7 @@ class Checker: ...@@ -432,7 +430,7 @@ class Checker:
self.markdone(url_pair) self.markdone(url_pair)
def newlink(self, url, origin): def newlink(self, url, origin):
if self.done.has_key(url): if url in self.done:
self.newdonelink(url, origin) self.newdonelink(url, origin)
else: else:
self.newtodolink(url, origin) self.newtodolink(url, origin)
...@@ -446,7 +444,7 @@ class Checker: ...@@ -446,7 +444,7 @@ class Checker:
self.note(3, " Done link %s", self.format_url(url)) self.note(3, " Done link %s", self.format_url(url))
# Make sure that if it's bad, that the origin gets added. # Make sure that if it's bad, that the origin gets added.
if self.bad.has_key(url): if url in self.bad:
source, rawlink = origin source, rawlink = origin
triple = url, rawlink, self.bad[url] triple = url, rawlink, self.bad[url]
self.seterror(source, triple) self.seterror(source, triple)
...@@ -454,7 +452,7 @@ class Checker: ...@@ -454,7 +452,7 @@ class Checker:
def newtodolink(self, url, origin): def newtodolink(self, url, origin):
# Call self.format_url(), since the URL here # Call self.format_url(), since the URL here
# is now a (URL, fragment) pair. # is now a (URL, fragment) pair.
if self.todo.has_key(url): if url in self.todo:
if origin not in self.todo[url]: if origin not in self.todo[url]:
self.todo[url].append(origin) self.todo[url].append(origin)
self.note(3, " Seen todo link %s", self.format_url(url)) self.note(3, " Seen todo link %s", self.format_url(url))
...@@ -486,7 +484,7 @@ class Checker: ...@@ -486,7 +484,7 @@ class Checker:
# Incoming argument name is a (URL, fragment) pair. # Incoming argument name is a (URL, fragment) pair.
# The page may have been cached in the name_table variable. # The page may have been cached in the name_table variable.
url, fragment = url_pair url, fragment = url_pair
if self.name_table.has_key(url): if url in self.name_table:
return self.name_table[url] return self.name_table[url]
scheme, path = urllib.splittype(url) scheme, path = urllib.splittype(url)
...@@ -550,7 +548,7 @@ class Checker: ...@@ -550,7 +548,7 @@ class Checker:
return None return None
def checkforhtml(self, info, url): def checkforhtml(self, info, url):
if info.has_key('content-type'): if 'content-type' in info:
ctype = cgi.parse_header(info['content-type'])[0].lower() ctype = cgi.parse_header(info['content-type'])[0].lower()
if ';' in ctype: if ';' in ctype:
# handle content-type: text/html; charset=iso8859-1 : # handle content-type: text/html; charset=iso8859-1 :
...@@ -566,13 +564,13 @@ class Checker: ...@@ -566,13 +564,13 @@ class Checker:
return 0 return 0
def setgood(self, url): def setgood(self, url):
if self.bad.has_key(url): if url in self.bad:
del self.bad[url] del self.bad[url]
self.changed = 1 self.changed = 1
self.note(0, "(Clear previously seen error)") self.note(0, "(Clear previously seen error)")
def setbad(self, url, msg): def setbad(self, url, msg):
if self.bad.has_key(url) and self.bad[url] == msg: if url in self.bad and self.bad[url] == msg:
self.note(0, "(Seen this error before)") self.note(0, "(Seen this error before)")
return return
self.bad[url] = msg self.bad[url] = msg
...@@ -882,7 +880,7 @@ class MyHTMLParser(sgmllib.SGMLParser): ...@@ -882,7 +880,7 @@ class MyHTMLParser(sgmllib.SGMLParser):
self.check_name_id(attributes) self.check_name_id(attributes)
def getlinks(self): def getlinks(self):
return self.links.keys() return list(self.links.keys())
def getbase(self): def getbase(self):
return self.base return self.base
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment