Commit 6afaeb75 authored by Collin Winter's avatar Collin Winter

Convert print statements to function calls in Tools/.

parent e5d0e843
...@@ -401,9 +401,9 @@ class Helpwin: ...@@ -401,9 +401,9 @@ class Helpwin:
def usage(code, msg=''): def usage(code, msg=''):
print __doc__ % globals() print(__doc__ % globals())
if msg: if msg:
print msg print(msg)
sys.exit(code) sys.exit(code)
...@@ -455,11 +455,11 @@ def main(): ...@@ -455,11 +455,11 @@ def main():
i = i + 1 i = i + 1
continue continue
elif arg in ('-v', '--version'): elif arg in ('-v', '--version'):
print '''\ print('''\
audiopy -- a program to control the Solaris audio device. audiopy -- a program to control the Solaris audio device.
Contact: Barry Warsaw Contact: Barry Warsaw
Email: bwarsaw@python.org Email: bwarsaw@python.org
Version: %s''' % __version__ Version: %s''' % __version__)
sys.exit(0) sys.exit(0)
for long, short, io, mask in options: for long, short, io, mask in options:
if arg in (long, short): if arg in (long, short):
......
...@@ -16,7 +16,7 @@ INOUT = IN_OUT = "in-out" ...@@ -16,7 +16,7 @@ INOUT = IN_OUT = "in-out"
class BaseFunctionGenerator: class BaseFunctionGenerator:
def __init__(self, name, condition=None, callname=None, modifiers=None): def __init__(self, name, condition=None, callname=None, modifiers=None):
if DEBUG: print "<--", name if DEBUG: print("<--", name)
self.name = name self.name = name
if callname: if callname:
self.callname = callname self.callname = callname
...@@ -36,7 +36,7 @@ class BaseFunctionGenerator: ...@@ -36,7 +36,7 @@ class BaseFunctionGenerator:
def generate(self): def generate(self):
if not self.checkgenerate(): if not self.checkgenerate():
return return
if DEBUG: print "-->", self.name if DEBUG: print("-->", self.name)
if self.condition: if self.condition:
Output() Output()
Output(self.condition) Output(self.condition)
...@@ -157,7 +157,7 @@ class FunctionGenerator(BaseFunctionGenerator): ...@@ -157,7 +157,7 @@ class FunctionGenerator(BaseFunctionGenerator):
continue continue
else: else:
typeName = "?" typeName = "?"
print "Nameless type", arg.type print("Nameless type", arg.type)
str = typeName + ' ' + arg.name str = typeName + ' ' + arg.name
if arg.mode in (InMode, InOutMode): if arg.mode in (InMode, InOutMode):
...@@ -294,7 +294,7 @@ def _test(): ...@@ -294,7 +294,7 @@ def _test():
(int, 'status', ErrorMode), (int, 'status', ErrorMode),
) )
eggs.setprefix("spam") eggs.setprefix("spam")
print "/* START */" print("/* START */")
eggs.generate() eggs.generate()
......
...@@ -9,7 +9,7 @@ class GeneratorGroup: ...@@ -9,7 +9,7 @@ class GeneratorGroup:
def add(self, g, dupcheck=0): def add(self, g, dupcheck=0):
if dupcheck: if dupcheck:
if g in self.generators: if g in self.generators:
print 'DUP', g.name print('DUP', g.name)
return return
g.setprefix(self.prefix) g.setprefix(self.prefix)
self.generators.append(g) self.generators.append(g)
...@@ -33,7 +33,7 @@ def _test(): ...@@ -33,7 +33,7 @@ def _test():
group = GeneratorGroup("spam") group = GeneratorGroup("spam")
eggs = FunctionGenerator(void, "eggs") eggs = FunctionGenerator(void, "eggs")
group.add(eggs) group.add(eggs)
print "/* START */" print("/* START */")
group.generate() group.generate()
if __name__ == "__main__": if __name__ == "__main__":
......
...@@ -162,11 +162,11 @@ if missing: raise "Missing Types" ...@@ -162,11 +162,11 @@ if missing: raise "Missing Types"
def error(self, format, *args): def error(self, format, *args):
if self.silent >= 0: if self.silent >= 0:
print format%args print(format%args)
def report(self, format, *args): def report(self, format, *args):
if not self.silent: if not self.silent:
print format%args print(format%args)
def writeinitialdefs(self): def writeinitialdefs(self):
pass pass
...@@ -221,7 +221,7 @@ if missing: raise "Missing Types" ...@@ -221,7 +221,7 @@ if missing: raise "Missing Types"
""" """
f = self.openrepairfile() f = self.openrepairfile()
if not f: return [] if not f: return []
print "Reading repair file", repr(f.name), "..." print("Reading repair file", repr(f.name), "...")
list = [] list = []
lineno = 0 lineno = 0
while 1: while 1:
...@@ -237,31 +237,31 @@ if missing: raise "Missing Types" ...@@ -237,31 +237,31 @@ if missing: raise "Missing Types"
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, 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))
continue continue
[fpat, pat, rep] = words [fpat, pat, rep] = words
if not fpat: fpat = "*" if not fpat: fpat = "*"
if not pat: if not pat:
print "Line", startlineno, print("Line", startlineno, end=' ')
print "Empty pattern" print("Empty pattern")
print repr(line) print(repr(line))
continue continue
patparts = [s.strip() for s in pat.split(',')] patparts = [s.strip() for s in pat.split(',')]
repparts = [s.strip() for s in rep.split(',')] repparts = [s.strip() for s in rep.split(',')]
patterns = [] patterns = []
for p in patparts: for p in patparts:
if not p: if not p:
print "Line", startlineno, print("Line", startlineno, end=' ')
print "Empty pattern part" print("Empty pattern part")
print repr(line) print(repr(line))
continue continue
pattern = p.split() pattern = p.split()
if len(pattern) > 3: if len(pattern) > 3:
print "Line", startlineno, print("Line", startlineno, end=' ')
print "Pattern part has > 3 words" print("Pattern part has > 3 words")
print repr(line) print(repr(line))
pattern = pattern[:3] pattern = pattern[:3]
else: else:
while len(pattern) < 3: while len(pattern) < 3:
...@@ -270,15 +270,15 @@ if missing: raise "Missing Types" ...@@ -270,15 +270,15 @@ if missing: raise "Missing Types"
replacements = [] replacements = []
for p in repparts: for p in repparts:
if not p: if not p:
print "Line", startlineno, print("Line", startlineno, end=' ')
print "Empty replacement part" print("Empty replacement part")
print repr(line) print(repr(line))
continue continue
replacement = p.split() replacement = p.split()
if len(replacement) > 3: if len(replacement) > 3:
print "Line", startlineno, print("Line", startlineno, end=' ')
print "Pattern part has > 3 words" print("Pattern part has > 3 words")
print repr(line) print(repr(line))
replacement = replacement[:3] replacement = replacement[:3]
else: else:
while len(replacement) < 3: while len(replacement) < 3:
...@@ -294,8 +294,8 @@ if missing: raise "Missing Types" ...@@ -294,8 +294,8 @@ if missing: raise "Missing Types"
try: try:
return open(filename, "rU") return open(filename, "rU")
except IOError as msg: except IOError as msg:
print repr(filename), ":", msg print(repr(filename), ":", msg)
print "Cannot open repair file -- assume no repair needed" print("Cannot open repair file -- assume no repair needed")
return None return None
def initfiles(self): def initfiles(self):
......
...@@ -28,6 +28,6 @@ except SystemExit as n: ...@@ -28,6 +28,6 @@ except SystemExit as n:
sys.exit(n) sys.exit(n)
except: except:
t, v, tb = sys.exc_info() t, v, tb = sys.exc_info()
print print()
import cgi import cgi
cgi.print_exception(t, v, tb) cgi.print_exception(t, v, tb)
...@@ -158,8 +158,8 @@ def send_my_cookie(ui): ...@@ -158,8 +158,8 @@ def send_my_cookie(ui):
then = now + COOKIE_LIFETIME then = now + COOKIE_LIFETIME
gmt = time.gmtime(then) gmt = time.gmtime(then)
path = os.environ.get('SCRIPT_NAME', '/cgi-bin/') path = os.environ.get('SCRIPT_NAME', '/cgi-bin/')
print "Set-Cookie: %s=%s; path=%s;" % (name, value, path), print("Set-Cookie: %s=%s; path=%s;" % (name, value, path), end=' ')
print time.strftime("expires=%a, %d-%b-%y %X GMT", gmt) print(time.strftime("expires=%a, %d-%b-%y %X GMT", gmt))
class MagicDict: class MagicDict:
...@@ -273,22 +273,22 @@ class FaqEntry: ...@@ -273,22 +273,22 @@ class FaqEntry:
raw = 0 raw = 0
continue continue
if raw: if raw:
print line print(line)
continue continue
if not line.strip(): if not line.strip():
if pre: if pre:
print '</PRE>' print('</PRE>')
pre = 0 pre = 0
else: else:
print '<P>' print('<P>')
else: else:
if not line[0].isspace(): if not line[0].isspace():
if pre: if pre:
print '</PRE>' print('</PRE>')
pre = 0 pre = 0
else: else:
if not pre: if not pre:
print '<PRE>' print('<PRE>')
pre = 1 pre = 1
if '/' in line or '@' in line: if '/' in line or '@' in line:
line = translate(line, pre) line = translate(line, pre)
...@@ -296,16 +296,16 @@ class FaqEntry: ...@@ -296,16 +296,16 @@ class FaqEntry:
line = escape(line) line = escape(line)
if not pre and '*' in line: if not pre and '*' in line:
line = emphasize(line) line = emphasize(line)
print line print(line)
if pre: if pre:
print '</PRE>' print('</PRE>')
pre = 0 pre = 0
if edit: if edit:
print '<P>' print('<P>')
emit(ENTRY_FOOTER, self) emit(ENTRY_FOOTER, self)
if self.last_changed_date: if self.last_changed_date:
emit(ENTRY_LOGINFO, self) emit(ENTRY_LOGINFO, self)
print '<P>' print('<P>')
class FaqDir: class FaqDir:
...@@ -377,7 +377,7 @@ class FaqWizard: ...@@ -377,7 +377,7 @@ class FaqWizard:
self.dir = FaqDir() self.dir = FaqDir()
def go(self): def go(self):
print 'Content-type: text/html' print('Content-type: text/html')
req = self.ui.req or 'home' req = self.ui.req or 'home'
mname = 'do_%s' % req mname = 'do_%s' % req
try: try:
...@@ -493,7 +493,7 @@ class FaqWizard: ...@@ -493,7 +493,7 @@ class FaqWizard:
mtime = mtime = entry.getmtime() mtime = mtime = entry.getmtime()
if mtime > latest: if mtime > latest:
latest = mtime latest = mtime
print time.strftime(LAST_CHANGED, time.localtime(latest)) print(time.strftime(LAST_CHANGED, time.localtime(latest)))
emit(EXPLAIN_MARKS) emit(EXPLAIN_MARKS)
def format_all(self, files, edit=1, headers=1): def format_all(self, files, edit=1, headers=1):
...@@ -637,7 +637,7 @@ class FaqWizard: ...@@ -637,7 +637,7 @@ class FaqWizard:
rev = line[9:].split() rev = line[9:].split()
mami = revparse(rev) mami = revparse(rev)
if not mami: if not mami:
print line print(line)
else: else:
emit(REVISIONLINK, entry, rev=rev, line=line) emit(REVISIONLINK, entry, rev=rev, line=line)
if mami[1] > 1: if mami[1] > 1:
...@@ -647,7 +647,7 @@ class FaqWizard: ...@@ -647,7 +647,7 @@ class FaqWizard:
emit(DIFFLINK, entry, prev=rev, rev=headrev) emit(DIFFLINK, entry, prev=rev, rev=headrev)
else: else:
headrev = rev headrev = rev
print print()
athead = 0 athead = 0
else: else:
athead = 0 athead = 0
...@@ -656,8 +656,8 @@ class FaqWizard: ...@@ -656,8 +656,8 @@ class FaqWizard:
athead = 1 athead = 1
sys.stdout.write('<HR>') sys.stdout.write('<HR>')
else: else:
print line print(line)
print '</PRE>' print('</PRE>')
def do_revision(self): def do_revision(self):
entry = self.dir.open(self.ui.file) entry = self.dir.open(self.ui.file)
...@@ -686,8 +686,8 @@ class FaqWizard: ...@@ -686,8 +686,8 @@ class FaqWizard:
def shell(self, command): def shell(self, command):
output = os.popen(command).read() output = os.popen(command).read()
sys.stdout.write('<PRE>') sys.stdout.write('<PRE>')
print escape(output) print(escape(output))
print '</PRE>' print('</PRE>')
def do_new(self): def do_new(self):
entry = self.dir.new(section=int(self.ui.section)) entry = self.dir.new(section=int(self.ui.section))
...@@ -759,9 +759,9 @@ class FaqWizard: ...@@ -759,9 +759,9 @@ class FaqWizard:
def cantcommit(self): def cantcommit(self):
self.prologue(T_CANTCOMMIT) self.prologue(T_CANTCOMMIT)
print CANTCOMMIT_HEAD print(CANTCOMMIT_HEAD)
self.errordetail() self.errordetail()
print CANTCOMMIT_TAIL print(CANTCOMMIT_TAIL)
def errordetail(self): def errordetail(self):
if PASSWORD and self.ui.password != PASSWORD: if PASSWORD and self.ui.password != PASSWORD:
...@@ -827,7 +827,7 @@ class FaqWizard: ...@@ -827,7 +827,7 @@ class FaqWizard:
else: else:
self.error(T_COMMITFAILED) self.error(T_COMMITFAILED)
emit(COMMITFAILED, sts=sts) emit(COMMITFAILED, sts=sts)
print '<PRE>%s</PRE>' % escape(output) print('<PRE>%s</PRE>' % escape(output))
try: try:
os.unlink(tf.name) os.unlink(tf.name)
......
...@@ -27,7 +27,7 @@ class BaseMetaclass(type): ...@@ -27,7 +27,7 @@ class BaseMetaclass(type):
def dump_methoddef(self, f, functions, vars): def dump_methoddef(self, f, functions, vars):
def p(templ, vars=vars): # helper function to generate output def p(templ, vars=vars): # helper function to generate output
print >> f, templ % vars print(templ % vars, file=f)
if not functions: if not functions:
return return
...@@ -77,12 +77,12 @@ class ModuleMetaclass(BaseMetaclass): ...@@ -77,12 +77,12 @@ class ModuleMetaclass(BaseMetaclass):
def dump(self, f): def dump(self, f):
def p(templ, vars=self.__vars): # helper function to generate output def p(templ, vars=self.__vars): # helper function to generate output
print >> f, templ % vars print(templ % vars, file=f)
p(template.module_start) p(template.module_start)
if self.__members: if self.__members:
p(template.member_include) p(template.member_include)
print >> f print(file=f)
if self.__doc__: if self.__doc__:
p(template.module_doc) p(template.module_doc)
...@@ -111,10 +111,10 @@ class TypeMetaclass(BaseMetaclass): ...@@ -111,10 +111,10 @@ class TypeMetaclass(BaseMetaclass):
# defined after initvars() so that __vars is defined # defined after initvars() so that __vars is defined
def p(templ, vars=self.__vars): def p(templ, vars=self.__vars):
print >> f, templ % vars print(templ % vars, file=f)
if self.struct is not None: if self.struct is not None:
print >> f, unindent(self.struct, False) print(unindent(self.struct, False), file=f)
if self.__doc__: if self.__doc__:
p(template.docstring) p(template.docstring)
...@@ -185,7 +185,7 @@ class TypeMetaclass(BaseMetaclass): ...@@ -185,7 +185,7 @@ class TypeMetaclass(BaseMetaclass):
def dump_memberdef(self, f): def dump_memberdef(self, f):
def p(templ, vars=self.__vars): def p(templ, vars=self.__vars):
print >> f, templ % vars print(templ % vars, file=f)
if not self.__members: if not self.__members:
return return
...@@ -196,7 +196,7 @@ class TypeMetaclass(BaseMetaclass): ...@@ -196,7 +196,7 @@ class TypeMetaclass(BaseMetaclass):
def dump_slots(self, f): def dump_slots(self, f):
def p(templ, vars=self.__vars): def p(templ, vars=self.__vars):
print >> f, templ % vars print(templ % vars, file=f)
if self.struct: if self.struct:
p(template.dealloc_func, {"name" : self.__slots[TP_DEALLOC]}) p(template.dealloc_func, {"name" : self.__slots[TP_DEALLOC]})
...@@ -206,12 +206,12 @@ class TypeMetaclass(BaseMetaclass): ...@@ -206,12 +206,12 @@ class TypeMetaclass(BaseMetaclass):
val = self.__slots.get(s, s.default) val = self.__slots.get(s, s.default)
ntabs = 4 - (4 + len(val)) / 8 ntabs = 4 - (4 + len(val)) / 8
line = " %s,%s/* %s */" % (val, "\t" * ntabs, s.name) line = " %s,%s/* %s */" % (val, "\t" * ntabs, s.name)
print >> f, line print(line, file=f)
p(template.type_struct_end) p(template.type_struct_end)
def dump_init(self, f): def dump_init(self, f):
def p(templ): def p(templ):
print >> f, templ % self.__vars print(templ % self.__vars, file=f)
p(template.type_init_type) p(template.type_init_type)
p(template.module_add_type) p(template.module_add_type)
......
...@@ -96,7 +96,7 @@ class VarArgs(_ArgumentList): ...@@ -96,7 +96,7 @@ class VarArgs(_ArgumentList):
def dump_decls(self, f): def dump_decls(self, f):
for a in self.args: for a in self.args:
print >> f, " %s" % a.decl() print(" %s" % a.decl(), file=f)
def ArgumentList(func, method): def ArgumentList(func, method):
code = func.func_code code = func.func_code
...@@ -135,7 +135,7 @@ class Function: ...@@ -135,7 +135,7 @@ class Function:
def p(templ, vars=None): # helper function to generate output def p(templ, vars=None): # helper function to generate output
if vars is None: if vars is None:
vars = self.vars vars = self.vars
print >> f, templ % vars print(templ % vars, file=f)
if self.__doc__: if self.__doc__:
p(template.docstring) p(template.docstring)
......
...@@ -68,6 +68,6 @@ class member(object): ...@@ -68,6 +68,6 @@ class member(object):
def dump(self, f): def dump(self, f):
if self.doc is None: if self.doc is None:
print >> f, template.memberdef_def % self.vars print(template.memberdef_def % self.vars, file=f)
else: else:
print >> f, template.memberdef_def_doc % self.vars print(template.memberdef_def_doc % self.vars, file=f)
...@@ -49,7 +49,7 @@ def pprint(data): ...@@ -49,7 +49,7 @@ def pprint(data):
items = data.items() items = data.items()
items.sort() items.sort()
for k,v in items: 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):
...@@ -57,17 +57,17 @@ def print_differences(data, olddata): ...@@ -57,17 +57,17 @@ def print_differences(data, olddata):
items.sort() items.sort()
for k, v in items: for k, v in items:
if not data.has_key(k): if not data.has_key(k):
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' % \
(k, olddata[k], data[k]) (k, olddata[k], data[k]))
# Additions are not mentioned # Additions are not mentioned
if __name__ == '__main__': if __name__ == '__main__':
data = locale.locale_alias.copy() data = locale.locale_alias.copy()
data.update(parse(LOCALE_ALIAS)) data.update(parse(LOCALE_ALIAS))
print_differences(data, locale.locale_alias) print_differences(data, locale.locale_alias)
print print()
print 'locale_alias = {' print('locale_alias = {')
pprint(data) pprint(data)
print '}' print('}')
...@@ -38,9 +38,9 @@ MESSAGES = {} ...@@ -38,9 +38,9 @@ MESSAGES = {}
def usage(code, msg=''): def usage(code, msg=''):
print >> sys.stderr, __doc__ print(__doc__, file=sys.stderr)
if msg: if msg:
print >> sys.stderr, msg print(msg, file=sys.stderr)
sys.exit(code) sys.exit(code)
...@@ -111,7 +111,7 @@ def make(filename, outfile): ...@@ -111,7 +111,7 @@ def make(filename, outfile):
try: try:
lines = open(infile).readlines() lines = open(infile).readlines()
except IOError as msg: except IOError as msg:
print >> sys.stderr, msg print(msg, file=sys.stderr)
sys.exit(1) sys.exit(1)
section = None section = None
...@@ -154,9 +154,9 @@ def make(filename, outfile): ...@@ -154,9 +154,9 @@ def make(filename, outfile):
elif section == STR: elif section == STR:
msgstr += l msgstr += l
else: else:
print >> sys.stderr, 'Syntax error on %s:%d' % (infile, lno), \ print('Syntax error on %s:%d' % (infile, lno), \
'before:' 'before:', file=sys.stderr)
print >> sys.stderr, l print(l, file=sys.stderr)
sys.exit(1) sys.exit(1)
# Add last entry # Add last entry
if section == STR: if section == STR:
...@@ -168,7 +168,7 @@ def make(filename, outfile): ...@@ -168,7 +168,7 @@ def make(filename, outfile):
try: try:
open(outfile,"wb").write(output) open(outfile,"wb").write(output)
except IOError as msg: except IOError as msg:
print >> sys.stderr, msg print(msg, file=sys.stderr)
...@@ -185,14 +185,14 @@ def main(): ...@@ -185,14 +185,14 @@ def main():
if opt in ('-h', '--help'): if opt in ('-h', '--help'):
usage(0) usage(0)
elif opt in ('-V', '--version'): elif opt in ('-V', '--version'):
print >> sys.stderr, "msgfmt.py", __version__ print("msgfmt.py", __version__, file=sys.stderr)
sys.exit(0) sys.exit(0)
elif opt in ('-o', '--output-file'): elif opt in ('-o', '--output-file'):
outfile = arg outfile = arg
# do it # do it
if not args: if not args:
print >> sys.stderr, 'No input file given' print('No input file given', file=sys.stderr)
print >> sys.stderr, "Try `msgfmt --help' for more information." print("Try `msgfmt --help' for more information.", file=sys.stderr)
return return
for filename in args: for filename in args:
......
...@@ -197,9 +197,9 @@ msgstr "" ...@@ -197,9 +197,9 @@ msgstr ""
def usage(code, msg=''): def usage(code, msg=''):
print >> sys.stderr, __doc__ % globals() print(__doc__ % globals(), file=sys.stderr)
if msg: if msg:
print >> sys.stderr, msg print(msg, file=sys.stderr)
sys.exit(code) sys.exit(code)
...@@ -423,13 +423,13 @@ class TokenEater: ...@@ -423,13 +423,13 @@ class TokenEater:
elif ttype not in [tokenize.COMMENT, token.INDENT, token.DEDENT, elif ttype not in [tokenize.COMMENT, token.INDENT, token.DEDENT,
token.NEWLINE, tokenize.NL]: token.NEWLINE, tokenize.NL]:
# warn if we see anything else than STRING or whitespace # warn if we see anything else than STRING or whitespace
print >> sys.stderr, _( print(_(
'*** %(file)s:%(lineno)s: Seen unexpected token "%(token)s"' '*** %(file)s:%(lineno)s: Seen unexpected token "%(token)s"'
) % { ) % {
'token': tstring, 'token': tstring,
'file': self.__curfile, 'file': self.__curfile,
'lineno': self.__lineno 'lineno': self.__lineno
} }, file=sys.stderr)
self.__state = self.__waiting self.__state = self.__waiting
def __addentry(self, msg, lineno=None, isdocstring=0): def __addentry(self, msg, lineno=None, isdocstring=0):
...@@ -448,7 +448,7 @@ class TokenEater: ...@@ -448,7 +448,7 @@ class TokenEater:
timestamp = time.strftime('%Y-%m-%d %H:%M+%Z') timestamp = time.strftime('%Y-%m-%d %H:%M+%Z')
# The time stamp in the header doesn't have the same format as that # The time stamp in the header doesn't have the same format as that
# generated by xgettext... # generated by xgettext...
print >> fp, pot_header % {'time': timestamp, 'version': __version__} print(pot_header % {'time': timestamp, 'version': __version__}, file=fp)
# Sort the entries. First sort each particular entry's keys, then # Sort the entries. First sort each particular entry's keys, then
# sort all the entries by their first item. # sort all the entries by their first item.
reverse = {} reverse = {}
...@@ -477,8 +477,8 @@ class TokenEater: ...@@ -477,8 +477,8 @@ class TokenEater:
elif options.locationstyle == options.SOLARIS: elif options.locationstyle == options.SOLARIS:
for filename, lineno in v: for filename, lineno in v:
d = {'filename': filename, 'lineno': lineno} d = {'filename': filename, 'lineno': lineno}
print >>fp, _( print(_(
'# File: %(filename)s, line: %(lineno)d') % d '# File: %(filename)s, line: %(lineno)d') % d, file=fp)
elif options.locationstyle == options.GNU: elif options.locationstyle == options.GNU:
# fit as many locations on one line, as long as the # fit as many locations on one line, as long as the
# resulting line length doesn't exceeds 'options.width' # resulting line length doesn't exceeds 'options.width'
...@@ -489,14 +489,14 @@ class TokenEater: ...@@ -489,14 +489,14 @@ class TokenEater:
if len(locline) + len(s) <= options.width: if len(locline) + len(s) <= options.width:
locline = locline + s locline = locline + s
else: else:
print >> fp, locline print(locline, file=fp)
locline = "#:" + s locline = "#:" + s
if len(locline) > 2: if len(locline) > 2:
print >> fp, locline print(locline, file=fp)
if isdocstring: if isdocstring:
print >> fp, '#, docstring' print('#, docstring', file=fp)
print >> fp, 'msgid', normalize(k) print('msgid', normalize(k), file=fp)
print >> fp, 'msgstr ""\n' print('msgstr ""\n', file=fp)
...@@ -570,7 +570,7 @@ def main(): ...@@ -570,7 +570,7 @@ def main():
elif opt in ('-v', '--verbose'): elif opt in ('-v', '--verbose'):
options.verbose = 1 options.verbose = 1
elif opt in ('-V', '--version'): elif opt in ('-V', '--version'):
print _('pygettext.py (xgettext for Python) %s') % __version__ print(_('pygettext.py (xgettext for Python) %s') % __version__)
sys.exit(0) sys.exit(0)
elif opt in ('-w', '--width'): elif opt in ('-w', '--width'):
try: try:
...@@ -603,8 +603,8 @@ def main(): ...@@ -603,8 +603,8 @@ def main():
options.toexclude = fp.readlines() options.toexclude = fp.readlines()
fp.close() fp.close()
except IOError: except IOError:
print >> sys.stderr, _( print(_(
"Can't read --exclude-file: %s") % options.excludefilename "Can't read --exclude-file: %s") % options.excludefilename, file=sys.stderr)
sys.exit(1) sys.exit(1)
else: else:
options.toexclude = [] options.toexclude = []
...@@ -623,12 +623,12 @@ def main(): ...@@ -623,12 +623,12 @@ def main():
for filename in args: for filename in args:
if filename == '-': if filename == '-':
if options.verbose: if options.verbose:
print _('Reading standard input') print(_('Reading standard input'))
fp = sys.stdin fp = sys.stdin
closep = 0 closep = 0
else: else:
if options.verbose: if options.verbose:
print _('Working on %s') % filename print(_('Working on %s') % filename)
fp = open(filename) fp = open(filename)
closep = 1 closep = 1
try: try:
...@@ -636,8 +636,8 @@ def main(): ...@@ -636,8 +636,8 @@ def main():
try: try:
tokenize.tokenize(fp.readline, eater) tokenize.tokenize(fp.readline, eater)
except tokenize.TokenError as e: except tokenize.TokenError as e:
print >> sys.stderr, '%s: %s, line %d, column %d' % ( print('%s: %s, line %d, column %d' % (
e[0], filename, e[1][0], e[1][1]) e[0], filename, e[1][0], e[1][1]), file=sys.stderr)
finally: finally:
if closep: if closep:
fp.close() fp.close()
......
...@@ -198,7 +198,7 @@ def _go(): ...@@ -198,7 +198,7 @@ def _go():
'', '',
-1, -1,
'OK') 'OK')
print 'pressed button', i print('pressed button', i)
i = dialog(mainWidget, i = dialog(mainWidget,
'File Modified', 'File Modified',
'File "tcl.h" has been modified since ' 'File "tcl.h" has been modified since '
...@@ -209,13 +209,13 @@ def _go(): ...@@ -209,13 +209,13 @@ def _go():
'Save File', 'Save File',
'Discard Changes', 'Discard Changes',
'Return To Editor') 'Return To Editor')
print 'pressed button', i print('pressed button', i)
print message('Test of message') print(message('Test of message'))
print askyn('Test of yes/no') print(askyn('Test of yes/no'))
print askync('Test of yes/no/cancel') print(askync('Test of yes/no/cancel'))
print askstr('Type a string:') print(askstr('Type a string:'))
print strdialog(mainWidget, 'Question', 'Another string:', '', print(strdialog(mainWidget, 'Question', 'Another string:', '',
0, 'Save', 'Save as text') 0, 'Save', 'Save as text'))
def _test(): def _test():
import sys import sys
......
...@@ -114,7 +114,7 @@ def build_mingw_lib(lib_file, def_file, dll_file, mingw_lib): ...@@ -114,7 +114,7 @@ def build_mingw_lib(lib_file, def_file, dll_file, mingw_lib):
dlltool = find_executable('dlltool') dlltool = find_executable('dlltool')
if not nm or not dlltool: if not nm or not dlltool:
print warning % "nm and/or dlltool were not found" print(warning % "nm and/or dlltool were not found")
return False return False
nm_command = '%s -Cs %s' % (nm, lib_file) nm_command = '%s -Cs %s' % (nm, lib_file)
...@@ -123,23 +123,23 @@ def build_mingw_lib(lib_file, def_file, dll_file, mingw_lib): ...@@ -123,23 +123,23 @@ def build_mingw_lib(lib_file, def_file, dll_file, mingw_lib):
export_match = re.compile(r"^_imp__(.*) in python\d+\.dll").match export_match = re.compile(r"^_imp__(.*) in python\d+\.dll").match
f = open(def_file,'w') f = open(def_file,'w')
print >>f, "LIBRARY %s" % dll_file print("LIBRARY %s" % dll_file, file=f)
print >>f, "EXPORTS" print("EXPORTS", file=f)
nm_pipe = os.popen(nm_command) nm_pipe = os.popen(nm_command)
for line in nm_pipe.readlines(): for line in nm_pipe.readlines():
m = export_match(line) m = export_match(line)
if m: if m:
print >>f, m.group(1) print(m.group(1), file=f)
f.close() f.close()
exit = nm_pipe.close() exit = nm_pipe.close()
if exit: if exit:
print warning % "nm did not run successfully" print(warning % "nm did not run successfully")
return False return False
if os.system(dlltool_command) != 0: if os.system(dlltool_command) != 0:
print warning % "dlltool did not run successfully" print(warning % "dlltool did not run successfully")
return False return False
return True return True
...@@ -875,7 +875,7 @@ def add_files(db): ...@@ -875,7 +875,7 @@ def add_files(db):
# Check if _ctypes.pyd exists # Check if _ctypes.pyd exists
have_ctypes = os.path.exists(srcdir+"/PCBuild/_ctypes.pyd") have_ctypes = os.path.exists(srcdir+"/PCBuild/_ctypes.pyd")
if not have_ctypes: if not have_ctypes:
print "WARNING: _ctypes.pyd not found, ctypes will not be included" print("WARNING: _ctypes.pyd not found, ctypes will not be included")
extensions.remove("_ctypes.pyd") extensions.remove("_ctypes.pyd")
# Add all .py files in Lib, except lib-tk, test # Add all .py files in Lib, except lib-tk, test
...@@ -953,7 +953,7 @@ def add_files(db): ...@@ -953,7 +953,7 @@ def add_files(db):
if f.endswith(".au") or f.endswith(".gif"): if f.endswith(".au") or f.endswith(".gif"):
lib.add_file(f) lib.add_file(f)
else: else:
print "WARNING: New file %s in email/test/data" % f print("WARNING: New file %s in email/test/data" % f)
for f in os.listdir(lib.absolute): for f in os.listdir(lib.absolute):
if os.path.isdir(os.path.join(lib.absolute, f)): if os.path.isdir(os.path.join(lib.absolute, f)):
pydirs.append((lib, f)) pydirs.append((lib, f))
...@@ -968,7 +968,7 @@ def add_files(db): ...@@ -968,7 +968,7 @@ def add_files(db):
if f=="_tkinter.pyd": if f=="_tkinter.pyd":
continue continue
if not os.path.exists(srcdir+"/PCBuild/"+f): if not os.path.exists(srcdir+"/PCBuild/"+f):
print "WARNING: Missing extension", f print("WARNING: Missing extension", f)
continue continue
dlls.append(f) dlls.append(f)
lib.add_file(f) lib.add_file(f)
...@@ -982,7 +982,7 @@ def add_files(db): ...@@ -982,7 +982,7 @@ def add_files(db):
lib.add_file(srcdir+"/"+sqlite_dir+sqlite_arch+"/sqlite3.dll") lib.add_file(srcdir+"/"+sqlite_dir+sqlite_arch+"/sqlite3.dll")
if have_tcl: if have_tcl:
if not os.path.exists(srcdir+"/PCBuild/_tkinter.pyd"): if not os.path.exists(srcdir+"/PCBuild/_tkinter.pyd"):
print "WARNING: Missing _tkinter.pyd" print("WARNING: Missing _tkinter.pyd")
else: else:
lib.start_component("TkDLLs", tcltk) lib.start_component("TkDLLs", tcltk)
lib.add_file("_tkinter.pyd") lib.add_file("_tkinter.pyd")
...@@ -994,7 +994,7 @@ def add_files(db): ...@@ -994,7 +994,7 @@ def add_files(db):
for f in glob.glob1(srcdir+"/PCBuild", "*.pyd"): for f in glob.glob1(srcdir+"/PCBuild", "*.pyd"):
if f.endswith("_d.pyd"): continue # debug version if f.endswith("_d.pyd"): continue # debug version
if f in dlls: continue if f in dlls: continue
print "WARNING: Unknown extension", f print("WARNING: Unknown extension", f)
# Add headers # Add headers
default_feature.set_current() default_feature.set_current()
......
...@@ -95,7 +95,7 @@ class Table: ...@@ -95,7 +95,7 @@ class Table:
index -= 1 index -= 1
unk = type & ~knownbits unk = type & ~knownbits
if unk: if unk:
print "%s.%s unknown bits %x" % (self.name, name, unk) print("%s.%s unknown bits %x" % (self.name, name, unk))
size = type & datasizemask size = type & datasizemask
dtype = type & typemask dtype = type & typemask
if dtype == type_string: if dtype == type_string:
...@@ -114,7 +114,7 @@ class Table: ...@@ -114,7 +114,7 @@ class Table:
tname="OBJECT" tname="OBJECT"
else: else:
tname="unknown" tname="unknown"
print "%s.%sunknown integer type %d" % (self.name, name, size) print("%s.%sunknown integer type %d" % (self.name, name, size))
if type & type_nullable: if type & type_nullable:
flags = "" flags = ""
else: else:
...@@ -202,7 +202,7 @@ def gen_sequence(destpath, msipath): ...@@ -202,7 +202,7 @@ def gen_sequence(destpath, msipath):
v = seqmsi.OpenView("SELECT * FROM _Tables"); v = seqmsi.OpenView("SELECT * FROM _Tables");
v.Execute(None) v.Execute(None)
f = open(destpath, "w") f = open(destpath, "w")
print >>f, "import msilib,os;dirname=os.path.dirname(__file__)" print("import msilib,os;dirname=os.path.dirname(__file__)", file=f)
tables = [] tables = []
while 1: while 1:
r = v.Fetch() r = v.Fetch()
...@@ -364,9 +364,9 @@ class CAB: ...@@ -364,9 +364,9 @@ class CAB:
logical = self.gen_id(dir, file) logical = self.gen_id(dir, file)
self.index += 1 self.index += 1
if full.find(" ")!=-1: if full.find(" ")!=-1:
print >>self.file, '"%s" %s' % (full, logical) print('"%s" %s' % (full, logical), file=self.file)
else: else:
print >>self.file, '%s %s' % (full, logical) print('%s %s' % (full, logical), file=self.file)
return self.index, logical return self.index, logical
def commit(self, db): def commit(self, db):
...@@ -386,7 +386,7 @@ class CAB: ...@@ -386,7 +386,7 @@ class CAB:
if not os.path.exists(cabarc):continue if not os.path.exists(cabarc):continue
break break
else: else:
print "WARNING: cabarc.exe not found in registry" print("WARNING: cabarc.exe not found in registry")
cabarc = "cabarc.exe" cabarc = "cabarc.exe"
cmd = r'"%s" -m lzx:21 n %s.cab @%s.txt' % (cabarc, self.name, self.name) cmd = r'"%s" -m lzx:21 n %s.cab @%s.txt' % (cabarc, self.name, self.name)
p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
......
...@@ -547,11 +547,11 @@ class Benchmark: ...@@ -547,11 +547,11 @@ class Benchmark:
min_overhead * MILLI_SECONDS)) min_overhead * MILLI_SECONDS))
self.roundtimes.append(total_eff_time) self.roundtimes.append(total_eff_time)
if self.verbose: if self.verbose:
print((' ' print(' '
' ------------------------------')) ' ------------------------------')
print((' ' print(' '
' Totals: %6.0fms' % ' Totals: %6.0fms' %
(total_eff_time * MILLI_SECONDS))) (total_eff_time * MILLI_SECONDS))
print() print()
else: else:
print('* Round %i done in %.3f seconds.' % (i+1, print('* Round %i done in %.3f seconds.' % (i+1,
...@@ -595,8 +595,8 @@ class Benchmark: ...@@ -595,8 +595,8 @@ class Benchmark:
def print_benchmark(self, hidenoise=0, limitnames=None): def print_benchmark(self, hidenoise=0, limitnames=None):
print(('Test ' print('Test '
' minimum average operation overhead')) ' minimum average operation overhead')
print('-' * LINE) print('-' * LINE)
tests = sorted(self.tests.items()) tests = sorted(self.tests.items())
total_min_time = 0.0 total_min_time = 0.0
...@@ -619,20 +619,20 @@ class Benchmark: ...@@ -619,20 +619,20 @@ class Benchmark:
op_avg * MICRO_SECONDS, op_avg * MICRO_SECONDS,
min_overhead *MILLI_SECONDS)) min_overhead *MILLI_SECONDS))
print('-' * LINE) print('-' * LINE)
print(('Totals: ' print('Totals: '
' %6.0fms %6.0fms' % ' %6.0fms %6.0fms' %
(total_min_time * MILLI_SECONDS, (total_min_time * MILLI_SECONDS,
total_avg_time * MILLI_SECONDS, total_avg_time * MILLI_SECONDS,
))) ))
print() print()
def print_comparison(self, compare_to, hidenoise=0, limitnames=None): def print_comparison(self, compare_to, hidenoise=0, limitnames=None):
# Check benchmark versions # Check benchmark versions
if compare_to.version != self.version: if compare_to.version != self.version:
print(('* Benchmark versions differ: ' print('* Benchmark versions differ: '
'cannot compare this benchmark to "%s" !' % 'cannot compare this benchmark to "%s" !' %
compare_to.name)) compare_to.name)
print() print()
self.print_benchmark(hidenoise=hidenoise, self.print_benchmark(hidenoise=hidenoise,
limitnames=limitnames) limitnames=limitnames)
...@@ -640,10 +640,10 @@ class Benchmark: ...@@ -640,10 +640,10 @@ class Benchmark:
# Print header # Print header
compare_to.print_header('Comparing with') compare_to.print_header('Comparing with')
print(('Test ' print('Test '
' minimum run-time average run-time')) ' minimum run-time average run-time')
print((' ' print(' '
' this other diff this other diff')) ' this other diff this other diff')
print('-' * LINE) print('-' * LINE)
# Print test comparisons # Print test comparisons
...@@ -726,7 +726,7 @@ class Benchmark: ...@@ -726,7 +726,7 @@ class Benchmark:
(other_total_avg_time * compare_to.warp) - 1.0) * PERCENT) (other_total_avg_time * compare_to.warp) - 1.0) * PERCENT)
else: else:
avg_diff = 'n/a' avg_diff = 'n/a'
print(('Totals: ' print('Totals: '
' %5.0fms %5.0fms %7s %5.0fms %5.0fms %7s' % ' %5.0fms %5.0fms %7s %5.0fms %5.0fms %7s' %
(total_min_time * MILLI_SECONDS, (total_min_time * MILLI_SECONDS,
(other_total_min_time * compare_to.warp/self.warp (other_total_min_time * compare_to.warp/self.warp
...@@ -736,7 +736,7 @@ class Benchmark: ...@@ -736,7 +736,7 @@ class Benchmark:
(other_total_avg_time * compare_to.warp/self.warp (other_total_avg_time * compare_to.warp/self.warp
* MILLI_SECONDS), * MILLI_SECONDS),
avg_diff avg_diff
))) ))
print() print()
print('(this=%s, other=%s)' % (self.name, print('(this=%s, other=%s)' % (self.name,
compare_to.name)) compare_to.name))
......
...@@ -57,7 +57,7 @@ class ColorDB: ...@@ -57,7 +57,7 @@ class ColorDB:
# get this compiled regular expression from derived class # get this compiled regular expression from derived class
mo = self._re.match(line) mo = self._re.match(line)
if not mo: if not mo:
print >> sys.stderr, 'Error in', fp.name, ' line', lineno print('Error in', fp.name, ' line', lineno, file=sys.stderr)
lineno += 1 lineno += 1
continue continue
# extract the red, green, blue, and name # extract the red, green, blue, and name
...@@ -254,26 +254,26 @@ def triplet_to_brightness(rgbtuple): ...@@ -254,26 +254,26 @@ def triplet_to_brightness(rgbtuple):
if __name__ == '__main__': if __name__ == '__main__':
colordb = get_colordb('/usr/openwin/lib/rgb.txt') colordb = get_colordb('/usr/openwin/lib/rgb.txt')
if not colordb: if not colordb:
print 'No parseable color database found' print('No parseable color database found')
sys.exit(1) sys.exit(1)
# on my system, this color matches exactly # on my system, this color matches exactly
target = 'navy' target = 'navy'
red, green, blue = rgbtuple = colordb.find_byname(target) red, green, blue = rgbtuple = colordb.find_byname(target)
print target, ':', red, green, blue, triplet_to_rrggbb(rgbtuple) print(target, ':', red, green, blue, triplet_to_rrggbb(rgbtuple))
name, aliases = colordb.find_byrgb(rgbtuple) name, aliases = colordb.find_byrgb(rgbtuple)
print 'name:', name, 'aliases:', COMMASPACE.join(aliases) print('name:', name, 'aliases:', COMMASPACE.join(aliases))
r, g, b = (1, 1, 128) # nearest to navy r, g, b = (1, 1, 128) # nearest to navy
r, g, b = (145, 238, 144) # nearest to lightgreen r, g, b = (145, 238, 144) # nearest to lightgreen
r, g, b = (255, 251, 250) # snow r, g, b = (255, 251, 250) # snow
print 'finding nearest to', target, '...' print('finding nearest to', target, '...')
import time import time
t0 = time.time() t0 = time.time()
nearest = colordb.nearest(r, g, b) nearest = colordb.nearest(r, g, b)
t1 = time.time() t1 = time.time()
print 'found nearest color', nearest, 'in', t1-t0, 'seconds' print('found nearest color', nearest, 'in', t1-t0, 'seconds')
# dump the database # dump the database
for n in colordb.unique_names(): for n in colordb.unique_names():
r, g, b = colordb.find_byname(n) r, g, b = colordb.find_byname(n)
aliases = colordb.aliases_of(r, g, b) aliases = colordb.aliases_of(r, g, b)
print '%20s: (%3d/%3d/%3d) == %s' % (n, r, g, b, print('%20s: (%3d/%3d/%3d) == %s' % (n, r, g, b,
SPACE.join(aliases[1:])) SPACE.join(aliases[1:])))
...@@ -85,9 +85,9 @@ def docstring(): ...@@ -85,9 +85,9 @@ def docstring():
def usage(code, msg=''): def usage(code, msg=''):
print docstring() print(docstring())
if msg: if msg:
print msg print(msg)
sys.exit(code) sys.exit(code)
...@@ -111,7 +111,7 @@ def initial_color(s, colordb): ...@@ -111,7 +111,7 @@ def initial_color(s, colordb):
# this to be escaped, which is a pain # this to be escaped, which is a pain
r, g, b = scan_color('#' + s) r, g, b = scan_color('#' + s)
if r is None: if r is None:
print 'Bad initial color, using gray50:', s print('Bad initial color, using gray50:', s)
r, g, b = scan_color('gray50') r, g, b = scan_color('gray50')
if r is None: if r is None:
usage(1, 'Cannot find an initial color to use') usage(1, 'Cannot find an initial color to use')
...@@ -203,11 +203,11 @@ def main(): ...@@ -203,11 +203,11 @@ def main():
if opt in ('-h', '--help'): if opt in ('-h', '--help'):
usage(0) usage(0)
elif opt in ('-v', '--version'): elif opt in ('-v', '--version'):
print """\ print("""\
Pynche -- The PYthon Natural Color and Hue Editor. Pynche -- The PYthon Natural Color and Hue Editor.
Contact: %(AUTHNAME)s Contact: %(AUTHNAME)s
Email: %(AUTHEMAIL)s Email: %(AUTHEMAIL)s
Version: %(__version__)s""" % globals() Version: %(__version__)s""" % globals())
sys.exit(0) sys.exit(0)
elif opt in ('-d', '--database'): elif opt in ('-d', '--database'):
dbfile = arg dbfile = arg
......
...@@ -65,8 +65,7 @@ class Switchboard: ...@@ -65,8 +65,7 @@ class Switchboard:
fp = open(initfile) fp = open(initfile)
self.__optiondb = marshal.load(fp) self.__optiondb = marshal.load(fp)
if not isinstance(self.__optiondb, DictType): if not isinstance(self.__optiondb, DictType):
print >> sys.stderr, \ print('Problem reading options from file:', initfile, file=sys.stderr)
'Problem reading options from file:', initfile
self.__optiondb = {} self.__optiondb = {}
except (IOError, EOFError, ValueError): except (IOError, EOFError, ValueError):
pass pass
...@@ -119,8 +118,8 @@ class Switchboard: ...@@ -119,8 +118,8 @@ class Switchboard:
try: try:
fp = open(self.__initfile, 'w') fp = open(self.__initfile, 'w')
except IOError: except IOError:
print >> sys.stderr, 'Cannot write options to file:', \ print('Cannot write options to file:', \
self.__initfile self.__initfile, file=sys.stderr)
else: else:
marshal.dump(self.__optiondb, fp) marshal.dump(self.__optiondb, fp)
finally: finally:
......
...@@ -109,14 +109,14 @@ class Stats: ...@@ -109,14 +109,14 @@ class Stats:
cols.insert(0, "ext") cols.insert(0, "ext")
def printheader(): def printheader():
for col in cols: for col in cols:
print "%*s" % (colwidth[col], col), print("%*s" % (colwidth[col], col), end=' ')
print print()
printheader() printheader()
for ext in exts: for ext in exts:
for col in cols: for col in cols:
value = self.stats[ext].get(col, "") value = self.stats[ext].get(col, "")
print "%*s" % (colwidth[col], value), print("%*s" % (colwidth[col], value), end=' ')
print print()
printheader() # Another header at the bottom printheader() # Another header at the bottom
def main(): def main():
......
...@@ -52,8 +52,8 @@ def main(): ...@@ -52,8 +52,8 @@ def main():
size = st[ST_SIZE] size = st[ST_SIZE]
age = now - anytime age = now - anytime
byteyears = float(size) * float(age) / secs_per_year byteyears = float(size) * float(age) / secs_per_year
print filename.ljust(maxlen), print(filename.ljust(maxlen), end=' ')
print repr(int(byteyears)).rjust(8) print(repr(int(byteyears)).rjust(8))
sys.exit(status) sys.exit(status)
......
...@@ -65,7 +65,7 @@ def main(): ...@@ -65,7 +65,7 @@ def main():
def check(file): def check(file):
if os.path.isdir(file) and not os.path.islink(file): if os.path.isdir(file) and not os.path.islink(file):
if verbose: if verbose:
print "%r: listing directory" % (file,) print("%r: listing directory" % (file,))
names = os.listdir(file) names = os.listdir(file)
for name in names: for name in names:
fullname = os.path.join(file, name) fullname = os.path.join(file, name)
...@@ -82,11 +82,11 @@ def check(file): ...@@ -82,11 +82,11 @@ def check(file):
return return
if verbose > 1: if verbose > 1:
print "checking %r ..." % (file,) print("checking %r ..." % (file,))
ok = AppendChecker(file, f).run() ok = AppendChecker(file, f).run()
if verbose and ok: if verbose and ok:
print "%r: Clean bill of health." % (file,) print("%r: Clean bill of health." % (file,))
[FIND_DOT, [FIND_DOT,
FIND_APPEND, FIND_APPEND,
...@@ -149,8 +149,8 @@ class AppendChecker: ...@@ -149,8 +149,8 @@ class AppendChecker:
state = FIND_DOT state = FIND_DOT
elif token == "," and self.level == 1: elif token == "," and self.level == 1:
self.nerrors = self.nerrors + 1 self.nerrors = self.nerrors + 1
print "%s(%d):\n%s" % (self.fname, self.lineno, print("%s(%d):\n%s" % (self.fname, self.lineno,
self.line) self.line))
# don't gripe about this stmt again # don't gripe about this stmt again
state = FIND_STMT state = FIND_STMT
......
...@@ -17,15 +17,15 @@ def main(): ...@@ -17,15 +17,15 @@ def main():
silent = 1 silent = 1
MAGIC = imp.get_magic() MAGIC = imp.get_magic()
if not silent: if not silent:
print 'Using MAGIC word', repr(MAGIC) print('Using MAGIC word', repr(MAGIC))
for dirname in sys.path: for dirname in sys.path:
try: try:
names = os.listdir(dirname) names = os.listdir(dirname)
except os.error: except os.error:
print 'Cannot list directory', repr(dirname) print('Cannot list directory', repr(dirname))
continue continue
if not silent: if not silent:
print 'Checking ', repr(dirname), '...' print('Checking ', repr(dirname), '...')
names.sort() names.sort()
for name in names: for name in names:
if name[-3:] == '.py': if name[-3:] == '.py':
...@@ -33,29 +33,29 @@ def main(): ...@@ -33,29 +33,29 @@ def main():
try: try:
st = os.stat(name) st = os.stat(name)
except os.error: except os.error:
print 'Cannot stat', repr(name) print('Cannot stat', repr(name))
continue continue
if verbose: if verbose:
print 'Check', repr(name), '...' print('Check', repr(name), '...')
name_c = name + 'c' name_c = name + 'c'
try: try:
f = open(name_c, 'r') f = open(name_c, 'r')
except IOError: except IOError:
print 'Cannot open', repr(name_c) print('Cannot open', repr(name_c))
continue continue
magic_str = f.read(4) magic_str = f.read(4)
mtime_str = f.read(4) mtime_str = f.read(4)
f.close() f.close()
if magic_str <> MAGIC: if magic_str <> MAGIC:
print 'Bad MAGIC word in ".pyc" file', print('Bad MAGIC word in ".pyc" file', end=' ')
print repr(name_c) print(repr(name_c))
continue continue
mtime = get_long(mtime_str) mtime = get_long(mtime_str)
if mtime == 0 or mtime == -1: if mtime == 0 or mtime == -1:
print 'Bad ".pyc" file', repr(name_c) print('Bad ".pyc" file', repr(name_c))
elif mtime <> st[ST_MTIME]: elif mtime <> st[ST_MTIME]:
print 'Out-of-date ".pyc" file', print('Out-of-date ".pyc" file', end=' ')
print repr(name_c) print(repr(name_c))
def get_long(s): def get_long(s):
if len(s) <> 4: if len(s) <> 4:
......
...@@ -78,7 +78,7 @@ def main(): ...@@ -78,7 +78,7 @@ def main():
def check(file): def check(file):
if os.path.isdir(file) and not os.path.islink(file): if os.path.isdir(file) and not os.path.islink(file):
if verbose: if verbose:
print "listing directory", file print("listing directory", file)
names = os.listdir(file) names = os.listdir(file)
for name in names: for name in names:
fullname = os.path.join(file, name) fullname = os.path.join(file, name)
...@@ -89,7 +89,7 @@ def check(file): ...@@ -89,7 +89,7 @@ def check(file):
return return
if verbose: if verbose:
print "checking", file, "...", print("checking", file, "...", end=' ')
try: try:
f = open(file) f = open(file)
except IOError as msg: except IOError as msg:
...@@ -103,33 +103,33 @@ def check(file): ...@@ -103,33 +103,33 @@ def check(file):
f.close() f.close()
if changed: if changed:
if verbose: if verbose:
print "changed." print("changed.")
if dryrun: if dryrun:
print "But this is a dry run, so leaving it alone." print("But this is a dry run, so leaving it alone.")
for s, e, line in changed: for s, e, line in changed:
print "%r lines %d-%d" % (file, s+1, e+1) print("%r lines %d-%d" % (file, s+1, e+1))
for i in range(s, e+1): for i in range(s, e+1):
print ff.lines[i], print(ff.lines[i], end=' ')
if line is None: if line is None:
print "-- deleted" print("-- deleted")
else: else:
print "-- change to:" print("-- change to:")
print line, print(line, end=' ')
if not dryrun: if not dryrun:
bak = file + ".bak" bak = file + ".bak"
if os.path.exists(bak): if os.path.exists(bak):
os.remove(bak) os.remove(bak)
os.rename(file, bak) os.rename(file, bak)
if verbose: if verbose:
print "renamed", file, "to", bak print("renamed", file, "to", bak)
g = open(file, "w") g = open(file, "w")
ff.write(g) ff.write(g)
g.close() g.close()
if verbose: if verbose:
print "wrote new", file print("wrote new", file)
else: else:
if verbose: if verbose:
print "unchanged." print("unchanged.")
class FutureFinder: class FutureFinder:
......
...@@ -102,7 +102,7 @@ def combine(fname): ...@@ -102,7 +102,7 @@ def combine(fname):
addr, addr2rc[addr], addr2guts[addr] = m.groups() addr, addr2rc[addr], addr2guts[addr] = m.groups()
before += 1 before += 1
else: else:
print '??? skipped:', line print('??? skipped:', line)
after = 0 after = 0
for line in read(fi, crack, True): for line in read(fi, crack, True):
...@@ -111,17 +111,17 @@ def combine(fname): ...@@ -111,17 +111,17 @@ def combine(fname):
assert m assert m
addr, rc, guts = m.groups() # guts is type name here addr, rc, guts = m.groups() # guts is type name here
if addr not in addr2rc: if addr not in addr2rc:
print '??? new object created while tearing down:', line.rstrip() print('??? new object created while tearing down:', line.rstrip())
continue continue
print addr, print(addr, end=' ')
if rc == addr2rc[addr]: if rc == addr2rc[addr]:
print '[%s]' % rc, print('[%s]' % rc, end=' ')
else: else:
print '[%s->%s]' % (addr2rc[addr], rc), print('[%s->%s]' % (addr2rc[addr], rc), end=' ')
print guts, addr2guts[addr] print(guts, addr2guts[addr])
f.close() f.close()
print "%d objects before, %d after" % (before, after) print("%d objects before, %d after" % (before, after))
if __name__ == '__main__': if __name__ == '__main__':
combine(sys.argv[1]) combine(sys.argv[1])
...@@ -6,15 +6,15 @@ import sys, os ...@@ -6,15 +6,15 @@ import sys, os
def main(): def main():
for filename in sys.argv[1:]: for filename in sys.argv[1:]:
if os.path.isdir(filename): if os.path.isdir(filename):
print filename, "Directory!" print(filename, "Directory!")
continue continue
data = open(filename, "rb").read() data = open(filename, "rb").read()
if '\0' in data: if '\0' in data:
print filename, "Binary!" print(filename, "Binary!")
continue continue
newdata = data.replace("\r\n", "\n") newdata = data.replace("\r\n", "\n")
if newdata != data: if newdata != data:
print filename print(filename)
f = open(filename, "wb") f = open(filename, "wb")
f.write(newdata) f.write(newdata)
f.close() f.close()
......
...@@ -21,8 +21,8 @@ def main(): ...@@ -21,8 +21,8 @@ def main():
try: try:
opts, args = getopt.getopt(sys.argv[1:], "n:") opts, args = getopt.getopt(sys.argv[1:], "n:")
except getopt.error as msg: except getopt.error as msg:
print msg print(msg)
print __doc__, print(__doc__, end=' ')
return 1 return 1
global cutofftime global cutofftime
newerfile = None newerfile = None
...@@ -57,7 +57,7 @@ def process(dir): ...@@ -57,7 +57,7 @@ def process(dir):
if cutofftime and getmtime(fullname) <= cutofftime: if cutofftime and getmtime(fullname) <= cutofftime:
pass pass
else: else:
print fullname print(fullname)
for sub in subdirs: for sub in subdirs:
process(sub) process(sub)
......
...@@ -51,7 +51,7 @@ def show(total, d, prefix): ...@@ -51,7 +51,7 @@ def show(total, d, prefix):
if tsub is None: if tsub is None:
psub = prefix psub = prefix
else: else:
print prefix + repr(tsub).rjust(width) + ' ' + key print(prefix + repr(tsub).rjust(width) + ' ' + key)
psub = prefix + ' '*(width-1) + '|' + ' '*(len(key)+1) psub = prefix + ' '*(width-1) + '|' + ' '*(len(key)+1)
if d.has_key(key): if d.has_key(key):
show(tsub, d[key][1], psub) show(tsub, d[key][1], psub)
......
...@@ -32,7 +32,7 @@ def main(): ...@@ -32,7 +32,7 @@ def main():
listnames = 0 listnames = 0
for o, a in opts: for o, a in opts:
if o == "-h": if o == "-h":
print __doc__ print(__doc__)
return return
if o == "-l": if o == "-l":
listnames = 1 listnames = 1
...@@ -60,11 +60,11 @@ def process(filename, listnames): ...@@ -60,11 +60,11 @@ def process(filename, listnames):
for type, token, (row, col), end, line in g: for type, token, (row, col), end, line in g:
if token in ("/", "/="): if token in ("/", "/="):
if listnames: if listnames:
print filename print(filename)
break break
if row != lastrow: if row != lastrow:
lastrow = row lastrow = row
print "%s:%d:%s" % (filename, row, line), print("%s:%d:%s" % (filename, row, line), end=' ')
fp.close() fp.close()
def processdir(dir, listnames): def processdir(dir, listnames):
......
...@@ -16,8 +16,8 @@ def main(): ...@@ -16,8 +16,8 @@ def main():
raise getopt.GetoptError('not enough arguments', None) raise getopt.GetoptError('not enough arguments', None)
except getopt.GetoptError as msg: except getopt.GetoptError as msg:
sys.stdout = sys.stderr sys.stdout = sys.stderr
print msg print(msg)
print 'usage: findlinksto pattern directory ...' print('usage: findlinksto pattern directory ...')
sys.exit(2) sys.exit(2)
pat, dirs = args[0], args[1:] pat, dirs = args[0], args[1:]
prog = re.compile(pat) prog = re.compile(pat)
...@@ -29,13 +29,13 @@ def visit(prog, dirname, names): ...@@ -29,13 +29,13 @@ def visit(prog, dirname, names):
names[:] = [] names[:] = []
return return
if os.path.ismount(dirname): if os.path.ismount(dirname):
print 'descend into', dirname print('descend into', dirname)
for name in names: for name in names:
name = os.path.join(dirname, name) name = os.path.join(dirname, name)
try: try:
linkto = os.readlink(name) linkto = os.readlink(name)
if prog.search(linkto) is not None: if prog.search(linkto) is not None:
print name, '->', linkto print(name, '->', linkto)
except os.error: except os.error:
pass pass
......
...@@ -28,8 +28,8 @@ except: ...@@ -28,8 +28,8 @@ except:
pysource = pysource() pysource = pysource()
print >>sys.stderr, ("The pysource module is not available; " print("The pysource module is not available; "
"no sophisticated Python source file search will be done.") "no sophisticated Python source file search will be done.", file=sys.stderr)
decl_re = re.compile(r"coding[=:]\s*([-\w.]+)") decl_re = re.compile(r"coding[=:]\s*([-\w.]+)")
...@@ -79,8 +79,8 @@ usage = """Usage: %s [-cd] paths... ...@@ -79,8 +79,8 @@ usage = """Usage: %s [-cd] paths...
try: try:
opts, args = getopt.getopt(sys.argv[1:], 'cd') opts, args = getopt.getopt(sys.argv[1:], 'cd')
except getopt.error as msg: except getopt.error as msg:
print >>sys.stderr, msg print(msg, file=sys.stderr)
print >>sys.stderr, usage print(usage, file=sys.stderr)
sys.exit(1) sys.exit(1)
is_python = pysource.looks_like_python is_python = pysource.looks_like_python
...@@ -93,12 +93,12 @@ for o, a in opts: ...@@ -93,12 +93,12 @@ for o, a in opts:
debug = True debug = True
if not args: if not args:
print >>sys.stderr, usage print(usage, file=sys.stderr)
sys.exit(1) sys.exit(1)
for fullpath in pysource.walk_python_files(args, is_python): for fullpath in pysource.walk_python_files(args, is_python):
if debug: if debug:
print "Testing for coding: %s" % fullpath print("Testing for coding: %s" % fullpath)
result = needs_declaration(fullpath) result = needs_declaration(fullpath)
if result: if result:
print fullpath print(fullpath)
...@@ -244,7 +244,7 @@ def fixline(line): ...@@ -244,7 +244,7 @@ def fixline(line):
subst = Dict[found] subst = Dict[found]
if Program is InsideCommentProgram: if Program is InsideCommentProgram:
if not Docomments: if not Docomments:
print 'Found in comment:', found print('Found in comment:', found)
i = i + n i = i + n
continue continue
if NotInComment.has_key(found): if NotInComment.has_key(found):
......
...@@ -145,7 +145,7 @@ def main(): ...@@ -145,7 +145,7 @@ def main():
return 2 return 2
for o, a in opts: for o, a in opts:
if o == "-h": if o == "-h":
print __doc__ print(__doc__)
return return
if o == "-m": if o == "-m":
global multi_ok global multi_ok
...@@ -160,7 +160,7 @@ def main(): ...@@ -160,7 +160,7 @@ def main():
return 1 return 1
files = warnings.keys() files = warnings.keys()
if not files: if not files:
print "No classic division warnings read from", args[0] print("No classic division warnings read from", args[0])
return return
files.sort() files.sort()
exit = None exit = None
...@@ -203,14 +203,14 @@ def readwarnings(warningsfile): ...@@ -203,14 +203,14 @@ def readwarnings(warningsfile):
return warnings return warnings
def process(filename, list): def process(filename, list):
print "-"*70 print("-"*70)
assert list # if this fails, readwarnings() is broken assert list # if this fails, readwarnings() is broken
try: try:
fp = open(filename) fp = open(filename)
except IOError as msg: except IOError as msg:
sys.stderr.write("can't open: %s\n" % msg) sys.stderr.write("can't open: %s\n" % msg)
return 1 return 1
print "Index:", filename print("Index:", filename)
f = FileContext(fp) f = FileContext(fp)
list.sort() list.sort()
index = 0 # list[:index] has been processed, list[index:] is still to do index = 0 # list[:index] has been processed, list[index:] is still to do
...@@ -248,10 +248,10 @@ def process(filename, list): ...@@ -248,10 +248,10 @@ def process(filename, list):
lastrow = row lastrow = row
assert rows assert rows
if len(rows) == 1: if len(rows) == 1:
print "*** More than one / operator in line", rows[0] print("*** More than one / operator in line", rows[0])
else: else:
print "*** More than one / operator per statement", print("*** More than one / operator per statement", end=' ')
print "in lines %d-%d" % (rows[0], rows[-1]) print("in lines %d-%d" % (rows[0], rows[-1]))
intlong = [] intlong = []
floatcomplex = [] floatcomplex = []
bad = [] bad = []
...@@ -269,24 +269,24 @@ def process(filename, list): ...@@ -269,24 +269,24 @@ def process(filename, list):
lastrow = row lastrow = row
line = chop(line) line = chop(line)
if line[col:col+1] != "/": if line[col:col+1] != "/":
print "*** Can't find the / operator in line %d:" % row print("*** Can't find the / operator in line %d:" % row)
print "*", line print("*", line)
continue continue
if bad: if bad:
print "*** Bad warning for line %d:" % row, bad print("*** Bad warning for line %d:" % row, bad)
print "*", line print("*", line)
elif intlong and not floatcomplex: elif intlong and not floatcomplex:
print "%dc%d" % (row, row) print("%dc%d" % (row, row))
print "<", line print("<", line)
print "---" print("---")
print ">", line[:col] + "/" + line[col:] print(">", line[:col] + "/" + line[col:])
elif floatcomplex and not intlong: elif floatcomplex and not intlong:
print "True division / operator at line %d:" % row print("True division / operator at line %d:" % row)
print "=", line print("=", line)
elif intlong and floatcomplex: elif intlong and floatcomplex:
print "*** Ambiguous / operator (%s, %s) at line %d:" % ( print("*** Ambiguous / operator (%s, %s) at line %d:" % (
"|".join(intlong), "|".join(floatcomplex), row) "|".join(intlong), "|".join(floatcomplex), row))
print "?", line print("?", line)
fp.close() fp.close()
def reportphantomwarnings(warnings, f): def reportphantomwarnings(warnings, f):
...@@ -301,15 +301,15 @@ def reportphantomwarnings(warnings, f): ...@@ -301,15 +301,15 @@ def reportphantomwarnings(warnings, f):
for block in blocks: for block in blocks:
row = block[0] row = block[0]
whats = "/".join(block[1:]) whats = "/".join(block[1:])
print "*** Phantom %s warnings for line %d:" % (whats, row) print("*** Phantom %s warnings for line %d:" % (whats, row))
f.report(row, mark="*") f.report(row, mark="*")
def report(slashes, message): def report(slashes, message):
lastrow = None lastrow = None
for (row, col), line in slashes: for (row, col), line in slashes:
if row != lastrow: if row != lastrow:
print "*** %s on line %d:" % (message, row) print("*** %s on line %d:" % (message, row))
print "*", chop(line) print("*", chop(line))
lastrow = row lastrow = row
class FileContext: class FileContext:
...@@ -354,7 +354,7 @@ class FileContext: ...@@ -354,7 +354,7 @@ class FileContext:
line = self[first] line = self[first]
except KeyError: except KeyError:
line = "<missing line>" line = "<missing line>"
print mark, chop(line) print(mark, chop(line))
def scanline(g): def scanline(g):
slashes = [] slashes = []
......
...@@ -32,18 +32,18 @@ def process(filename): ...@@ -32,18 +32,18 @@ def process(filename):
magic = magic + c.upper() magic = magic + c.upper()
else: magic = magic + '_' else: magic = magic + '_'
sys.stdout = f sys.stdout = f
print '#ifndef', magic print('#ifndef', magic)
print '#define', magic print('#define', magic)
print '#ifdef __cplusplus' print('#ifdef __cplusplus')
print 'extern "C" {' print('extern "C" {')
print '#endif' print('#endif')
print print()
f.write(data) f.write(data)
print print()
print '#ifdef __cplusplus' print('#ifdef __cplusplus')
print '}' print('}')
print '#endif' print('#endif')
print '#endif /*', '!'+magic, '*/' print('#endif /*', '!'+magic, '*/')
if __name__ == '__main__': if __name__ == '__main__':
main() main()
...@@ -50,9 +50,9 @@ VERBOSE = 0 ...@@ -50,9 +50,9 @@ VERBOSE = 0
def usage(code, msg=''): def usage(code, msg=''):
print __doc__ % globals() print(__doc__ % globals())
if msg: if msg:
print msg print(msg)
sys.exit(code) sys.exit(code)
...@@ -92,10 +92,10 @@ def process(file): ...@@ -92,10 +92,10 @@ def process(file):
i = data.find(OLD_NOTICE) i = data.find(OLD_NOTICE)
if i < 0: if i < 0:
if VERBOSE: if VERBOSE:
print 'no change:', file print('no change:', file)
return return
elif DRYRUN or VERBOSE: elif DRYRUN or VERBOSE:
print ' change:', file print(' change:', file)
if DRYRUN: if DRYRUN:
# Don't actually change the file # Don't actually change the file
return return
......
...@@ -12,18 +12,18 @@ def main(): ...@@ -12,18 +12,18 @@ def main():
try: try:
f = open(filename, 'r') f = open(filename, 'r')
except IOError as msg: except IOError as msg:
print filename, ': can\'t open :', msg print(filename, ': can\'t open :', msg)
continue continue
line = f.readline() line = f.readline()
if not re.match('^#! */usr/local/bin/python', line): if not re.match('^#! */usr/local/bin/python', line):
print filename, ': not a /usr/local/bin/python script' print(filename, ': not a /usr/local/bin/python script')
f.close() f.close()
continue continue
rest = f.read() rest = f.read()
f.close() f.close()
line = re.sub('/usr/local/bin/python', line = re.sub('/usr/local/bin/python',
'/usr/bin/env python', line) '/usr/bin/env python', line)
print filename, ':', repr(line) print(filename, ':', repr(line))
f = open(filename, "w") f = open(filename, "w")
f.write(line) f.write(line)
f.write(rest) f.write(rest)
......
This diff is collapsed.
...@@ -5,7 +5,7 @@ import sys, webbrowser ...@@ -5,7 +5,7 @@ import sys, webbrowser
def main(): def main():
args = sys.argv[1:] args = sys.argv[1:]
if not args: if not args:
print "Usage: %s querystring" % sys.argv[0] print("Usage: %s querystring" % sys.argv[0])
return return
list = [] list = []
for arg in args: for arg in args:
......
...@@ -7,15 +7,15 @@ import sys, re, os ...@@ -7,15 +7,15 @@ import sys, re, os
def main(): def main():
for filename in sys.argv[1:]: for filename in sys.argv[1:]:
if os.path.isdir(filename): if os.path.isdir(filename):
print filename, "Directory!" print(filename, "Directory!")
continue continue
data = open(filename, "rb").read() data = open(filename, "rb").read()
if '\0' in data: if '\0' in data:
print filename, "Binary!" print(filename, "Binary!")
continue continue
newdata = re.sub("\r?\n", "\r\n", data) newdata = re.sub("\r?\n", "\r\n", data)
if newdata != data: if newdata != data:
print filename print(filename)
f = open(filename, "wb") f = open(filename, "wb")
f.write(newdata) f.write(newdata)
f.close() f.close()
......
...@@ -18,7 +18,7 @@ debug = 0 ...@@ -18,7 +18,7 @@ debug = 0
def main(): def main():
if not 3 <= len(sys.argv) <= 4: if not 3 <= len(sys.argv) <= 4:
print 'usage:', sys.argv[0], 'oldtree newtree [linkto]' print('usage:', sys.argv[0], 'oldtree newtree [linkto]')
return 2 return 2
oldtree, newtree = sys.argv[1], sys.argv[2] oldtree, newtree = sys.argv[1], sys.argv[2]
if len(sys.argv) > 3: if len(sys.argv) > 3:
...@@ -28,46 +28,46 @@ def main(): ...@@ -28,46 +28,46 @@ def main():
link = LINK link = LINK
link_may_fail = 0 link_may_fail = 0
if not os.path.isdir(oldtree): if not os.path.isdir(oldtree):
print oldtree + ': not a directory' print(oldtree + ': not a directory')
return 1 return 1
try: try:
os.mkdir(newtree, 0o777) os.mkdir(newtree, 0o777)
except os.error as msg: except os.error as msg:
print newtree + ': cannot mkdir:', msg print(newtree + ': cannot mkdir:', msg)
return 1 return 1
linkname = os.path.join(newtree, link) linkname = os.path.join(newtree, link)
try: try:
os.symlink(os.path.join(os.pardir, oldtree), linkname) os.symlink(os.path.join(os.pardir, oldtree), linkname)
except os.error as msg: except os.error as msg:
if not link_may_fail: if not link_may_fail:
print linkname + ': cannot symlink:', msg print(linkname + ': cannot symlink:', msg)
return 1 return 1
else: else:
print linkname + ': warning: cannot symlink:', msg print(linkname + ': warning: cannot symlink:', msg)
linknames(oldtree, newtree, link) linknames(oldtree, newtree, link)
return 0 return 0
def linknames(old, new, link): def linknames(old, new, link):
if debug: print 'linknames', (old, new, link) if debug: print('linknames', (old, new, link))
try: try:
names = os.listdir(old) names = os.listdir(old)
except os.error as msg: except os.error as msg:
print old + ': warning: cannot listdir:', msg print(old + ': warning: cannot listdir:', msg)
return return
for name in names: for name in names:
if name not in (os.curdir, os.pardir): if name not in (os.curdir, os.pardir):
oldname = os.path.join(old, name) oldname = os.path.join(old, name)
linkname = os.path.join(link, name) linkname = os.path.join(link, name)
newname = os.path.join(new, name) newname = os.path.join(new, name)
if debug > 1: print oldname, newname, linkname if debug > 1: print(oldname, newname, linkname)
if os.path.isdir(oldname) and \ if os.path.isdir(oldname) and \
not os.path.islink(oldname): not os.path.islink(oldname):
try: try:
os.mkdir(newname, 0o777) os.mkdir(newname, 0o777)
ok = 1 ok = 1
except: except:
print newname + \ print(newname + \
': warning: cannot mkdir:', msg ': warning: cannot mkdir:', msg)
ok = 0 ok = 0
if ok: if ok:
linkname = os.path.join(os.pardir, linkname = os.path.join(os.pardir,
......
...@@ -12,16 +12,16 @@ def lll(dirname): ...@@ -12,16 +12,16 @@ def lll(dirname):
if name not in (os.curdir, os.pardir): if name not in (os.curdir, os.pardir):
full = os.path.join(dirname, name) full = os.path.join(dirname, name)
if os.path.islink(full): if os.path.islink(full):
print name, '->', os.readlink(full) print(name, '->', os.readlink(full))
def main(): def main():
args = sys.argv[1:] args = sys.argv[1:]
if not args: args = [os.curdir] if not args: args = [os.curdir]
first = 1 first = 1
for arg in args: for arg in args:
if len(args) > 1: if len(args) > 1:
if not first: print if not first: print()
first = 0 first = 0
print arg + ':' print(arg + ':')
lll(arg) lll(arg)
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -53,7 +53,7 @@ def main(): ...@@ -53,7 +53,7 @@ def main():
elif o == '-b': elif o == '-b':
branch = a branch = a
elif o == '-h': elif o == '-h':
print __doc__ print(__doc__)
sys.exit(0) sys.exit(0)
database = [] database = []
while 1: while 1:
...@@ -169,9 +169,9 @@ def format_output(database): ...@@ -169,9 +169,9 @@ def format_output(database):
for (date, working_file, rev, author, text) in database: for (date, working_file, rev, author, text) in database:
if text != prevtext: if text != prevtext:
if prev: if prev:
print sep2, print(sep2, end=' ')
for (p_date, p_working_file, p_rev, p_author) in prev: for (p_date, p_working_file, p_rev, p_author) in prev:
print p_date, p_author, p_working_file, p_rev print(p_date, p_author, p_working_file, p_rev)
sys.stdout.writelines(prevtext) sys.stdout.writelines(prevtext)
prev = [] prev = []
prev.append((date, working_file, rev, author)) prev.append((date, working_file, rev, author))
......
...@@ -171,11 +171,11 @@ def parsedir(dir, modify): ...@@ -171,11 +171,11 @@ def parsedir(dir, modify):
fp = open(fn) fp = open(fn)
m = ErrorMessage(fp) m = ErrorMessage(fp)
sender = m.getaddr('From') sender = m.getaddr('From')
print '%s\t%-40s\t'%(fn, sender[1]), print('%s\t%-40s\t'%(fn, sender[1]), end=' ')
if m.is_warning(): if m.is_warning():
fp.close() fp.close()
print 'warning only' print('warning only')
nwarn = nwarn + 1 nwarn = nwarn + 1
if modify: if modify:
os.rename(fn, ','+fn) os.rename(fn, ','+fn)
...@@ -185,11 +185,11 @@ def parsedir(dir, modify): ...@@ -185,11 +185,11 @@ def parsedir(dir, modify):
try: try:
errors = m.get_errors() errors = m.get_errors()
except Unparseable: except Unparseable:
print '** Not parseable' print('** Not parseable')
nbad = nbad + 1 nbad = nbad + 1
fp.close() fp.close()
continue continue
print len(errors), 'errors' print(len(errors), 'errors')
# Remember them # Remember them
for e in errors: for e in errors:
...@@ -211,16 +211,16 @@ def parsedir(dir, modify): ...@@ -211,16 +211,16 @@ def parsedir(dir, modify):
os.rename(fn, ','+fn) os.rename(fn, ','+fn)
## os.unlink(fn) ## os.unlink(fn)
print '--------------' print('--------------')
print nok, 'files parsed,',nwarn,'files warning-only,', print(nok, 'files parsed,',nwarn,'files warning-only,', end=' ')
print nbad,'files unparseable' print(nbad,'files unparseable')
print '--------------' print('--------------')
list = [] list = []
for e in errordict.keys(): for e in errordict.keys():
list.append((errordict[e], errorfirst[e], errorlast[e], e)) list.append((errordict[e], errorfirst[e], errorlast[e], e))
list.sort() list.sort()
for num, first, last, e in list: for num, first, last, e in list:
print '%d %s - %s\t%s' % (num, first, last, e) print('%d %s - %s\t%s' % (num, first, last, e))
def main(): def main():
modify = 0 modify = 0
......
...@@ -48,12 +48,12 @@ def main(): ...@@ -48,12 +48,12 @@ def main():
if progname == '-c': progname = 'mkreal' if progname == '-c': progname = 'mkreal'
args = sys.argv[1:] args = sys.argv[1:]
if not args: if not args:
print 'usage:', progname, 'path ...' print('usage:', progname, 'path ...')
sys.exit(2) sys.exit(2)
status = 0 status = 0
for name in args: for name in args:
if not os.path.islink(name): if not os.path.islink(name):
print progname+':', name+':', 'not a symlink' print(progname+':', name+':', 'not a symlink')
status = 1 status = 1
else: else:
if os.path.isdir(name): if os.path.isdir(name):
......
...@@ -74,7 +74,7 @@ def fcompare(f1name, f2name): ...@@ -74,7 +74,7 @@ def fcompare(f1name, f2name):
a = f1.readlines(); f1.close() a = f1.readlines(); f1.close()
b = f2.readlines(); f2.close() b = f2.readlines(); f2.close()
for line in difflib.ndiff(a, b): for line in difflib.ndiff(a, b):
print line, print(line, end=' ')
return 1 return 1
...@@ -109,8 +109,8 @@ def main(args): ...@@ -109,8 +109,8 @@ def main(args):
return fail("need 2 filename args") return fail("need 2 filename args")
f1name, f2name = args f1name, f2name = args
if noisy: if noisy:
print '-:', f1name print('-:', f1name)
print '+:', f2name print('+:', f2name)
return fcompare(f1name, f2name) return fcompare(f1name, f2name)
# read ndiff output from stdin, and print file1 (which=='1') or # read ndiff output from stdin, and print file1 (which=='1') or
......
...@@ -80,7 +80,7 @@ def readinput(fp): ...@@ -80,7 +80,7 @@ def readinput(fp):
store(file2undef, fn, name) store(file2undef, fn, name)
store(undef2file, name, fn) store(undef2file, name, fn)
elif not type in ignore: elif not type in ignore:
print fn + ':' + name + ': unknown type ' + type print(fn + ':' + name + ': unknown type ' + type)
# Print all names that were undefined in some module and where they are # Print all names that were undefined in some module and where they are
# defined. # defined.
...@@ -89,7 +89,7 @@ def printcallee(): ...@@ -89,7 +89,7 @@ def printcallee():
flist = file2undef.keys() flist = file2undef.keys()
flist.sort() flist.sort()
for filename in flist: for filename in flist:
print filename + ':' print(filename + ':')
elist = file2undef[filename] elist = file2undef[filename]
elist.sort() elist.sort()
for ext in elist: for ext in elist:
...@@ -98,9 +98,9 @@ def printcallee(): ...@@ -98,9 +98,9 @@ def printcallee():
else: else:
tabs = '\t\t' tabs = '\t\t'
if not def2file.has_key(ext): if not def2file.has_key(ext):
print '\t' + ext + tabs + ' *undefined' print('\t' + ext + tabs + ' *undefined')
else: else:
print '\t' + ext + tabs + flat(def2file[ext]) print('\t' + ext + tabs + flat(def2file[ext]))
# Print for each module the names of the other modules that use it. # Print for each module the names of the other modules that use it.
# #
...@@ -114,14 +114,14 @@ def printcaller(): ...@@ -114,14 +114,14 @@ def printcaller():
callers = callers + undef2file[label] callers = callers + undef2file[label]
if callers: if callers:
callers.sort() callers.sort()
print filename + ':' print(filename + ':')
lastfn = '' lastfn = ''
for fn in callers: for fn in callers:
if fn <> lastfn: if fn <> lastfn:
print '\t' + fn print('\t' + fn)
lastfn = fn lastfn = fn
else: else:
print filename + ': unused' print(filename + ': unused')
# Print undefined names and where they are used. # Print undefined names and where they are used.
# #
...@@ -134,11 +134,11 @@ def printundef(): ...@@ -134,11 +134,11 @@ def printundef():
elist = undefs.keys() elist = undefs.keys()
elist.sort() elist.sort()
for ext in elist: for ext in elist:
print ext + ':' print(ext + ':')
flist = undefs[ext] flist = undefs[ext]
flist.sort() flist.sort()
for filename in flist: for filename in flist:
print '\t' + filename print('\t' + filename)
# Print warning messages about names defined in more than one file. # Print warning messages about names defined in more than one file.
# #
...@@ -149,8 +149,8 @@ def warndups(): ...@@ -149,8 +149,8 @@ def warndups():
names.sort() names.sort()
for name in names: for name in names:
if len(def2file[name]) > 1: if len(def2file[name]) > 1:
print 'warning:', name, 'multiply defined:', print('warning:', name, 'multiply defined:', end=' ')
print flat(def2file[name]) print(flat(def2file[name]))
sys.stdout = savestdout sys.stdout = savestdout
# Main program # Main program
...@@ -160,14 +160,14 @@ def main(): ...@@ -160,14 +160,14 @@ def main():
optlist, args = getopt.getopt(sys.argv[1:], 'cdu') optlist, args = getopt.getopt(sys.argv[1:], 'cdu')
except getopt.error: except getopt.error:
sys.stdout = sys.stderr sys.stdout = sys.stderr
print 'Usage:', os.path.basename(sys.argv[0]), print('Usage:', os.path.basename(sys.argv[0]), end=' ')
print '[-cdu] [file] ...' print('[-cdu] [file] ...')
print '-c: print callers per objectfile' print('-c: print callers per objectfile')
print '-d: print callees per objectfile' print('-d: print callees per objectfile')
print '-u: print usage of undefined symbols' print('-u: print usage of undefined symbols')
print 'If none of -cdu is specified, all are assumed.' print('If none of -cdu is specified, all are assumed.')
print 'Use "nm -o" to generate the input (on IRIX: "nm -Bo"),' print('Use "nm -o" to generate the input (on IRIX: "nm -Bo"),')
print 'e.g.: nm -o /lib/libc.a | objgraph' print('e.g.: nm -o /lib/libc.a | objgraph')
return 1 return 1
optu = optc = optd = 0 optu = optc = optd = 0
for opt, void in optlist: for opt, void in optlist:
...@@ -192,15 +192,15 @@ def main(): ...@@ -192,15 +192,15 @@ def main():
more = (optu + optc + optd > 1) more = (optu + optc + optd > 1)
if optd: if optd:
if more: if more:
print '---------------All callees------------------' print('---------------All callees------------------')
printcallee() printcallee()
if optu: if optu:
if more: if more:
print '---------------Undefined callees------------' print('---------------Undefined callees------------')
printundef() printundef()
if optc: if optc:
if more: if more:
print '---------------All Callers------------------' print('---------------All Callers------------------')
printcaller() printcaller()
return 0 return 0
......
...@@ -30,25 +30,25 @@ import os ...@@ -30,25 +30,25 @@ import os
def main(): def main():
args = sys.argv[1:] args = sys.argv[1:]
if not args: if not args:
print 'usage: pdeps file.py file.py ...' print('usage: pdeps file.py file.py ...')
return 2 return 2
# #
table = {} table = {}
for arg in args: for arg in args:
process(arg, table) process(arg, table)
# #
print '--- Uses ---' print('--- Uses ---')
printresults(table) printresults(table)
# #
print '--- Used By ---' print('--- Used By ---')
inv = inverse(table) inv = inverse(table)
printresults(inv) printresults(inv)
# #
print '--- Closure of Uses ---' print('--- Closure of Uses ---')
reach = closure(table) reach = closure(table)
printresults(reach) printresults(reach)
# #
print '--- Closure of Used By ---' print('--- Closure of Used By ---')
invreach = inverse(reach) invreach = inverse(reach)
printresults(invreach) printresults(invreach)
# #
...@@ -151,12 +151,12 @@ def printresults(table): ...@@ -151,12 +151,12 @@ def printresults(table):
for mod in modules: for mod in modules:
list = table[mod] list = table[mod]
list.sort() list.sort()
print mod.ljust(maxlen), ':', print(mod.ljust(maxlen), ':', end=' ')
if mod in list: if mod in list:
print '(*)', print('(*)', end=' ')
for ref in list: for ref in list:
print ref, print(ref, end=' ')
print print()
# Call main and honor exit status # Call main and honor exit status
......
...@@ -27,7 +27,7 @@ binary_re = re.compile('[\x00-\x08\x0E-\x1F\x7F]') ...@@ -27,7 +27,7 @@ binary_re = re.compile('[\x00-\x08\x0E-\x1F\x7F]')
debug = False debug = False
def print_debug(msg): def print_debug(msg):
if debug: print msg if debug: print(msg)
def _open(fullpath): def _open(fullpath):
...@@ -124,7 +124,7 @@ def walk_python_files(paths, is_python=looks_like_python, exclude_dirs=None): ...@@ -124,7 +124,7 @@ def walk_python_files(paths, is_python=looks_like_python, exclude_dirs=None):
if __name__ == "__main__": if __name__ == "__main__":
# Two simple examples/tests # Two simple examples/tests
for fullpath in walk_python_files(['.']): for fullpath in walk_python_files(['.']):
print fullpath print(fullpath)
print "----------" print("----------")
for fullpath in walk_python_files(['.'], is_python=can_be_compiled): for fullpath in walk_python_files(['.'], is_python=can_be_compiled):
print fullpath print(fullpath)
...@@ -52,12 +52,12 @@ def main(): ...@@ -52,12 +52,12 @@ def main():
lines.reverse() lines.reverse()
for line in lines: for line in lines:
if prog.search(line): if prog.search(line):
print line print(line)
def usage(msg, code=2): def usage(msg, code=2):
sys.stdout = sys.stderr sys.stdout = sys.stderr
print msg print(msg)
print __doc__ print(__doc__)
sys.exit(code) sys.exit(code)
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -17,7 +17,7 @@ def main(): ...@@ -17,7 +17,7 @@ def main():
keys = suffixes.keys() keys = suffixes.keys()
keys.sort() keys.sort()
for suff in keys: for suff in keys:
print repr(suff), len(suffixes[suff]) print(repr(suff), len(suffixes[suff]))
def getsuffix(filename): def getsuffix(filename):
suff = '' suff = ''
......
...@@ -65,10 +65,10 @@ def matchclose(c_lineno, c_symbol, openers, pairmap): ...@@ -65,10 +65,10 @@ def matchclose(c_lineno, c_symbol, openers, pairmap):
try: try:
o_lineno, o_symbol = openers.pop() o_lineno, o_symbol = openers.pop()
except IndexError: except IndexError:
print "\nDelimiter mismatch. On line %d, encountered closing '%s' without corresponding open" % (c_lineno, c_symbol) print("\nDelimiter mismatch. On line %d, encountered closing '%s' without corresponding open" % (c_lineno, c_symbol))
return return
if o_symbol in pairmap.get(c_symbol, [c_symbol]): return if o_symbol in pairmap.get(c_symbol, [c_symbol]): return
print "\nOpener '%s' on line %d was not closed before encountering '%s' on line %d" % (o_symbol, o_lineno, c_symbol, c_lineno) print("\nOpener '%s' on line %d was not closed before encountering '%s' on line %d" % (o_symbol, o_lineno, c_symbol, c_lineno))
return return
def checkit(source, opts, morecmds=[]): def checkit(source, opts, morecmds=[]):
...@@ -120,7 +120,7 @@ def checkit(source, opts, morecmds=[]): ...@@ -120,7 +120,7 @@ def checkit(source, opts, morecmds=[]):
# Check balancing of open/close parenthesis, brackets, and begin/end blocks # Check balancing of open/close parenthesis, brackets, and begin/end blocks
for begend, name, punct in delimiters.findall(line): for begend, name, punct in delimiters.findall(line):
if '-v' in opts: if '-v' in opts:
print lineno, '|', begend, name, punct, print(lineno, '|', begend, name, punct, end=' ')
if begend == 'begin' and '-d' not in opts: if begend == 'begin' and '-d' not in opts:
openers.append((lineno, name)) openers.append((lineno, name))
elif punct in openpunct: elif punct in openpunct:
...@@ -130,7 +130,7 @@ def checkit(source, opts, morecmds=[]): ...@@ -130,7 +130,7 @@ def checkit(source, opts, morecmds=[]):
elif punct in pairmap: elif punct in pairmap:
matchclose(lineno, punct, openers, pairmap) matchclose(lineno, punct, openers, pairmap)
if '-v' in opts: if '-v' in opts:
print ' --> ', openers print(' --> ', openers)
# Balance opening and closing braces # Balance opening and closing braces
for open, close in braces.findall(line): for open, close in braces.findall(line):
...@@ -140,7 +140,7 @@ def checkit(source, opts, morecmds=[]): ...@@ -140,7 +140,7 @@ def checkit(source, opts, morecmds=[]):
try: try:
bracestack.pop() bracestack.pop()
except IndexError: except IndexError:
print r'Warning, unmatched } on line %s.' % (lineno,) print(r'Warning, unmatched } on line %s.' % (lineno,))
# Optionally, skip LaTeX specific checks # Optionally, skip LaTeX specific checks
if '-d' in opts: if '-d' in opts:
...@@ -151,11 +151,11 @@ def checkit(source, opts, morecmds=[]): ...@@ -151,11 +151,11 @@ def checkit(source, opts, morecmds=[]):
if '822' in line or '.html' in line: if '822' in line or '.html' in line:
continue # Ignore false positives for urls and for /rfc822 continue # Ignore false positives for urls and for /rfc822
if '\\' + cmd in validcmds: if '\\' + cmd in validcmds:
print 'Warning, forward slash used on line %d with cmd: /%s' % (lineno, cmd) print('Warning, forward slash used on line %d with cmd: /%s' % (lineno, cmd))
# Check for markup requiring {} for correct spacing # Check for markup requiring {} for correct spacing
for cmd in spacingmarkup.findall(line): for cmd in spacingmarkup.findall(line):
print r'Warning, \%s should be written as \%s{} on line %d' % (cmd, cmd, lineno) print(r'Warning, \%s should be written as \%s{} on line %d' % (cmd, cmd, lineno))
# Validate commands # Validate commands
nc = line.find(r'\newcommand') nc = line.find(r'\newcommand')
...@@ -165,7 +165,7 @@ def checkit(source, opts, morecmds=[]): ...@@ -165,7 +165,7 @@ def checkit(source, opts, morecmds=[]):
validcmds.add(line[start+1:end]) validcmds.add(line[start+1:end])
for cmd in texcmd.findall(line): for cmd in texcmd.findall(line):
if cmd not in validcmds: if cmd not in validcmds:
print r'Warning, unknown tex cmd on line %d: \%s' % (lineno, cmd) print(r'Warning, unknown tex cmd on line %d: \%s' % (lineno, cmd))
# Check table levels (make sure lineii only inside tableii) # Check table levels (make sure lineii only inside tableii)
m = tablestart.search(line) m = tablestart.search(line)
...@@ -174,23 +174,23 @@ def checkit(source, opts, morecmds=[]): ...@@ -174,23 +174,23 @@ def checkit(source, opts, morecmds=[]):
tablestartline = lineno tablestartline = lineno
m = tableline.search(line) m = tableline.search(line)
if m and m.group(1) != tablelevel: if m and m.group(1) != tablelevel:
print r'Warning, \line%s on line %d does not match \table%s on line %d' % (m.group(1), lineno, tablelevel, tablestartline) print(r'Warning, \line%s on line %d does not match \table%s on line %d' % (m.group(1), lineno, tablelevel, tablestartline))
if tableend.search(line): if tableend.search(line):
tablelevel = '' tablelevel = ''
# Style guide warnings # Style guide warnings
if 'e.g.' in line or 'i.e.' in line: if 'e.g.' in line or 'i.e.' in line:
print r'Style warning, avoid use of i.e or e.g. on line %d' % (lineno,) print(r'Style warning, avoid use of i.e or e.g. on line %d' % (lineno,))
for dw in doubledwords.findall(line): for dw in doubledwords.findall(line):
print r'Doubled word warning. "%s" on line %d' % (dw, lineno) print(r'Doubled word warning. "%s" on line %d' % (dw, lineno))
lastline = lineno lastline = lineno
for lineno, symbol in openers: for lineno, symbol in openers:
print "Unmatched open delimiter '%s' on line %d" % (symbol, lineno) print("Unmatched open delimiter '%s' on line %d" % (symbol, lineno))
for lineno in bracestack: for lineno in bracestack:
print "Unmatched { on line %d" % (lineno,) print("Unmatched { on line %d" % (lineno,))
print 'Done checking %d lines.' % (lastline,) print('Done checking %d lines.' % (lastline,))
return 0 return 0
def main(args=None): def main(args=None):
...@@ -199,11 +199,11 @@ def main(args=None): ...@@ -199,11 +199,11 @@ def main(args=None):
optitems, arglist = getopt.getopt(args, "k:mdhs:v") optitems, arglist = getopt.getopt(args, "k:mdhs:v")
opts = dict(optitems) opts = dict(optitems)
if '-h' in opts or args==[]: if '-h' in opts or args==[]:
print __doc__ print(__doc__)
return 0 return 0
if len(arglist) < 1: if len(arglist) < 1:
print 'Please specify a file to be checked' print('Please specify a file to be checked')
return 1 return 1
for i, filespec in enumerate(arglist): for i, filespec in enumerate(arglist):
...@@ -214,12 +214,12 @@ def main(args=None): ...@@ -214,12 +214,12 @@ def main(args=None):
err = [] err = []
for filename in arglist: for filename in arglist:
print '=' * 30 print('=' * 30)
print "Checking", filename print("Checking", filename)
try: try:
f = open(filename) f = open(filename)
except IOError: except IOError:
print 'Cannot open file %s.' % arglist[0] print('Cannot open file %s.' % arglist[0])
return 2 return 2
try: try:
......
This diff is collapsed.
...@@ -54,35 +54,35 @@ def main(): ...@@ -54,35 +54,35 @@ def main():
try: try:
[slave, master] = args [slave, master] = args
except ValueError: except ValueError:
print "usage: python", sys.argv[0] or "treesync.py", print("usage: python", sys.argv[0] or "treesync.py", end=' ')
print "[-n] [-y] [-m y|n|a] [-s y|n|a] [-d y|n|a] [-f n|y|a]", print("[-n] [-y] [-m y|n|a] [-s y|n|a] [-d y|n|a] [-f n|y|a]", end=' ')
print "slavedir masterdir" print("slavedir masterdir")
return return
process(slave, master) process(slave, master)
def process(slave, master): def process(slave, master):
cvsdir = os.path.join(master, "CVS") cvsdir = os.path.join(master, "CVS")
if not os.path.isdir(cvsdir): if not os.path.isdir(cvsdir):
print "skipping master subdirectory", master print("skipping master subdirectory", master)
print "-- not under CVS" print("-- not under CVS")
return return
print "-"*40 print("-"*40)
print "slave ", slave print("slave ", slave)
print "master", master print("master", master)
if not os.path.isdir(slave): if not os.path.isdir(slave):
if not okay("create slave directory %s?" % slave, if not okay("create slave directory %s?" % slave,
answer=create_directories): answer=create_directories):
print "skipping master subdirectory", master print("skipping master subdirectory", master)
print "-- no corresponding slave", slave print("-- no corresponding slave", slave)
return return
print "creating slave directory", slave print("creating slave directory", slave)
try: try:
os.mkdir(slave) os.mkdir(slave)
except os.error as msg: except os.error as msg:
print "can't make slave directory", slave, ":", msg print("can't make slave directory", slave, ":", msg)
return return
else: else:
print "made slave directory", slave print("made slave directory", slave)
cvsdir = None cvsdir = None
subdirs = [] subdirs = []
names = os.listdir(master) names = os.listdir(master)
...@@ -117,13 +117,13 @@ def compare(slave, master): ...@@ -117,13 +117,13 @@ def compare(slave, master):
mf = None mf = None
if not sf: if not sf:
if not mf: if not mf:
print "Neither master nor slave exists", master print("Neither master nor slave exists", master)
return return
print "Creating missing slave", slave print("Creating missing slave", slave)
copy(master, slave, answer=create_files) copy(master, slave, answer=create_files)
return return
if not mf: if not mf:
print "Not updating missing master", master print("Not updating missing master", master)
return return
if sf and mf: if sf and mf:
if identical(sf, mf): if identical(sf, mf):
...@@ -134,22 +134,22 @@ def compare(slave, master): ...@@ -134,22 +134,22 @@ def compare(slave, master):
# Master is newer -- copy master to slave # Master is newer -- copy master to slave
sf.close() sf.close()
mf.close() mf.close()
print "Master ", master print("Master ", master)
print "is newer than slave", slave print("is newer than slave", slave)
copy(master, slave, answer=write_slave) copy(master, slave, answer=write_slave)
return return
# Slave is newer -- copy slave to master # Slave is newer -- copy slave to master
print "Slave is", sft-mft, "seconds newer than master" print("Slave is", sft-mft, "seconds newer than master")
# But first check what to do about CRLF # But first check what to do about CRLF
mf.seek(0) mf.seek(0)
fun = funnychars(mf) fun = funnychars(mf)
mf.close() mf.close()
sf.close() sf.close()
if fun: if fun:
print "***UPDATING MASTER (BINARY COPY)***" print("***UPDATING MASTER (BINARY COPY)***")
copy(slave, master, "rb", answer=write_master) copy(slave, master, "rb", answer=write_master)
else: else:
print "***UPDATING MASTER***" print("***UPDATING MASTER***")
copy(slave, master, "r", answer=write_master) copy(slave, master, "r", answer=write_master)
BUFSIZE = 16*1024 BUFSIZE = 16*1024
...@@ -174,8 +174,8 @@ def funnychars(f): ...@@ -174,8 +174,8 @@ def funnychars(f):
return 0 return 0
def copy(src, dst, rmode="rb", wmode="wb", answer='ask'): def copy(src, dst, rmode="rb", wmode="wb", answer='ask'):
print "copying", src print("copying", src)
print " to", dst print(" to", dst)
if not okay("okay to copy? ", answer): if not okay("okay to copy? ", answer):
return return
f = open(src, rmode) f = open(src, rmode)
...@@ -203,7 +203,7 @@ def okay(prompt, answer='ask'): ...@@ -203,7 +203,7 @@ def okay(prompt, answer='ask'):
return 1 return 1
if answer[:1] == 'n': if answer[:1] == 'n':
return 0 return 0
print "Yes or No please -- try again:" print("Yes or No please -- try again:")
return okay(prompt) return okay(prompt)
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -13,8 +13,8 @@ def main(): ...@@ -13,8 +13,8 @@ def main():
if not args: if not args:
raise getopt.error, "At least one file argument required" raise getopt.error, "At least one file argument required"
except getopt.error as msg: except getopt.error as msg:
print msg print(msg)
print "usage:", sys.argv[0], "[-t tabwidth] file ..." print("usage:", sys.argv[0], "[-t tabwidth] file ...")
return return
for optname, optvalue in opts: for optname, optvalue in opts:
if optname == '-t': if optname == '-t':
...@@ -29,7 +29,7 @@ def process(filename, tabsize): ...@@ -29,7 +29,7 @@ def process(filename, tabsize):
text = f.read() text = f.read()
f.close() f.close()
except IOError as msg: except IOError as msg:
print "%r: I/O error: %s" % (filename, msg) print("%r: I/O error: %s" % (filename, msg))
return return
newtext = text.expandtabs(tabsize) newtext = text.expandtabs(tabsize)
if newtext == text: if newtext == text:
...@@ -46,7 +46,7 @@ def process(filename, tabsize): ...@@ -46,7 +46,7 @@ def process(filename, tabsize):
f = open(filename, "w") f = open(filename, "w")
f.write(newtext) f.write(newtext)
f.close() f.close()
print filename print(filename)
if __name__ == '__main__': if __name__ == '__main__':
main() main()
...@@ -37,7 +37,7 @@ def main(): ...@@ -37,7 +37,7 @@ def main():
mode = S_IMODE(st[ST_MODE]) mode = S_IMODE(st[ST_MODE])
if mode & 0o111: if mode & 0o111:
if not ident: if not ident:
print filename print(filename)
ident = st[:3] ident = st[:3]
else: else:
if st[:3] == ident: if st[:3] == ident:
......
...@@ -18,14 +18,14 @@ def getargs(): ...@@ -18,14 +18,14 @@ def getargs():
args = sys.argv[1:] args = sys.argv[1:]
if args: if args:
return args return args
print 'No arguments, checking almost *, in "ls -t" order' print('No arguments, checking almost *, in "ls -t" order')
list = [] list = []
for file in os.listdir(os.curdir): for file in os.listdir(os.curdir):
if not skipfile(file): if not skipfile(file):
list.append((getmtime(file), file)) list.append((getmtime(file), file))
list.sort() list.sort()
if not list: if not list:
print 'Nothing to do -- exit 1' print('Nothing to do -- exit 1')
sys.exit(1) sys.exit(1)
list.sort() list.sort()
list.reverse() list.reverse()
...@@ -89,7 +89,7 @@ def badsuffix(file): ...@@ -89,7 +89,7 @@ def badsuffix(file):
def go(args): def go(args):
for file in args: for file in args:
print file + ':' print(file + ':')
if differing(file): if differing(file):
showdiffs(file) showdiffs(file)
if askyesno('Check in ' + file + ' ? '): if askyesno('Check in ' + file + ' ? '):
...@@ -119,4 +119,4 @@ if __name__ == '__main__': ...@@ -119,4 +119,4 @@ if __name__ == '__main__':
setup() setup()
go(getargs()) go(getargs())
except KeyboardInterrupt: except KeyboardInterrupt:
print '[Intr]' print('[Intr]')
...@@ -11,7 +11,7 @@ import sys ...@@ -11,7 +11,7 @@ import sys
def compare_codecs(encoding1, encoding2): def compare_codecs(encoding1, encoding2):
print 'Comparing encoding/decoding of %r and %r' % (encoding1, encoding2) print('Comparing encoding/decoding of %r and %r' % (encoding1, encoding2))
mismatch = 0 mismatch = 0
# Check encoding # Check encoding
for i in range(sys.maxunicode): for i in range(sys.maxunicode):
...@@ -25,8 +25,8 @@ def compare_codecs(encoding1, encoding2): ...@@ -25,8 +25,8 @@ def compare_codecs(encoding1, encoding2):
except UnicodeError as reason: except UnicodeError as reason:
c2 = '<undefined>' c2 = '<undefined>'
if c1 != c2: if c1 != c2:
print ' * encoding mismatch for 0x%04X: %-14r != %r' % \ print(' * encoding mismatch for 0x%04X: %-14r != %r' % \
(i, c1, c2) (i, c1, c2))
mismatch += 1 mismatch += 1
# Check decoding # Check decoding
for i in range(256): for i in range(256):
...@@ -40,14 +40,14 @@ def compare_codecs(encoding1, encoding2): ...@@ -40,14 +40,14 @@ def compare_codecs(encoding1, encoding2):
except UnicodeError: except UnicodeError:
u2 = u'<undefined>' u2 = u'<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))
mismatch += 1 mismatch += 1
if mismatch: if mismatch:
print print()
print 'Found %i mismatches' % mismatch print('Found %i mismatches' % mismatch)
else: else:
print '-> Codecs are identical.' print('-> Codecs are identical.')
if __name__ == '__main__': if __name__ == '__main__':
compare_codecs(sys.argv[1], sys.argv[2]) compare_codecs(sys.argv[1], sys.argv[2])
...@@ -131,7 +131,7 @@ def hexrepr(t, precision=4): ...@@ -131,7 +131,7 @@ def hexrepr(t, precision=4):
return '(' + ', '.join(['0x%0*X' % (precision, item) return '(' + ', '.join(['0x%0*X' % (precision, item)
for item in t]) + ')' for item in t]) + ')'
except TypeError as why: except TypeError as why:
print '* failed to convert %r: %s' % (t, why) print('* failed to convert %r: %s' % (t, why))
raise raise
def python_mapdef_code(varname, map, comments=1, precisions=(2, 4)): def python_mapdef_code(varname, map, comments=1, precisions=(2, 4)):
...@@ -383,18 +383,18 @@ def convertdir(dir, dirprefix='', nameprefix='', comments=1): ...@@ -383,18 +383,18 @@ def convertdir(dir, dirprefix='', nameprefix='', comments=1):
name = nameprefix + name name = nameprefix + name
codefile = name + '.py' codefile = name + '.py'
marshalfile = name + '.mapping' marshalfile = name + '.mapping'
print 'converting %s to %s and %s' % (mapname, print('converting %s to %s and %s' % (mapname,
dirprefix + codefile, dirprefix + codefile,
dirprefix + marshalfile) dirprefix + marshalfile))
try: try:
map = readmap(os.path.join(dir,mapname)) map = readmap(os.path.join(dir,mapname))
if not map: if not map:
print '* map is empty; skipping' print('* map is empty; skipping')
else: else:
pymap(mappathname, map, dirprefix + codefile,name,comments) pymap(mappathname, map, dirprefix + codefile,name,comments)
marshalmap(mappathname, map, dirprefix + marshalfile) marshalmap(mappathname, map, dirprefix + marshalfile)
except ValueError as why: except ValueError as why:
print '* conversion failed: %s' % why print('* conversion failed: %s' % why)
raise raise
def rewritepythondir(dir, dirprefix='', comments=1): def rewritepythondir(dir, dirprefix='', comments=1):
...@@ -405,17 +405,17 @@ def rewritepythondir(dir, dirprefix='', comments=1): ...@@ -405,17 +405,17 @@ def rewritepythondir(dir, dirprefix='', comments=1):
continue continue
name = mapname[:-len('.mapping')] name = mapname[:-len('.mapping')]
codefile = name + '.py' codefile = name + '.py'
print 'converting %s to %s' % (mapname, print('converting %s to %s' % (mapname,
dirprefix + codefile) dirprefix + codefile))
try: try:
map = marshal.load(open(os.path.join(dir,mapname), map = marshal.load(open(os.path.join(dir,mapname),
'rb')) 'rb'))
if not map: if not map:
print '* map is empty; skipping' print('* map is empty; skipping')
else: else:
pymap(mapname, map, dirprefix + codefile,name,comments) pymap(mapname, map, dirprefix + codefile,name,comments)
except ValueError as why: except ValueError as why:
print '* conversion failed: %s' % why print('* conversion failed: %s' % why)
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -26,8 +26,8 @@ def listcodecs(dir): ...@@ -26,8 +26,8 @@ def listcodecs(dir):
# Probably an error from importing the codec; still it's # Probably an error from importing the codec; still it's
# a valid code name # a valid code name
if _debug: if _debug:
print '* problem importing codec %r: %s' % \ print('* problem importing codec %r: %s' % \
(name, reason) (name, reason))
names.append(name) names.append(name)
return names return names
...@@ -35,7 +35,7 @@ def listcodecs(dir): ...@@ -35,7 +35,7 @@ def listcodecs(dir):
if __name__ == '__main__': if __name__ == '__main__':
names = listcodecs(encodings.__path__[0]) names = listcodecs(encodings.__path__[0])
names.sort() names.sort()
print 'all_codecs = [' print('all_codecs = [')
for name in names: for name in names:
print ' %r,' % name print(' %r,' % name)
print ']' print(']')
This diff is collapsed.
...@@ -106,7 +106,7 @@ for l in data: ...@@ -106,7 +106,7 @@ for l in data:
########### Generate compact Python versions of the tables ############# ########### Generate compact Python versions of the tables #############
print """# This file is generated by mkstringprep.py. DO NOT EDIT. print("""# This file is generated by mkstringprep.py. DO NOT EDIT.
\"\"\"Library that exposes various tables found in the StringPrep RFC 3454. \"\"\"Library that exposes various tables found in the StringPrep RFC 3454.
There are two kinds of tables: sets, for which a member test is provided, There are two kinds of tables: sets, for which a member test is provided,
...@@ -114,9 +114,9 @@ and mappings, for which a mapping function is provided. ...@@ -114,9 +114,9 @@ and mappings, for which a mapping function is provided.
\"\"\" \"\"\"
import unicodedata import unicodedata
""" """)
print "assert unicodedata.unidata_version == %s" % repr(unicodedata.unidata_version) print("assert unicodedata.unidata_version == %s" % repr(unicodedata.unidata_version))
# A.1 is the table of unassigned characters # A.1 is the table of unassigned characters
# XXX Plane 15 PUA is listed as unassigned in Python. # XXX Plane 15 PUA is listed as unassigned in Python.
...@@ -134,13 +134,13 @@ Cn -= set(range(0xFFFF, 0x110000, 0x10000)) ...@@ -134,13 +134,13 @@ Cn -= set(range(0xFFFF, 0x110000, 0x10000))
# assert table == Cn # assert table == Cn
print """ print("""
def in_table_a1(code): def in_table_a1(code):
if unicodedata.category(code) != 'Cn': return False if unicodedata.category(code) != 'Cn': return False
c = ord(code) c = ord(code)
if 0xFDD0 <= c < 0xFDF0: return False if 0xFDD0 <= c < 0xFDF0: return False
return (c & 0xFFFF) not in (0xFFFE, 0xFFFF) return (c & 0xFFFF) not in (0xFFFE, 0xFFFF)
""" """)
# B.1 cannot easily be derived # B.1 cannot easily be derived
name, table = tables[0] name, table = tables[0]
...@@ -148,11 +148,11 @@ del tables[0] ...@@ -148,11 +148,11 @@ del tables[0]
assert name == "B.1" assert name == "B.1"
table = table.keys() table = table.keys()
table.sort() table.sort()
print """ print("""
b1_set = """ + compact_set(table) + """ b1_set = """ + compact_set(table) + """
def in_table_b1(code): def in_table_b1(code):
return ord(code) in b1_set return ord(code) in b1_set
""" """)
# B.2 and B.3 is case folding. # B.2 and B.3 is case folding.
# It takes CaseFolding.txt into account, which is # It takes CaseFolding.txt into account, which is
...@@ -180,20 +180,20 @@ for k,v in table_b2.items(): ...@@ -180,20 +180,20 @@ for k,v in table_b2.items():
b3 = b3_exceptions.items() b3 = b3_exceptions.items()
b3.sort() b3.sort()
print """ print("""
b3_exceptions = {""" b3_exceptions = {""")
for i,(k,v) in enumerate(b3): for i,(k,v) in enumerate(b3):
print "0x%x:%s," % (k, repr(v)), print("0x%x:%s," % (k, repr(v)), end=' ')
if i % 4 == 3: if i % 4 == 3:
print print()
print "}" print("}")
print """ print("""
def map_table_b3(code): def map_table_b3(code):
r = b3_exceptions.get(ord(code)) r = b3_exceptions.get(ord(code))
if r is not None: return r if r is not None: return r
return code.lower() return code.lower()
""" """)
def map_table_b3(code): def map_table_b3(code):
r = b3_exceptions.get(ord(code)) r = b3_exceptions.get(ord(code))
...@@ -222,7 +222,7 @@ for k,v in table_b2.items(): ...@@ -222,7 +222,7 @@ for k,v in table_b2.items():
# B.3 should not add any additional special cases # B.3 should not add any additional special cases
assert specials == {} assert specials == {}
print """ print("""
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)
...@@ -232,7 +232,7 @@ def map_table_b2(a): ...@@ -232,7 +232,7 @@ def map_table_b2(a):
return c return c
else: else:
return al return al
""" """)
# C.1.1 is a table with a single character # C.1.1 is a table with a single character
name, table = tables[0] name, table = tables[0]
...@@ -240,10 +240,10 @@ del tables[0] ...@@ -240,10 +240,10 @@ del tables[0]
assert name == "C.1.1" assert name == "C.1.1"
assert table == {0x20:0x20} assert table == {0x20:0x20}
print """ print("""
def in_table_c11(code): def in_table_c11(code):
return code == u" " return code == u" "
""" """)
# C.1.2 is the rest of all space characters # C.1.2 is the rest of all space characters
name, table = tables[0] name, table = tables[0]
...@@ -254,13 +254,13 @@ assert name == "C.1.2" ...@@ -254,13 +254,13 @@ assert name == "C.1.2"
# Zs = set(gen_category(["Zs"])) - set([0x20]) # Zs = set(gen_category(["Zs"])) - set([0x20])
# assert Zs == table # assert Zs == table
print """ print("""
def in_table_c12(code): def in_table_c12(code):
return unicodedata.category(code) == "Zs" and code != u" " return unicodedata.category(code) == "Zs" and code != u" "
def in_table_c11_c12(code): def in_table_c11_c12(code):
return unicodedata.category(code) == "Zs" return unicodedata.category(code) == "Zs"
""" """)
# C.2.1 ASCII control characters # C.2.1 ASCII control characters
name, table_c21 = tables[0] name, table_c21 = tables[0]
...@@ -272,10 +272,10 @@ Cc_ascii = Cc & set(range(128)) ...@@ -272,10 +272,10 @@ Cc_ascii = Cc & set(range(128))
table_c21 = set(table_c21.keys()) table_c21 = set(table_c21.keys())
assert Cc_ascii == table_c21 assert Cc_ascii == table_c21
print """ print("""
def in_table_c21(code): def in_table_c21(code):
return ord(code) < 128 and unicodedata.category(code) == "Cc" return ord(code) < 128 and unicodedata.category(code) == "Cc"
""" """)
# C.2.2 Non-ASCII control characters. It also includes # C.2.2 Non-ASCII control characters. It also includes
# a number of characters in category Cf. # a number of characters in category Cf.
...@@ -290,7 +290,7 @@ assert len(Cc_nonascii - table_c22) == 0 ...@@ -290,7 +290,7 @@ assert len(Cc_nonascii - table_c22) == 0
specials = list(table_c22 - Cc_nonascii) specials = list(table_c22 - Cc_nonascii)
specials.sort() specials.sort()
print """c22_specials = """ + compact_set(specials) + """ print("""c22_specials = """ + compact_set(specials) + """
def in_table_c22(code): def in_table_c22(code):
c = ord(code) c = ord(code)
if c < 128: return False if c < 128: return False
...@@ -300,7 +300,7 @@ def in_table_c22(code): ...@@ -300,7 +300,7 @@ def in_table_c22(code):
def in_table_c21_c22(code): def in_table_c21_c22(code):
return unicodedata.category(code) == "Cc" or \\ return unicodedata.category(code) == "Cc" or \\
ord(code) in c22_specials ord(code) in c22_specials
""" """)
# C.3 Private use # C.3 Private use
name, table = tables[0] name, table = tables[0]
...@@ -310,10 +310,10 @@ assert name == "C.3" ...@@ -310,10 +310,10 @@ assert name == "C.3"
Co = set(gen_category(["Co"])) Co = set(gen_category(["Co"]))
assert set(table.keys()) == Co assert set(table.keys()) == Co
print """ print("""
def in_table_c3(code): def in_table_c3(code):
return unicodedata.category(code) == "Co" return unicodedata.category(code) == "Co"
""" """)
# C.4 Non-character code points, xFFFE, xFFFF # C.4 Non-character code points, xFFFE, xFFFF
# plus process internal codes # plus process internal codes
...@@ -327,13 +327,13 @@ nonchar = set(range(0xFDD0,0xFDF0) + ...@@ -327,13 +327,13 @@ nonchar = set(range(0xFDD0,0xFDF0) +
table = set(table.keys()) table = set(table.keys())
assert table == nonchar assert table == nonchar
print """ print("""
def in_table_c4(code): def in_table_c4(code):
c = ord(code) c = ord(code)
if c < 0xFDD0: return False if c < 0xFDD0: return False
if c < 0xFDF0: return True if c < 0xFDF0: return True
return (ord(code) & 0xFFFF) in (0xFFFE, 0xFFFF) return (ord(code) & 0xFFFF) in (0xFFFE, 0xFFFF)
""" """)
# C.5 Surrogate codes # C.5 Surrogate codes
name, table = tables[0] name, table = tables[0]
...@@ -343,10 +343,10 @@ assert name == "C.5" ...@@ -343,10 +343,10 @@ assert name == "C.5"
Cs = set(gen_category(["Cs"])) Cs = set(gen_category(["Cs"]))
assert set(table.keys()) == Cs assert set(table.keys()) == Cs
print """ print("""
def in_table_c5(code): def in_table_c5(code):
return unicodedata.category(code) == "Cs" return unicodedata.category(code) == "Cs"
""" """)
# C.6 Inappropriate for plain text # C.6 Inappropriate for plain text
name, table = tables[0] name, table = tables[0]
...@@ -356,11 +356,11 @@ assert name == "C.6" ...@@ -356,11 +356,11 @@ assert name == "C.6"
table = table.keys() table = table.keys()
table.sort() table.sort()
print """ print("""
c6_set = """ + compact_set(table) + """ c6_set = """ + compact_set(table) + """
def in_table_c6(code): def in_table_c6(code):
return ord(code) in c6_set return ord(code) in c6_set
""" """)
# C.7 Inappropriate for canonical representation # C.7 Inappropriate for canonical representation
name, table = tables[0] name, table = tables[0]
...@@ -370,11 +370,11 @@ assert name == "C.7" ...@@ -370,11 +370,11 @@ assert name == "C.7"
table = table.keys() table = table.keys()
table.sort() table.sort()
print """ print("""
c7_set = """ + compact_set(table) + """ c7_set = """ + compact_set(table) + """
def in_table_c7(code): def in_table_c7(code):
return ord(code) in c7_set return ord(code) in c7_set
""" """)
# C.8 Change display properties or are deprecated # C.8 Change display properties or are deprecated
name, table = tables[0] name, table = tables[0]
...@@ -384,11 +384,11 @@ assert name == "C.8" ...@@ -384,11 +384,11 @@ assert name == "C.8"
table = table.keys() table = table.keys()
table.sort() table.sort()
print """ print("""
c8_set = """ + compact_set(table) + """ c8_set = """ + compact_set(table) + """
def in_table_c8(code): def in_table_c8(code):
return ord(code) in c8_set return ord(code) in c8_set
""" """)
# C.9 Tagging characters # C.9 Tagging characters
name, table = tables[0] name, table = tables[0]
...@@ -398,11 +398,11 @@ assert name == "C.9" ...@@ -398,11 +398,11 @@ assert name == "C.9"
table = table.keys() table = table.keys()
table.sort() table.sort()
print """ print("""
c9_set = """ + compact_set(table) + """ c9_set = """ + compact_set(table) + """
def in_table_c9(code): def in_table_c9(code):
return ord(code) in c9_set return ord(code) in c9_set
""" """)
# D.1 Characters with bidirectional property "R" or "AL" # D.1 Characters with bidirectional property "R" or "AL"
name, table = tables[0] name, table = tables[0]
...@@ -412,10 +412,10 @@ assert name == "D.1" ...@@ -412,10 +412,10 @@ assert name == "D.1"
RandAL = set(gen_bidirectional(["R","AL"])) RandAL = set(gen_bidirectional(["R","AL"]))
assert set(table.keys()) == RandAL assert set(table.keys()) == RandAL
print """ print("""
def in_table_d1(code): def in_table_d1(code):
return unicodedata.bidirectional(code) in ("R","AL") return unicodedata.bidirectional(code) in ("R","AL")
""" """)
# D.2 Characters with bidirectional property "L" # D.2 Characters with bidirectional property "L"
name, table = tables[0] name, table = tables[0]
...@@ -425,7 +425,7 @@ assert name == "D.2" ...@@ -425,7 +425,7 @@ assert name == "D.2"
L = set(gen_bidirectional(["L"])) L = set(gen_bidirectional(["L"]))
assert set(table.keys()) == L assert set(table.keys()) == L
print """ print("""
def in_table_d2(code): def in_table_d2(code):
return unicodedata.bidirectional(code) == "L" return unicodedata.bidirectional(code) == "L"
""" """)
...@@ -28,7 +28,7 @@ def check1dir(dummy, dir, files): ...@@ -28,7 +28,7 @@ def check1dir(dummy, dir, files):
try: try:
execfile(fullname) execfile(fullname)
except: except:
print '** Exception in', fullname print('** Exception in', fullname)
def walk1tree(tree): def walk1tree(tree):
os.path.walk(tree, check1dir, None) os.path.walk(tree, check1dir, None)
...@@ -38,7 +38,7 @@ def main(): ...@@ -38,7 +38,7 @@ def main():
try: try:
options, arguments = getopt.getopt(sys.argv[1:], 'v:') options, arguments = getopt.getopt(sys.argv[1:], 'v:')
except getopt.error: except getopt.error:
print USAGE print(USAGE)
sys.exit(1) sys.exit(1)
for o, a in options: for o, a in options:
if o == '-v': if o == '-v':
......
...@@ -18,12 +18,12 @@ def versioncheck(package, url, version, verbose=0): ...@@ -18,12 +18,12 @@ def versioncheck(package, url, version, verbose=0):
if verbose > VERBOSE_NORMAL: if verbose > VERBOSE_NORMAL:
return ok return ok
if ok < 0: if ok < 0:
print '%s: No correctly formatted current version file found'%(package) print('%s: No correctly formatted current version file found'%(package))
elif ok == 1: elif ok == 1:
print '%s: up-to-date (version %s)'%(package, version) print('%s: up-to-date (version %s)'%(package, version))
else: else:
print '%s: version %s installed, version %s found:' % \ print('%s: version %s installed, version %s found:' % \
(package, version, newversion) (package, version, newversion))
if verbose > VERBOSE_SILENT: if verbose > VERBOSE_SILENT:
while 1: while 1:
line = fp.readline() line = fp.readline()
...@@ -33,7 +33,7 @@ def versioncheck(package, url, version, verbose=0): ...@@ -33,7 +33,7 @@ def versioncheck(package, url, version, verbose=0):
def checkonly(package, url, version, verbose=0): def checkonly(package, url, version, verbose=0):
if verbose >= VERBOSE_EACHFILE: if verbose >= VERBOSE_EACHFILE:
print '%s:'%package print('%s:'%package)
if isinstance(url, str): if isinstance(url, str):
ok, newversion, fp = _check1version(package, url, version, verbose) ok, newversion, fp = _check1version(package, url, version, verbose)
else: else:
...@@ -45,51 +45,51 @@ def checkonly(package, url, version, verbose=0): ...@@ -45,51 +45,51 @@ def checkonly(package, url, version, verbose=0):
def _check1version(package, url, version, verbose=0): def _check1version(package, url, version, verbose=0):
if verbose >= VERBOSE_EACHFILE: if verbose >= VERBOSE_EACHFILE:
print ' Checking %s'%url print(' Checking %s'%url)
try: try:
fp = urllib.urlopen(url) fp = urllib.urlopen(url)
except IOError as arg: except IOError as arg:
if verbose >= VERBOSE_EACHFILE: if verbose >= VERBOSE_EACHFILE:
print ' Cannot open:', arg print(' Cannot open:', arg)
return -1, None, None return -1, None, None
msg = rfc822.Message(fp, seekable=0) msg = rfc822.Message(fp, seekable=0)
newversion = msg.getheader('current-version') newversion = msg.getheader('current-version')
if not newversion: if not newversion:
if verbose >= VERBOSE_EACHFILE: if verbose >= VERBOSE_EACHFILE:
print ' No "Current-Version:" header in URL or URL not found' print(' No "Current-Version:" header in URL or URL not found')
return -1, None, None return -1, None, None
version = version.lower().strip() version = version.lower().strip()
newversion = newversion.lower().strip() newversion = newversion.lower().strip()
if version == newversion: if version == newversion:
if verbose >= VERBOSE_EACHFILE: if verbose >= VERBOSE_EACHFILE:
print ' Version identical (%s)'%newversion print(' Version identical (%s)'%newversion)
return 1, version, fp return 1, version, fp
else: else:
if verbose >= VERBOSE_EACHFILE: if verbose >= VERBOSE_EACHFILE:
print ' Versions different (installed: %s, new: %s)'% \ print(' Versions different (installed: %s, new: %s)'% \
(version, newversion) (version, newversion))
return 0, newversion, fp return 0, newversion, fp
def _test(): def _test():
print '--- TEST VERBOSE=1' print('--- TEST VERBOSE=1')
print '--- Testing existing and identical version file' print('--- Testing existing and identical version file')
versioncheck('VersionTestPackage', _TESTDIR+'Version10.txt', '1.0', verbose=1) versioncheck('VersionTestPackage', _TESTDIR+'Version10.txt', '1.0', verbose=1)
print '--- Testing existing package with new version' print('--- Testing existing package with new version')
versioncheck('VersionTestPackage', _TESTDIR+'Version11.txt', '1.0', verbose=1) versioncheck('VersionTestPackage', _TESTDIR+'Version11.txt', '1.0', verbose=1)
print '--- Testing package with non-existing version file' print('--- Testing package with non-existing version file')
versioncheck('VersionTestPackage', _TESTDIR+'nonexistent.txt', '1.0', verbose=1) versioncheck('VersionTestPackage', _TESTDIR+'nonexistent.txt', '1.0', verbose=1)
print '--- Test package with 2 locations, first non-existing second ok' print('--- Test package with 2 locations, first non-existing second ok')
versfiles = [_TESTDIR+'nonexistent.txt', _TESTDIR+'Version10.txt'] versfiles = [_TESTDIR+'nonexistent.txt', _TESTDIR+'Version10.txt']
versioncheck('VersionTestPackage', versfiles, '1.0', verbose=1) versioncheck('VersionTestPackage', versfiles, '1.0', verbose=1)
print '--- TEST VERBOSE=2' print('--- TEST VERBOSE=2')
print '--- Testing existing and identical version file' print('--- Testing existing and identical version file')
versioncheck('VersionTestPackage', _TESTDIR+'Version10.txt', '1.0', verbose=2) versioncheck('VersionTestPackage', _TESTDIR+'Version10.txt', '1.0', verbose=2)
print '--- Testing existing package with new version' print('--- Testing existing package with new version')
versioncheck('VersionTestPackage', _TESTDIR+'Version11.txt', '1.0', verbose=2) versioncheck('VersionTestPackage', _TESTDIR+'Version11.txt', '1.0', verbose=2)
print '--- Testing package with non-existing version file' print('--- Testing package with non-existing version file')
versioncheck('VersionTestPackage', _TESTDIR+'nonexistent.txt', '1.0', verbose=2) versioncheck('VersionTestPackage', _TESTDIR+'nonexistent.txt', '1.0', verbose=2)
print '--- Test package with 2 locations, first non-existing second ok' print('--- Test package with 2 locations, first non-existing second ok')
versfiles = [_TESTDIR+'nonexistent.txt', _TESTDIR+'Version10.txt'] versfiles = [_TESTDIR+'nonexistent.txt', _TESTDIR+'Version10.txt']
versioncheck('VersionTestPackage', versfiles, '1.0', verbose=2) versioncheck('VersionTestPackage', versfiles, '1.0', verbose=2)
......
...@@ -76,8 +76,8 @@ def main(): ...@@ -76,8 +76,8 @@ def main():
opts, args = getopt.getopt(sys.argv[1:], 't:m:qva') opts, args = getopt.getopt(sys.argv[1:], 't:m:qva')
except getopt.error as msg: except getopt.error as msg:
sys.stdout = sys.stderr sys.stdout = sys.stderr
print msg print(msg)
print __doc__%vars(webchecker) print(__doc__%vars(webchecker))
sys.exit(2) sys.exit(2)
webchecker.verbose = webchecker.VERBOSE webchecker.verbose = webchecker.VERBOSE
webchecker.nonames = webchecker.NONAMES webchecker.nonames = webchecker.NONAMES
......
...@@ -155,8 +155,8 @@ def main(): ...@@ -155,8 +155,8 @@ def main():
opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vxa') opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vxa')
except getopt.error as msg: except getopt.error as msg:
sys.stdout = sys.stderr sys.stdout = sys.stderr
print msg print(msg)
print __doc__%globals() print(__doc__%globals())
sys.exit(2) sys.exit(2)
# The extra_roots variable collects extra roots. # The extra_roots variable collects extra roots.
...@@ -186,7 +186,7 @@ def main(): ...@@ -186,7 +186,7 @@ def main():
checkext = not checkext checkext = not checkext
if verbose > 0: if verbose > 0:
print AGENTNAME, "version", __version__ print(AGENTNAME, "version", __version__)
if restart: if restart:
c = load_pickle(dumpfile=dumpfile, verbose=verbose) c = load_pickle(dumpfile=dumpfile, verbose=verbose)
...@@ -222,32 +222,32 @@ def main(): ...@@ -222,32 +222,32 @@ def main():
c.run() c.run()
except KeyboardInterrupt: except KeyboardInterrupt:
if verbose > 0: if verbose > 0:
print "[run interrupted]" print("[run interrupted]")
try: try:
c.report() c.report()
except KeyboardInterrupt: except KeyboardInterrupt:
if verbose > 0: if verbose > 0:
print "[report interrupted]" print("[report interrupted]")
finally: finally:
if c.save_pickle(dumpfile): if c.save_pickle(dumpfile):
if dumpfile == DUMPFILE: if dumpfile == DUMPFILE:
print "Use ``%s -R'' to restart." % sys.argv[0] print("Use ``%s -R'' to restart." % sys.argv[0])
else: else:
print "Use ``%s -R -d %s'' to restart." % (sys.argv[0], print("Use ``%s -R -d %s'' to restart." % (sys.argv[0],
dumpfile) dumpfile))
def load_pickle(dumpfile=DUMPFILE, verbose=VERBOSE): def load_pickle(dumpfile=DUMPFILE, verbose=VERBOSE):
if verbose > 0: if verbose > 0:
print "Loading checkpoint from %s ..." % dumpfile print("Loading checkpoint from %s ..." % dumpfile)
f = open(dumpfile, "rb") f = open(dumpfile, "rb")
c = pickle.load(f) c = pickle.load(f)
f.close() f.close()
if verbose > 0: if verbose > 0:
print "Done." print("Done.")
print "Root:", "\n ".join(c.roots) print("Root:", "\n ".join(c.roots))
return c return c
...@@ -297,7 +297,7 @@ class Checker: ...@@ -297,7 +297,7 @@ class Checker:
def message(self, format, *args): def message(self, format, *args):
if args: if args:
format = format%args format = format%args
print format print(format)
def __getstate__(self): def __getstate__(self):
return (self.roots, self.todo, self.done, self.bad, self.round) return (self.roots, self.todo, self.done, self.bad, self.round)
...@@ -689,7 +689,7 @@ class Page: ...@@ -689,7 +689,7 @@ class Page:
if self.verbose >= level: if self.verbose >= level:
if args: if args:
msg = msg%args msg = msg%args
print msg print(msg)
# Method to retrieve names. # Method to retrieve names.
def getnames(self): def getnames(self):
......
...@@ -22,8 +22,8 @@ def main(): ...@@ -22,8 +22,8 @@ def main():
try: try:
opts, args = getopt.getopt(sys.argv[1:], "qv") opts, args = getopt.getopt(sys.argv[1:], "qv")
except getopt.error as msg: except getopt.error as msg:
print msg print(msg)
print "usage:", sys.argv[0], "[-qv] ... [rooturl] ..." print("usage:", sys.argv[0], "[-qv] ... [rooturl] ...")
return 2 return 2
for o, a in opts: for o, a in opts:
if o == "-q": if o == "-q":
...@@ -36,9 +36,9 @@ def main(): ...@@ -36,9 +36,9 @@ def main():
('User-agent', 'websucker/%s' % __version__), ('User-agent', 'websucker/%s' % __version__),
] ]
for arg in args: for arg in args:
print "Adding root", arg print("Adding root", arg)
c.addroot(arg) c.addroot(arg)
print "Run..." print("Run...")
c.run() c.run()
class Sucker(webchecker.Checker): class Sucker(webchecker.Checker):
...@@ -116,7 +116,7 @@ def makedirs(dir): ...@@ -116,7 +116,7 @@ def makedirs(dir):
return return
head, tail = os.path.split(dir) head, tail = os.path.split(dir)
if not tail: if not tail:
print "Huh? Don't know how to make dir", dir print("Huh? Don't know how to make dir", dir)
return return
makedirs(head) makedirs(head)
os.mkdir(dir, 0o777) os.mkdir(dir, 0o777)
......
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