Convert print statements to function calls in Tools/.

This commit is contained in:
Collin Winter 2007-08-03 17:06:41 +00:00
parent e5d0e8431f
commit 6afaeb757a
66 changed files with 777 additions and 779 deletions

View File

@ -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():
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):

View File

@ -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:
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):
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():
(int, 'status', ErrorMode), (int, 'status', ErrorMode),
) )
eggs.setprefix("spam") eggs.setprefix("spam")
print "/* START */" print("/* START */")
eggs.generate() eggs.generate()

View File

@ -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():
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__":

View File

@ -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"
""" """
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"
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"
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"
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):

View File

@ -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)

View File

@ -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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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)

View File

@ -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):
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):
# 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):
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):
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):
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)

View File

@ -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:
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)

View File

@ -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)

View File

@ -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):
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('}')

View File

@ -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):
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):
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):
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():
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:

View File

@ -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:
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:
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:
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:
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():
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():
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():
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():
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()

View File

@ -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():
'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

View File

@ -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):
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):
# 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):
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):
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):
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):
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()

View File

@ -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:
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):
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:
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:
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,

View File

@ -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:
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:
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:
# 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:
(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:
(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))

View File

@ -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):
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:])))

View File

@ -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):
# 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():
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

View File

@ -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:
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:

View File

@ -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():

View File

@ -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)

View File

@ -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):
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:
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

View File

@ -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():
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:

View File

@ -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):
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):
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:

View File

@ -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):
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])

View File

@ -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()

View File

@ -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):
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)

View File

@ -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)

View File

@ -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):
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):

View File

@ -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):
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

View File

@ -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...
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:
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)

View File

@ -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):

View File

@ -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():
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):
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):
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):
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):
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:
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 = []

View File

@ -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()

View File

@ -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):
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

View File

@ -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)

View File

@ -29,8 +29,8 @@ from fnmatch import fnmatch
# Print usage message and exit # Print usage message and exit
def usage(*args): def usage(*args):
sys.stdout = sys.stderr sys.stdout = sys.stderr
for msg in args: print msg for msg in args: print(msg)
print __doc__ print(__doc__)
sys.exit(2) sys.exit(2)
verbose = 1 # 0 for -q, 2 for -v verbose = 1 # 0 for -q, 2 for -v
@ -82,22 +82,22 @@ def main():
if args[3:]: usage('too many arguments') if args[3:]: usage('too many arguments')
# #
f = ftplib.FTP() f = ftplib.FTP()
if verbose: print "Connecting to '%s%s'..." % (host, if verbose: print("Connecting to '%s%s'..." % (host,
(port and ":%d"%port or "")) (port and ":%d"%port or "")))
f.connect(host,port) f.connect(host,port)
if not nologin: if not nologin:
if verbose: if verbose:
print 'Logging in as %r...' % (login or 'anonymous') print('Logging in as %r...' % (login or 'anonymous'))
f.login(login, passwd, account) f.login(login, passwd, account)
if verbose: print 'OK.' if verbose: print('OK.')
pwd = f.pwd() pwd = f.pwd()
if verbose > 1: print 'PWD =', repr(pwd) if verbose > 1: print('PWD =', repr(pwd))
if remotedir: if remotedir:
if verbose > 1: print 'cwd(%s)' % repr(remotedir) if verbose > 1: print('cwd(%s)' % repr(remotedir))
f.cwd(remotedir) f.cwd(remotedir)
if verbose > 1: print 'OK.' if verbose > 1: print('OK.')
pwd = f.pwd() pwd = f.pwd()
if verbose > 1: print 'PWD =', repr(pwd) if verbose > 1: print('PWD =', repr(pwd))
# #
mirrorsubdir(f, localdir) mirrorsubdir(f, localdir)
@ -105,11 +105,11 @@ def main():
def mirrorsubdir(f, localdir): def mirrorsubdir(f, localdir):
pwd = f.pwd() pwd = f.pwd()
if localdir and not os.path.isdir(localdir): if localdir and not os.path.isdir(localdir):
if verbose: print 'Creating local directory', repr(localdir) if verbose: print('Creating local directory', repr(localdir))
try: try:
makedir(localdir) makedir(localdir)
except os.error as msg: except os.error as msg:
print "Failed to establish local directory", repr(localdir) print("Failed to establish local directory", repr(localdir))
return return
infofilename = os.path.join(localdir, '.mirrorinfo') infofilename = os.path.join(localdir, '.mirrorinfo')
try: try:
@ -119,15 +119,15 @@ def mirrorsubdir(f, localdir):
try: try:
info = eval(text) info = eval(text)
except (SyntaxError, NameError): except (SyntaxError, NameError):
print 'Bad mirror info in', repr(infofilename) print('Bad mirror info in', repr(infofilename))
info = {} info = {}
subdirs = [] subdirs = []
listing = [] listing = []
if verbose: print 'Listing remote directory %r...' % (pwd,) if verbose: print('Listing remote directory %r...' % (pwd,))
f.retrlines('LIST', listing.append) f.retrlines('LIST', listing.append)
filesfound = [] filesfound = []
for line in listing: for line in listing:
if verbose > 1: print '-->', repr(line) if verbose > 1: print('-->', repr(line))
if mac: if mac:
# Mac listing has just filenames; # Mac listing has just filenames;
# trailing / means subdirectory # trailing / means subdirectory
@ -141,14 +141,14 @@ def mirrorsubdir(f, localdir):
# Parse, assuming a UNIX listing # Parse, assuming a UNIX listing
words = line.split(None, 8) words = line.split(None, 8)
if len(words) < 6: if len(words) < 6:
if verbose > 1: print 'Skipping short line' if verbose > 1: print('Skipping short line')
continue continue
filename = words[-1].lstrip() filename = words[-1].lstrip()
i = filename.find(" -> ") i = filename.find(" -> ")
if i >= 0: if i >= 0:
# words[0] had better start with 'l'... # words[0] had better start with 'l'...
if verbose > 1: if verbose > 1:
print 'Found symbolic link %r' % (filename,) print('Found symbolic link %r' % (filename,))
linkto = filename[i+4:] linkto = filename[i+4:]
filename = filename[:i] filename = filename[:i]
infostuff = words[-5:-1] infostuff = words[-5:-1]
@ -157,21 +157,21 @@ def mirrorsubdir(f, localdir):
for pat in skippats: for pat in skippats:
if fnmatch(filename, pat): if fnmatch(filename, pat):
if verbose > 1: if verbose > 1:
print 'Skip pattern', repr(pat), print('Skip pattern', repr(pat), end=' ')
print 'matches', repr(filename) print('matches', repr(filename))
skip = 1 skip = 1
break break
if skip: if skip:
continue continue
if mode[0] == 'd': if mode[0] == 'd':
if verbose > 1: if verbose > 1:
print 'Remembering subdirectory', repr(filename) print('Remembering subdirectory', repr(filename))
subdirs.append(filename) subdirs.append(filename)
continue continue
filesfound.append(filename) filesfound.append(filename)
if info.has_key(filename) and info[filename] == infostuff: if info.has_key(filename) and info[filename] == infostuff:
if verbose > 1: if verbose > 1:
print 'Already have this version of',repr(filename) print('Already have this version of',repr(filename))
continue continue
fullname = os.path.join(localdir, filename) fullname = os.path.join(localdir, filename)
tempname = os.path.join(localdir, '@'+filename) tempname = os.path.join(localdir, '@'+filename)
@ -187,20 +187,20 @@ def mirrorsubdir(f, localdir):
pass pass
if mode[0] == 'l': if mode[0] == 'l':
if verbose: if verbose:
print "Creating symlink %r -> %r" % (filename, linkto) print("Creating symlink %r -> %r" % (filename, linkto))
try: try:
os.symlink(linkto, tempname) os.symlink(linkto, tempname)
except IOError as msg: except IOError as msg:
print "Can't create %r: %s" % (tempname, msg) print("Can't create %r: %s" % (tempname, msg))
continue continue
else: else:
try: try:
fp = open(tempname, 'wb') fp = open(tempname, 'wb')
except IOError as msg: except IOError as msg:
print "Can't create %r: %s" % (tempname, msg) print("Can't create %r: %s" % (tempname, msg))
continue continue
if verbose: if verbose:
print 'Retrieving %r from %r as %r...' % (filename, pwd, fullname) print('Retrieving %r from %r as %r...' % (filename, pwd, fullname))
if verbose: if verbose:
fp1 = LoggingFile(fp, 1024, sys.stdout) fp1 = LoggingFile(fp, 1024, sys.stdout)
else: else:
@ -210,7 +210,7 @@ def mirrorsubdir(f, localdir):
f.retrbinary('RETR ' + filename, f.retrbinary('RETR ' + filename,
fp1.write, 8*1024) fp1.write, 8*1024)
except ftplib.error_perm as msg: except ftplib.error_perm as msg:
print msg print(msg)
t1 = time.time() t1 = time.time()
bytes = fp.tell() bytes = fp.tell()
fp.close() fp.close()
@ -223,29 +223,29 @@ def mirrorsubdir(f, localdir):
try: try:
os.rename(tempname, fullname) os.rename(tempname, fullname)
except os.error as msg: except os.error as msg:
print "Can't rename %r to %r: %s" % (tempname, fullname, msg) print("Can't rename %r to %r: %s" % (tempname, fullname, msg))
continue continue
info[filename] = infostuff info[filename] = infostuff
writedict(info, infofilename) writedict(info, infofilename)
if verbose and mode[0] != 'l': if verbose and mode[0] != 'l':
dt = t1 - t0 dt = t1 - t0
kbytes = bytes / 1024.0 kbytes = bytes / 1024.0
print int(round(kbytes)), print(int(round(kbytes)), end=' ')
print 'Kbytes in', print('Kbytes in', end=' ')
print int(round(dt)), print(int(round(dt)), end=' ')
print 'seconds', print('seconds', end=' ')
if t1 > t0: if t1 > t0:
print '(~%d Kbytes/sec)' % \ print('(~%d Kbytes/sec)' % \
int(round(kbytes/dt),) int(round(kbytes/dt),))
print print()
# #
# Remove files from info that are no longer remote # Remove files from info that are no longer remote
deletions = 0 deletions = 0
for filename in info.keys(): for filename in info.keys():
if filename not in filesfound: if filename not in filesfound:
if verbose: if verbose:
print "Removing obsolete info entry for", print("Removing obsolete info entry for", end=' ')
print repr(filename), "in", repr(localdir or ".") print(repr(filename), "in", repr(localdir or "."))
del info[filename] del info[filename]
deletions = deletions + 1 deletions = deletions + 1
if deletions: if deletions:
@ -264,8 +264,8 @@ def mirrorsubdir(f, localdir):
for pat in skippats: for pat in skippats:
if fnmatch(name, pat): if fnmatch(name, pat):
if verbose > 1: if verbose > 1:
print 'Skip pattern', repr(pat), print('Skip pattern', repr(pat), end=' ')
print 'matches', repr(name) print('matches', repr(name))
skip = 1 skip = 1
break break
if skip: if skip:
@ -273,10 +273,10 @@ def mirrorsubdir(f, localdir):
fullname = os.path.join(localdir, name) fullname = os.path.join(localdir, name)
if not rmok: if not rmok:
if verbose: if verbose:
print 'Local file', repr(fullname), print('Local file', repr(fullname), end=' ')
print 'is no longer pertinent' print('is no longer pertinent')
continue continue
if verbose: print 'Removing local file/dir', repr(fullname) if verbose: print('Removing local file/dir', repr(fullname))
remove(fullname) remove(fullname)
# #
# Recursively mirror subdirectories # Recursively mirror subdirectories
@ -284,28 +284,28 @@ def mirrorsubdir(f, localdir):
if interactive: if interactive:
doit = askabout('subdirectory', subdir, pwd) doit = askabout('subdirectory', subdir, pwd)
if not doit: continue if not doit: continue
if verbose: print 'Processing subdirectory', repr(subdir) if verbose: print('Processing subdirectory', repr(subdir))
localsubdir = os.path.join(localdir, subdir) localsubdir = os.path.join(localdir, subdir)
pwd = f.pwd() pwd = f.pwd()
if verbose > 1: if verbose > 1:
print 'Remote directory now:', repr(pwd) print('Remote directory now:', repr(pwd))
print 'Remote cwd', repr(subdir) print('Remote cwd', repr(subdir))
try: try:
f.cwd(subdir) f.cwd(subdir)
except ftplib.error_perm as msg: except ftplib.error_perm as msg:
print "Can't chdir to", repr(subdir), ":", repr(msg) print("Can't chdir to", repr(subdir), ":", repr(msg))
else: else:
if verbose: print 'Mirroring as', repr(localsubdir) if verbose: print('Mirroring as', repr(localsubdir))
mirrorsubdir(f, localsubdir) mirrorsubdir(f, localsubdir)
if verbose > 1: print 'Remote cwd ..' if verbose > 1: print('Remote cwd ..')
f.cwd('..') f.cwd('..')
newpwd = f.pwd() newpwd = f.pwd()
if newpwd != pwd: if newpwd != pwd:
print 'Ended up in wrong directory after cd + cd ..' print('Ended up in wrong directory after cd + cd ..')
print 'Giving up now.' print('Giving up now.')
break break
else: else:
if verbose > 1: print 'OK.' if verbose > 1: print('OK.')
# Helper to remove a file or directory tree # Helper to remove a file or directory tree
def remove(fullname): def remove(fullname):
@ -323,13 +323,13 @@ def remove(fullname):
try: try:
os.rmdir(fullname) os.rmdir(fullname)
except os.error as msg: except os.error as msg:
print "Can't remove local directory %r: %s" % (fullname, msg) print("Can't remove local directory %r: %s" % (fullname, msg))
return 0 return 0
else: else:
try: try:
os.unlink(fullname) os.unlink(fullname)
except os.error as msg: except os.error as msg:
print "Can't remove local file %r: %s" % (fullname, msg) print("Can't remove local file %r: %s" % (fullname, msg))
return 0 return 0
return 1 return 1
@ -366,7 +366,7 @@ def askabout(filetype, filename, pwd):
return 1 return 1
if reply in ['', 'n', 'no', 'nop', 'nope']: if reply in ['', 'n', 'no', 'nop', 'nope']:
return 0 return 0
print 'Please answer yes or no.' print('Please answer yes or no.')
# Create a directory if it doesn't exist. Recursively create the # Create a directory if it doesn't exist. Recursively create the
# parent directory as well if needed. # parent directory as well if needed.

View File

@ -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:

View File

@ -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()

View File

@ -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():
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,

View File

@ -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__':

View File

@ -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):
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))

View File

@ -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):
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):
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

View File

@ -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):

View File

@ -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):
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

View File

@ -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():
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():
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():
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():
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():
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():
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():
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

View File

@ -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):
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

View File

@ -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):
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)

View File

@ -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__':

View File

@ -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 = ''

View File

@ -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=[]):
# 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=[]):
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=[]):
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=[]):
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=[]):
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=[]):
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):
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):
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:

View File

@ -275,7 +275,7 @@ class TexinfoParser:
if not self.skip: self.process(accu) if not self.skip: self.process(accu)
accu = [] accu = []
if initial_lineno > 0: if initial_lineno > 0:
print '*** EOF before @bye' print('*** EOF before @bye')
break break
lineno = lineno + 1 lineno = lineno + 1
mo = cmprog.match(line) mo = cmprog.match(line)
@ -306,10 +306,10 @@ class TexinfoParser:
accu.append(line) accu.append(line)
# #
if self.skip: if self.skip:
print '*** Still skipping at the end' print('*** Still skipping at the end')
if self.stack: if self.stack:
print '*** Stack not empty at the end' print('*** Stack not empty at the end')
print '***', self.stack print('***', self.stack)
if self.includedepth == 0: if self.includedepth == 0:
while self.nodestack: while self.nodestack:
self.nodestack[-1].finalize() self.nodestack[-1].finalize()
@ -338,7 +338,7 @@ class TexinfoParser:
try: try:
text = ''.join(args) text = ''.join(args)
except: except:
print args print(args)
raise TypeError raise TypeError
if self.savetext <> None: if self.savetext <> None:
self.savetext = self.savetext + text self.savetext = self.savetext + text
@ -350,7 +350,7 @@ class TexinfoParser:
# Complete the current node -- write footnotes and close file # Complete the current node -- write footnotes and close file
def endnode(self): def endnode(self):
if self.savetext <> None: if self.savetext <> None:
print '*** Still saving text at end of node' print('*** Still saving text at end of node')
dummy = self.collectsavings() dummy = self.collectsavings()
if self.footnotes: if self.footnotes:
self.writefootnotes() self.writefootnotes()
@ -382,10 +382,10 @@ class TexinfoParser:
# This mostly distinguishes between menus and normal text # This mostly distinguishes between menus and normal text
def process(self, accu): def process(self, accu):
if self.debugging > 1: if self.debugging > 1:
print '!'*self.debugging, 'process:', self.skip, self.stack, print('!'*self.debugging, 'process:', self.skip, self.stack, end=' ')
if accu: print accu[0][:30], if accu: print(accu[0][:30], end=' ')
if accu[0][30:] or accu[1:]: print '...', if accu[0][30:] or accu[1:]: print('...', end=' ')
print print()
if self.inmenu(): if self.inmenu():
# XXX should be done differently # XXX should be done differently
for line in accu: for line in accu:
@ -461,7 +461,7 @@ class TexinfoParser:
continue continue
if c == '}': if c == '}':
if not stack: if not stack:
print '*** Unmatched }' print('*** Unmatched }')
self.write('}') self.write('}')
continue continue
cmd = stack[-1] cmd = stack[-1]
@ -509,12 +509,12 @@ class TexinfoParser:
continue continue
method() method()
if stack: if stack:
print '*** Stack not empty at para:', stack print('*** Stack not empty at para:', stack)
# --- Handle unknown embedded @-commands --- # --- Handle unknown embedded @-commands ---
def unknown_open(self, cmd): def unknown_open(self, cmd):
print '*** No open func for @' + cmd + '{...}' print('*** No open func for @' + cmd + '{...}')
cmd = cmd + '{' cmd = cmd + '{'
self.write('@', cmd) self.write('@', cmd)
if not self.unknown.has_key(cmd): if not self.unknown.has_key(cmd):
@ -523,7 +523,7 @@ class TexinfoParser:
self.unknown[cmd] = self.unknown[cmd] + 1 self.unknown[cmd] = self.unknown[cmd] + 1
def unknown_close(self, cmd): def unknown_close(self, cmd):
print '*** No close func for @' + cmd + '{...}' print('*** No close func for @' + cmd + '{...}')
cmd = '}' + cmd cmd = '}' + cmd
self.write('}') self.write('}')
if not self.unknown.has_key(cmd): if not self.unknown.has_key(cmd):
@ -532,7 +532,7 @@ class TexinfoParser:
self.unknown[cmd] = self.unknown[cmd] + 1 self.unknown[cmd] = self.unknown[cmd] + 1
def unknown_handle(self, cmd): def unknown_handle(self, cmd):
print '*** No handler for @' + cmd print('*** No handler for @' + cmd)
self.write('@', cmd) self.write('@', cmd)
if not self.unknown.has_key(cmd): if not self.unknown.has_key(cmd):
self.unknown[cmd] = 1 self.unknown[cmd] = 1
@ -555,9 +555,9 @@ class TexinfoParser:
try: try:
fp = open(file, 'r') fp = open(file, 'r')
except IOError as msg: except IOError as msg:
print '*** Can\'t open include file', repr(file) print('*** Can\'t open include file', repr(file))
return return
print '!'*self.debugging, '--> file', repr(file) print('!'*self.debugging, '--> file', repr(file))
save_done = self.done save_done = self.done
save_skip = self.skip save_skip = self.skip
save_stack = self.stack save_stack = self.stack
@ -568,7 +568,7 @@ class TexinfoParser:
self.done = save_done self.done = save_done
self.skip = save_skip self.skip = save_skip
self.stack = save_stack self.stack = save_stack
print '!'*self.debugging, '<-- file', repr(file) print('!'*self.debugging, '<-- file', repr(file))
# --- Special Insertions --- # --- Special Insertions ---
@ -764,7 +764,7 @@ class TexinfoParser:
elif os.path.exists(imagelocation+'.gif'): # MySQL uses GIF files elif os.path.exists(imagelocation+'.gif'): # MySQL uses GIF files
filename += '.gif' filename += '.gif'
else: else:
print "*** Cannot find image " + imagelocation print("*** Cannot find image " + imagelocation)
#TODO: what is 'ext'? #TODO: what is 'ext'?
self.write('<IMG SRC="', filename, '"', \ self.write('<IMG SRC="', filename, '"', \
width and (' WIDTH="' + width + '"') or "", \ width and (' WIDTH="' + width + '"') or "", \
@ -871,8 +871,8 @@ class TexinfoParser:
cmd = line[a:b] cmd = line[a:b]
args = line[b:].strip() args = line[b:].strip()
if self.debugging > 1: if self.debugging > 1:
print '!'*self.debugging, 'command:', self.skip, self.stack, \ print('!'*self.debugging, 'command:', self.skip, self.stack, \
'@' + cmd, args '@' + cmd, args)
try: try:
func = getattr(self, 'do_' + cmd) func = getattr(self, 'do_' + cmd)
except AttributeError: except AttributeError:
@ -890,7 +890,7 @@ class TexinfoParser:
func(args) func(args)
def unknown_cmd(self, cmd, args): def unknown_cmd(self, cmd, args):
print '*** unknown', '@' + cmd, args print('*** unknown', '@' + cmd, args)
if not self.unknown.has_key(cmd): if not self.unknown.has_key(cmd):
self.unknown[cmd] = 1 self.unknown[cmd] = 1
else: else:
@ -899,11 +899,11 @@ class TexinfoParser:
def do_end(self, args): def do_end(self, args):
words = args.split() words = args.split()
if not words: if not words:
print '*** @end w/o args' print('*** @end w/o args')
else: else:
cmd = words[0] cmd = words[0]
if not self.stack or self.stack[-1] <> cmd: if not self.stack or self.stack[-1] <> cmd:
print '*** @end', cmd, 'unexpected' print('*** @end', cmd, 'unexpected')
else: else:
del self.stack[-1] del self.stack[-1]
try: try:
@ -915,7 +915,7 @@ class TexinfoParser:
def unknown_end(self, cmd): def unknown_end(self, cmd):
cmd = 'end ' + cmd cmd = 'end ' + cmd
print '*** unknown', '@' + cmd print('*** unknown', '@' + cmd)
if not self.unknown.has_key(cmd): if not self.unknown.has_key(cmd):
self.unknown[cmd] = 1 self.unknown[cmd] = 1
else: else:
@ -965,7 +965,7 @@ class TexinfoParser:
self.skip = self.skip - 1 self.skip = self.skip - 1
del self.stackinfo[len(self.stack) + 1] del self.stackinfo[len(self.stack) + 1]
except KeyError: except KeyError:
print '*** end_ifset: KeyError :', len(self.stack) + 1 print('*** end_ifset: KeyError :', len(self.stack) + 1)
def bgn_ifclear(self, args): def bgn_ifclear(self, args):
if args in self.values.keys() \ if args in self.values.keys() \
@ -980,7 +980,7 @@ class TexinfoParser:
self.skip = self.skip - 1 self.skip = self.skip - 1
del self.stackinfo[len(self.stack) + 1] del self.stackinfo[len(self.stack) + 1]
except KeyError: except KeyError:
print '*** end_ifclear: KeyError :', len(self.stack) + 1 print('*** end_ifclear: KeyError :', len(self.stack) + 1)
def open_value(self): def open_value(self):
self.startsaving() self.startsaving()
@ -990,7 +990,7 @@ class TexinfoParser:
if key in self.values.keys(): if key in self.values.keys():
self.write(self.values[key]) self.write(self.values[key])
else: else:
print '*** Undefined value: ', key print('*** Undefined value: ', key)
# --- Beginning a file --- # --- Beginning a file ---
@ -1052,9 +1052,9 @@ class TexinfoParser:
[name, next, prev, up] = parts[:4] [name, next, prev, up] = parts[:4]
file = self.dirname + '/' + makefile(name) file = self.dirname + '/' + makefile(name)
if self.filenames.has_key(file): if self.filenames.has_key(file):
print '*** Filename already in use: ', file print('*** Filename already in use: ', file)
else: else:
if self.debugging: print '!'*self.debugging, '--- writing', file if self.debugging: print('!'*self.debugging, '--- writing', file)
self.filenames[file] = 1 self.filenames[file] = 1
# self.nodefp = open(file, 'w') # self.nodefp = open(file, 'w')
self.nodename = name self.nodename = name
@ -1169,7 +1169,7 @@ class TexinfoParser:
self.expand(args) self.expand(args)
self.write('</', type, '>\n') self.write('</', type, '>\n')
if self.debugging or self.print_headers: if self.debugging or self.print_headers:
print '---', args print('---', args)
def do_contents(self, args): def do_contents(self, args):
# pass # pass
@ -1549,7 +1549,7 @@ class TexinfoParser:
if self.whichindex.has_key(name): if self.whichindex.has_key(name):
self.index(name, args) self.index(name, args)
else: else:
print '*** No index named', repr(name) print('*** No index named', repr(name))
def do_cindex(self, args): self.index('cp', args) def do_cindex(self, args): self.index('cp', args)
def do_findex(self, args): self.index('fn', args) def do_findex(self, args): self.index('fn', args)
@ -1565,12 +1565,12 @@ class TexinfoParser:
def do_synindex(self, args): def do_synindex(self, args):
words = args.split() words = args.split()
if len(words) <> 2: if len(words) <> 2:
print '*** bad @synindex', args print('*** bad @synindex', args)
return return
[old, new] = words [old, new] = words
if not self.whichindex.has_key(old) or \ if not self.whichindex.has_key(old) or \
not self.whichindex.has_key(new): not self.whichindex.has_key(new):
print '*** bad key(s) in @synindex', args print('*** bad key(s) in @synindex', args)
return return
if old <> new and \ if old <> new and \
self.whichindex[old] is not self.whichindex[new]: self.whichindex[old] is not self.whichindex[new]:
@ -1585,15 +1585,15 @@ class TexinfoParser:
if self.whichindex.has_key(name): if self.whichindex.has_key(name):
self.prindex(name) self.prindex(name)
else: else:
print '*** No index named', repr(name) print('*** No index named', repr(name))
def prindex(self, name): def prindex(self, name):
iscodeindex = (name not in self.noncodeindices) iscodeindex = (name not in self.noncodeindices)
index = self.whichindex[name] index = self.whichindex[name]
if not index: return if not index: return
if self.debugging: if self.debugging:
print '!'*self.debugging, '--- Generating', \ print('!'*self.debugging, '--- Generating', \
self.indextitle[name], 'index' self.indextitle[name], 'index')
# The node already provides a title # The node already provides a title
index1 = [] index1 = []
junkprog = re.compile('^(@[a-z]+)?{') junkprog = re.compile('^(@[a-z]+)?{')
@ -1616,7 +1616,7 @@ class TexinfoParser:
for sortkey, key, node in index1: for sortkey, key, node in index1:
if (key, node) == (prevkey, prevnode): if (key, node) == (prevkey, prevnode):
continue continue
if self.debugging > 1: print '!'*self.debugging, key, ':', node if self.debugging > 1: print('!'*self.debugging, key, ':', node)
self.write('<DT>') self.write('<DT>')
if iscodeindex: key = '@code{' + key + '}' if iscodeindex: key = '@code{' + key + '}'
if key != prevkey: if key != prevkey:
@ -1629,11 +1629,11 @@ class TexinfoParser:
def report(self): def report(self):
if self.unknown: if self.unknown:
print '--- Unrecognized commands ---' print('--- Unrecognized commands ---')
cmds = self.unknown.keys() cmds = self.unknown.keys()
cmds.sort() cmds.sort()
for cmd in cmds: for cmd in cmds:
print cmd.ljust(20), self.unknown[cmd] print(cmd.ljust(20), self.unknown[cmd])
class TexinfoParserHTML3(TexinfoParser): class TexinfoParserHTML3(TexinfoParser):
@ -1773,86 +1773,86 @@ class HTMLHelp:
# PROJECT FILE # PROJECT FILE
try: try:
fp = open(projectfile,'w') fp = open(projectfile,'w')
print>>fp, '[OPTIONS]' print('[OPTIONS]', file=fp)
print>>fp, 'Auto Index=Yes' print('Auto Index=Yes', file=fp)
print>>fp, 'Binary TOC=No' print('Binary TOC=No', file=fp)
print>>fp, 'Binary Index=Yes' print('Binary Index=Yes', file=fp)
print>>fp, 'Compatibility=1.1' print('Compatibility=1.1', file=fp)
print>>fp, 'Compiled file=' + resultfile + '' print('Compiled file=' + resultfile + '', file=fp)
print>>fp, 'Contents file=' + contentfile + '' print('Contents file=' + contentfile + '', file=fp)
print>>fp, 'Default topic=' + defaulttopic + '' print('Default topic=' + defaulttopic + '', file=fp)
print>>fp, 'Error log file=ErrorLog.log' print('Error log file=ErrorLog.log', file=fp)
print>>fp, 'Index file=' + indexfile + '' print('Index file=' + indexfile + '', file=fp)
print>>fp, 'Title=' + title + '' print('Title=' + title + '', file=fp)
print>>fp, 'Display compile progress=Yes' print('Display compile progress=Yes', file=fp)
print>>fp, 'Full-text search=Yes' print('Full-text search=Yes', file=fp)
print>>fp, 'Default window=main' print('Default window=main', file=fp)
print>>fp, '' print('', file=fp)
print>>fp, '[WINDOWS]' print('[WINDOWS]', file=fp)
print>>fp, ('main=,"' + contentfile + '","' + indexfile print('main=,"' + contentfile + '","' + indexfile
+ '","","",,,,,0x23520,222,0x1046,[10,10,780,560],' + '","","",,,,,0x23520,222,0x1046,[10,10,780,560],'
'0xB0000,,,,,,0') '0xB0000,,,,,,0', file=fp)
print>>fp, '' print('', file=fp)
print>>fp, '[FILES]' print('[FILES]', file=fp)
print>>fp, '' print('', file=fp)
self.dumpfiles(fp) self.dumpfiles(fp)
fp.close() fp.close()
except IOError as msg: except IOError as msg:
print projectfile, ':', msg print(projectfile, ':', msg)
sys.exit(1) sys.exit(1)
# CONTENT FILE # CONTENT FILE
try: try:
fp = open(contentfile,'w') fp = open(contentfile,'w')
print>>fp, '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">' print('<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">', file=fp)
print>>fp, '<!-- This file defines the table of contents -->' print('<!-- This file defines the table of contents -->', file=fp)
print>>fp, '<HTML>' print('<HTML>', file=fp)
print>>fp, '<HEAD>' print('<HEAD>', file=fp)
print>>fp, ('<meta name="GENERATOR"' print('<meta name="GENERATOR"'
'content="Microsoft&reg; HTML Help Workshop 4.1">') 'content="Microsoft&reg; HTML Help Workshop 4.1">', file=fp)
print>>fp, '<!-- Sitemap 1.0 -->' print('<!-- Sitemap 1.0 -->', file=fp)
print>>fp, '</HEAD>' print('</HEAD>', file=fp)
print>>fp, '<BODY>' print('<BODY>', file=fp)
print>>fp, ' <OBJECT type="text/site properties">' print(' <OBJECT type="text/site properties">', file=fp)
print>>fp, ' <param name="Window Styles" value="0x800025">' print(' <param name="Window Styles" value="0x800025">', file=fp)
print>>fp, ' <param name="comment" value="title:">' print(' <param name="comment" value="title:">', file=fp)
print>>fp, ' <param name="comment" value="base:">' print(' <param name="comment" value="base:">', file=fp)
print>>fp, ' </OBJECT>' print(' </OBJECT>', file=fp)
self.dumpnodes(fp) self.dumpnodes(fp)
print>>fp, '</BODY>' print('</BODY>', file=fp)
print>>fp, '</HTML>' print('</HTML>', file=fp)
fp.close() fp.close()
except IOError as msg: except IOError as msg:
print contentfile, ':', msg print(contentfile, ':', msg)
sys.exit(1) sys.exit(1)
# INDEX FILE # INDEX FILE
try: try:
fp = open(indexfile ,'w') fp = open(indexfile ,'w')
print>>fp, '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">' print('<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">', file=fp)
print>>fp, '<!-- This file defines the index -->' print('<!-- This file defines the index -->', file=fp)
print>>fp, '<HTML>' print('<HTML>', file=fp)
print>>fp, '<HEAD>' print('<HEAD>', file=fp)
print>>fp, ('<meta name="GENERATOR"' print('<meta name="GENERATOR"'
'content="Microsoft&reg; HTML Help Workshop 4.1">') 'content="Microsoft&reg; HTML Help Workshop 4.1">', file=fp)
print>>fp, '<!-- Sitemap 1.0 -->' print('<!-- Sitemap 1.0 -->', file=fp)
print>>fp, '</HEAD>' print('</HEAD>', file=fp)
print>>fp, '<BODY>' print('<BODY>', file=fp)
print>>fp, '<OBJECT type="text/site properties">' print('<OBJECT type="text/site properties">', file=fp)
print>>fp, '</OBJECT>' print('</OBJECT>', file=fp)
self.dumpindex(fp) self.dumpindex(fp)
print>>fp, '</BODY>' print('</BODY>', file=fp)
print>>fp, '</HTML>' print('</HTML>', file=fp)
fp.close() fp.close()
except IOError as msg: except IOError as msg:
print indexfile , ':', msg print(indexfile , ':', msg)
sys.exit(1) sys.exit(1)
def dumpfiles(self, outfile=sys.stdout): def dumpfiles(self, outfile=sys.stdout):
filelist = self.filenames.values() filelist = self.filenames.values()
filelist.sort() filelist.sort()
for filename in filelist: for filename in filelist:
print>>outfile, filename print(filename, file=outfile)
def dumpnodes(self, outfile=sys.stdout): def dumpnodes(self, outfile=sys.stdout):
self.dumped = {} self.dumped = {}
@ -1860,10 +1860,10 @@ class HTMLHelp:
nodename, dummy, dummy, dummy, dummy = self.nodelist[0] nodename, dummy, dummy, dummy, dummy = self.nodelist[0]
self.topnode = nodename self.topnode = nodename
print>>outfile, '<UL>' print('<UL>', file=outfile)
for node in self.nodelist: for node in self.nodelist:
self.dumpnode(node,0,outfile) self.dumpnode(node,0,outfile)
print>>outfile, '</UL>' print('</UL>', file=outfile)
def dumpnode(self, node, indent=0, outfile=sys.stdout): def dumpnode(self, node, indent=0, outfile=sys.stdout):
if node: if node:
@ -1877,11 +1877,11 @@ class HTMLHelp:
self.dumped[nodename] = 1 self.dumped[nodename] = 1
# Print info for this node # Print info for this node
print>>outfile, ' '*indent, print(' '*indent, end=' ', file=outfile)
print>>outfile, '<LI><OBJECT type="text/sitemap">', print('<LI><OBJECT type="text/sitemap">', end=' ', file=outfile)
print>>outfile, '<param name="Name" value="' + nodename +'">', print('<param name="Name" value="' + nodename +'">', end=' ', file=outfile)
print>>outfile, '<param name="Local" value="'+ filename +'">', print('<param name="Local" value="'+ filename +'">', end=' ', file=outfile)
print>>outfile, '</OBJECT>' print('</OBJECT>', file=outfile)
# Does this node have menu items? # Does this node have menu items?
try: try:
@ -1894,13 +1894,13 @@ class HTMLHelp:
if menu: if menu:
currentnode = self.current currentnode = self.current
if currentnode != self.topnode: # XXX this is a hack if currentnode != self.topnode: # XXX this is a hack
print>>outfile, ' '*indent + '<UL>' print(' '*indent + '<UL>', file=outfile)
indent += 2 indent += 2
for item in menu: for item in menu:
menunode = self.getnode(item) menunode = self.getnode(item)
self.dumpnode(menunode,indent,outfile) self.dumpnode(menunode,indent,outfile)
if currentnode != self.topnode: # XXX this is a hack if currentnode != self.topnode: # XXX this is a hack
print>>outfile, ' '*indent + '</UL>' print(' '*indent + '</UL>', file=outfile)
indent -= 2 indent -= 2
def getnode(self, nodename): def getnode(self, nodename):
@ -1914,16 +1914,16 @@ class HTMLHelp:
# (args,nodename) == (key,location) # (args,nodename) == (key,location)
def dumpindex(self, outfile=sys.stdout): def dumpindex(self, outfile=sys.stdout):
print>>outfile, '<UL>' print('<UL>', file=outfile)
for (key,location) in self.indexlist: for (key,location) in self.indexlist:
key = self.codeexpand(key) key = self.codeexpand(key)
location = makefile(location) location = makefile(location)
location = self.dirname + '/' + location location = self.dirname + '/' + location
print>>outfile, '<LI><OBJECT type="text/sitemap">', print('<LI><OBJECT type="text/sitemap">', end=' ', file=outfile)
print>>outfile, '<param name="Name" value="' + key + '">', print('<param name="Name" value="' + key + '">', end=' ', file=outfile)
print>>outfile, '<param name="Local" value="' + location + '">', print('<param name="Local" value="' + location + '">', end=' ', file=outfile)
print>>outfile, '</OBJECT>' print('</OBJECT>', file=outfile)
print>>outfile, '</UL>' print('</UL>', file=outfile)
def codeexpand(self, line): def codeexpand(self, line):
co = self.codeprog.match(line) co = self.codeprog.match(line)
@ -2041,8 +2041,8 @@ def test():
helpbase = sys.argv[2] helpbase = sys.argv[2]
del sys.argv[1:3] del sys.argv[1:3]
if len(sys.argv) <> 3: if len(sys.argv) <> 3:
print 'usage: texi2hh [-d [-d]] [-p] [-c] [-3] [-H htmlhelp]', \ print('usage: texi2hh [-d [-d]] [-p] [-c] [-3] [-H htmlhelp]', \
'inputfile outputdirectory' 'inputfile outputdirectory')
sys.exit(2) sys.exit(2)
if html3: if html3:
@ -2064,7 +2064,7 @@ def test():
try: try:
fp = open(file, 'r') fp = open(file, 'r')
except IOError as msg: except IOError as msg:
print file, ':', msg print(file, ':', msg)
sys.exit(1) sys.exit(1)
parser.parse(fp) parser.parse(fp)

View File

@ -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):
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):
# 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):
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'):
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__':

View File

@ -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):
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):
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()

View File

@ -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:

View File

@ -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):
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__':
setup() setup()
go(getargs()) go(getargs())
except KeyboardInterrupt: except KeyboardInterrupt:
print '[Intr]' print('[Intr]')

View File

@ -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):
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):
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])

View File

@ -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):
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):
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__':

View File

@ -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):
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(']')

View File

@ -60,21 +60,21 @@ UPPER_MASK = 0x80
def maketables(trace=0): def maketables(trace=0):
print "--- Reading", UNICODE_DATA % "", "..." print("--- Reading", UNICODE_DATA % "", "...")
version = "" version = ""
unicode = UnicodeData(UNICODE_DATA % version, unicode = UnicodeData(UNICODE_DATA % version,
COMPOSITION_EXCLUSIONS % version, COMPOSITION_EXCLUSIONS % version,
EASTASIAN_WIDTH % version) EASTASIAN_WIDTH % version)
print len(filter(None, unicode.table)), "characters" print(len(filter(None, unicode.table)), "characters")
for version in old_versions: for version in old_versions:
print "--- Reading", UNICODE_DATA % ("-"+version), "..." print("--- Reading", UNICODE_DATA % ("-"+version), "...")
old_unicode = UnicodeData(UNICODE_DATA % ("-"+version), old_unicode = UnicodeData(UNICODE_DATA % ("-"+version),
COMPOSITION_EXCLUSIONS % ("-"+version), COMPOSITION_EXCLUSIONS % ("-"+version),
EASTASIAN_WIDTH % ("-"+version)) EASTASIAN_WIDTH % ("-"+version))
print len(filter(None, old_unicode.table)), "characters" print(len(filter(None, old_unicode.table)), "characters")
merge_old_version(version, unicode, old_unicode) merge_old_version(version, unicode, old_unicode)
makeunicodename(unicode, trace) makeunicodename(unicode, trace)
@ -93,7 +93,7 @@ def makeunicodedata(unicode, trace):
FILE = "Modules/unicodedata_db.h" FILE = "Modules/unicodedata_db.h"
print "--- Preparing", FILE, "..." print("--- Preparing", FILE, "...")
# 1) database properties # 1) database properties
@ -203,93 +203,92 @@ def makeunicodedata(unicode, trace):
l = comp_last[l] l = comp_last[l]
comp_data[f*total_last+l] = char comp_data[f*total_last+l] = char
print len(table), "unique properties" print(len(table), "unique properties")
print len(decomp_prefix), "unique decomposition prefixes" print(len(decomp_prefix), "unique decomposition prefixes")
print len(decomp_data), "unique decomposition entries:", print(len(decomp_data), "unique decomposition entries:", end=' ')
print decomp_size, "bytes" print(decomp_size, "bytes")
print total_first, "first characters in NFC" print(total_first, "first characters in NFC")
print total_last, "last characters in NFC" print(total_last, "last characters in NFC")
print len(comp_pairs), "NFC pairs" print(len(comp_pairs), "NFC pairs")
print "--- Writing", FILE, "..." print("--- Writing", FILE, "...")
fp = open(FILE, "w") fp = open(FILE, "w")
print >>fp, "/* this file was generated by %s %s */" % (SCRIPT, VERSION) print("/* this file was generated by %s %s */" % (SCRIPT, VERSION), file=fp)
print >>fp print(file=fp)
print >>fp, '#define UNIDATA_VERSION "%s"' % UNIDATA_VERSION print('#define UNIDATA_VERSION "%s"' % UNIDATA_VERSION, file=fp)
print >>fp, "/* a list of unique database records */" print("/* a list of unique database records */", file=fp)
print >>fp, \ print("const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {", file=fp)
"const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {"
for item in table: for item in table:
print >>fp, " {%d, %d, %d, %d, %d}," % item print(" {%d, %d, %d, %d, %d}," % item, file=fp)
print >>fp, "};" print("};", file=fp)
print >>fp print(file=fp)
print >>fp, "/* Reindexing of NFC first characters. */" print("/* Reindexing of NFC first characters. */", file=fp)
print >>fp, "#define TOTAL_FIRST",total_first print("#define TOTAL_FIRST",total_first, file=fp)
print >>fp, "#define TOTAL_LAST",total_last print("#define TOTAL_LAST",total_last, file=fp)
print >>fp, "struct reindex{int start;short count,index;};" print("struct reindex{int start;short count,index;};", file=fp)
print >>fp, "struct reindex nfc_first[] = {" print("struct reindex nfc_first[] = {", file=fp)
for start,end in comp_first_ranges: for start,end in comp_first_ranges:
print >>fp," { %d, %d, %d}," % (start,end-start,comp_first[start]) print(" { %d, %d, %d}," % (start,end-start,comp_first[start]), file=fp)
print >>fp," {0,0,0}" print(" {0,0,0}", file=fp)
print >>fp,"};\n" print("};\n", file=fp)
print >>fp, "struct reindex nfc_last[] = {" print("struct reindex nfc_last[] = {", file=fp)
for start,end in comp_last_ranges: for start,end in comp_last_ranges:
print >>fp," { %d, %d, %d}," % (start,end-start,comp_last[start]) print(" { %d, %d, %d}," % (start,end-start,comp_last[start]), file=fp)
print >>fp," {0,0,0}" print(" {0,0,0}", file=fp)
print >>fp,"};\n" print("};\n", file=fp)
# FIXME: <fl> the following tables could be made static, and # FIXME: <fl> the following tables could be made static, and
# the support code moved into unicodedatabase.c # the support code moved into unicodedatabase.c
print >>fp, "/* string literals */" print("/* string literals */", file=fp)
print >>fp, "const char *_PyUnicode_CategoryNames[] = {" print("const char *_PyUnicode_CategoryNames[] = {", file=fp)
for name in CATEGORY_NAMES: for name in CATEGORY_NAMES:
print >>fp, " \"%s\"," % name print(" \"%s\"," % name, file=fp)
print >>fp, " NULL" print(" NULL", file=fp)
print >>fp, "};" print("};", file=fp)
print >>fp, "const char *_PyUnicode_BidirectionalNames[] = {" print("const char *_PyUnicode_BidirectionalNames[] = {", file=fp)
for name in BIDIRECTIONAL_NAMES: for name in BIDIRECTIONAL_NAMES:
print >>fp, " \"%s\"," % name print(" \"%s\"," % name, file=fp)
print >>fp, " NULL" print(" NULL", file=fp)
print >>fp, "};" print("};", file=fp)
print >>fp, "const char *_PyUnicode_EastAsianWidthNames[] = {" print("const char *_PyUnicode_EastAsianWidthNames[] = {", file=fp)
for name in EASTASIANWIDTH_NAMES: for name in EASTASIANWIDTH_NAMES:
print >>fp, " \"%s\"," % name print(" \"%s\"," % name, file=fp)
print >>fp, " NULL" print(" NULL", file=fp)
print >>fp, "};" print("};", file=fp)
print >>fp, "static const char *decomp_prefix[] = {" print("static const char *decomp_prefix[] = {", file=fp)
for name in decomp_prefix: for name in decomp_prefix:
print >>fp, " \"%s\"," % name print(" \"%s\"," % name, file=fp)
print >>fp, " NULL" print(" NULL", file=fp)
print >>fp, "};" print("};", file=fp)
# split record index table # split record index table
index1, index2, shift = splitbins(index, trace) index1, index2, shift = splitbins(index, trace)
print >>fp, "/* index tables for the database records */" print("/* index tables for the database records */", file=fp)
print >>fp, "#define SHIFT", shift print("#define SHIFT", shift, file=fp)
Array("index1", index1).dump(fp, trace) Array("index1", index1).dump(fp, trace)
Array("index2", index2).dump(fp, trace) Array("index2", index2).dump(fp, trace)
# split decomposition index table # split decomposition index table
index1, index2, shift = splitbins(decomp_index, trace) index1, index2, shift = splitbins(decomp_index, trace)
print >>fp, "/* decomposition data */" print("/* decomposition data */", file=fp)
Array("decomp_data", decomp_data).dump(fp, trace) Array("decomp_data", decomp_data).dump(fp, trace)
print >>fp, "/* index tables for the decomposition data */" print("/* index tables for the decomposition data */", file=fp)
print >>fp, "#define DECOMP_SHIFT", shift print("#define DECOMP_SHIFT", shift, file=fp)
Array("decomp_index1", index1).dump(fp, trace) Array("decomp_index1", index1).dump(fp, trace)
Array("decomp_index2", index2).dump(fp, trace) Array("decomp_index2", index2).dump(fp, trace)
index, index2, shift = splitbins(comp_data, trace) index, index2, shift = splitbins(comp_data, trace)
print >>fp, "/* NFC pairs */" print("/* NFC pairs */", file=fp)
print >>fp, "#define COMP_SHIFT", shift print("#define COMP_SHIFT", shift, file=fp)
Array("comp_index", index).dump(fp, trace) Array("comp_index", index).dump(fp, trace)
Array("comp_data", index2).dump(fp, trace) Array("comp_data", index2).dump(fp, trace)
@ -306,30 +305,30 @@ def makeunicodedata(unicode, trace):
index[i] = cache[record] = len(records) index[i] = cache[record] = len(records)
records.append(record) records.append(record)
index1, index2, shift = splitbins(index, trace) index1, index2, shift = splitbins(index, trace)
print >>fp, "static const change_record change_records_%s[] = {" % cversion print("static const change_record change_records_%s[] = {" % cversion, file=fp)
for record in records: for record in records:
print >>fp, "\t{ %s }," % ", ".join(map(str,record)) print("\t{ %s }," % ", ".join(map(str,record)), file=fp)
print >>fp, "};" print("};", file=fp)
Array("changes_%s_index" % cversion, index1).dump(fp, trace) Array("changes_%s_index" % cversion, index1).dump(fp, trace)
Array("changes_%s_data" % cversion, index2).dump(fp, trace) Array("changes_%s_data" % cversion, index2).dump(fp, trace)
print >>fp, "static const change_record* get_change_%s(Py_UCS4 n)" % cversion print("static const change_record* get_change_%s(Py_UCS4 n)" % cversion, file=fp)
print >>fp, "{" print("{", file=fp)
print >>fp, "\tint index;" print("\tint index;", file=fp)
print >>fp, "\tif (n >= 0x110000) index = 0;" print("\tif (n >= 0x110000) index = 0;", file=fp)
print >>fp, "\telse {" print("\telse {", file=fp)
print >>fp, "\t\tindex = changes_%s_index[n>>%d];" % (cversion, shift) print("\t\tindex = changes_%s_index[n>>%d];" % (cversion, shift), file=fp)
print >>fp, "\t\tindex = changes_%s_data[(index<<%d)+(n & %d)];" % \ print("\t\tindex = changes_%s_data[(index<<%d)+(n & %d)];" % \
(cversion, shift, ((1<<shift)-1)) (cversion, shift, ((1<<shift)-1)), file=fp)
print >>fp, "\t}" print("\t}", file=fp)
print >>fp, "\treturn change_records_%s+index;" % cversion print("\treturn change_records_%s+index;" % cversion, file=fp)
print >>fp, "}\n" print("}\n", file=fp)
print >>fp, "static Py_UCS4 normalization_%s(Py_UCS4 n)" % cversion print("static Py_UCS4 normalization_%s(Py_UCS4 n)" % cversion, file=fp)
print >>fp, "{" print("{", file=fp)
print >>fp, "\tswitch(n) {" print("\tswitch(n) {", file=fp)
for k, v in normalization: for k, v in normalization:
print >>fp, "\tcase %s: return 0x%s;" % (hex(k), v) print("\tcase %s: return 0x%s;" % (hex(k), v), file=fp)
print >>fp, "\tdefault: return 0;" print("\tdefault: return 0;", file=fp)
print >>fp, "\t}\n}\n" print("\t}\n}\n", file=fp)
fp.close() fp.close()
@ -340,7 +339,7 @@ def makeunicodetype(unicode, trace):
FILE = "Objects/unicodetype_db.h" FILE = "Objects/unicodetype_db.h"
print "--- Preparing", FILE, "..." print("--- Preparing", FILE, "...")
# extract unicode types # extract unicode types
dummy = (0, 0, 0, 0, 0, 0) dummy = (0, 0, 0, 0, 0, 0)
@ -405,25 +404,25 @@ def makeunicodetype(unicode, trace):
table.append(item) table.append(item)
index[char] = i index[char] = i
print len(table), "unique character type entries" print(len(table), "unique character type entries")
print "--- Writing", FILE, "..." print("--- Writing", FILE, "...")
fp = open(FILE, "w") fp = open(FILE, "w")
print >>fp, "/* this file was generated by %s %s */" % (SCRIPT, VERSION) print("/* this file was generated by %s %s */" % (SCRIPT, VERSION), file=fp)
print >>fp print(file=fp)
print >>fp, "/* a list of unique character type descriptors */" print("/* a list of unique character type descriptors */", file=fp)
print >>fp, "const _PyUnicode_TypeRecord _PyUnicode_TypeRecords[] = {" print("const _PyUnicode_TypeRecord _PyUnicode_TypeRecords[] = {", file=fp)
for item in table: for item in table:
print >>fp, " {%d, %d, %d, %d, %d, %d}," % item print(" {%d, %d, %d, %d, %d, %d}," % item, file=fp)
print >>fp, "};" print("};", file=fp)
print >>fp print(file=fp)
# split decomposition index table # split decomposition index table
index1, index2, shift = splitbins(index, trace) index1, index2, shift = splitbins(index, trace)
print >>fp, "/* type indexes */" print("/* type indexes */", file=fp)
print >>fp, "#define SHIFT", shift print("#define SHIFT", shift, file=fp)
Array("index1", index1).dump(fp, trace) Array("index1", index1).dump(fp, trace)
Array("index2", index2).dump(fp, trace) Array("index2", index2).dump(fp, trace)
@ -436,7 +435,7 @@ def makeunicodename(unicode, trace):
FILE = "Modules/unicodename_db.h" FILE = "Modules/unicodename_db.h"
print "--- Preparing", FILE, "..." print("--- Preparing", FILE, "...")
# collect names # collect names
names = [None] * len(unicode.chars) names = [None] * len(unicode.chars)
@ -448,7 +447,7 @@ def makeunicodename(unicode, trace):
if name and name[0] != "<": if name and name[0] != "<":
names[char] = name + chr(0) names[char] = name + chr(0)
print len(filter(lambda n: n is not None, names)), "distinct names" print(len(filter(lambda n: n is not None, names)), "distinct names")
# collect unique words from names (note that we differ between # collect unique words from names (note that we differ between
# words inside a sentence, and words ending a sentence. the # words inside a sentence, and words ending a sentence. the
@ -469,7 +468,7 @@ def makeunicodename(unicode, trace):
else: else:
words[w] = [len(words)] words[w] = [len(words)]
print n, "words in text;", b, "bytes" print(n, "words in text;", b, "bytes")
wordlist = words.items() wordlist = words.items()
@ -485,19 +484,19 @@ def makeunicodename(unicode, trace):
escapes = 0 escapes = 0
while escapes * 256 < len(wordlist): while escapes * 256 < len(wordlist):
escapes = escapes + 1 escapes = escapes + 1
print escapes, "escapes" print(escapes, "escapes")
short = 256 - escapes short = 256 - escapes
assert short > 0 assert short > 0
print short, "short indexes in lexicon" print(short, "short indexes in lexicon")
# statistics # statistics
n = 0 n = 0
for i in range(short): for i in range(short):
n = n + len(wordlist[i][1]) n = n + len(wordlist[i][1])
print n, "short indexes in phrasebook" print(n, "short indexes in phrasebook")
# pick the most commonly used words, and sort the rest on falling # pick the most commonly used words, and sort the rest on falling
# length (to maximize overlap) # length (to maximize overlap)
@ -566,29 +565,29 @@ def makeunicodename(unicode, trace):
codehash = Hash("code", data, 47) codehash = Hash("code", data, 47)
print "--- Writing", FILE, "..." print("--- Writing", FILE, "...")
fp = open(FILE, "w") fp = open(FILE, "w")
print >>fp, "/* this file was generated by %s %s */" % (SCRIPT, VERSION) print("/* this file was generated by %s %s */" % (SCRIPT, VERSION), file=fp)
print >>fp print(file=fp)
print >>fp, "#define NAME_MAXLEN", 256 print("#define NAME_MAXLEN", 256, file=fp)
print >>fp print(file=fp)
print >>fp, "/* lexicon */" print("/* lexicon */", file=fp)
Array("lexicon", lexicon).dump(fp, trace) Array("lexicon", lexicon).dump(fp, trace)
Array("lexicon_offset", lexicon_offset).dump(fp, trace) Array("lexicon_offset", lexicon_offset).dump(fp, trace)
# split decomposition index table # split decomposition index table
offset1, offset2, shift = splitbins(phrasebook_offset, trace) offset1, offset2, shift = splitbins(phrasebook_offset, trace)
print >>fp, "/* code->name phrasebook */" print("/* code->name phrasebook */", file=fp)
print >>fp, "#define phrasebook_shift", shift print("#define phrasebook_shift", shift, file=fp)
print >>fp, "#define phrasebook_short", short print("#define phrasebook_short", short, file=fp)
Array("phrasebook", phrasebook).dump(fp, trace) Array("phrasebook", phrasebook).dump(fp, trace)
Array("phrasebook_offset1", offset1).dump(fp, trace) Array("phrasebook_offset1", offset1).dump(fp, trace)
Array("phrasebook_offset2", offset2).dump(fp, trace) Array("phrasebook_offset2", offset2).dump(fp, trace)
print >>fp, "/* name->code dictionary */" print("/* name->code dictionary */", file=fp)
codehash.dump(fp, trace) codehash.dump(fp, trace)
fp.close() fp.close()
@ -781,7 +780,7 @@ class Hash:
else: else:
raise AssertionError, "ran out of polynominals" raise AssertionError, "ran out of polynominals"
print size, "slots in hash table" print(size, "slots in hash table")
table = [None] * size table = [None] * size
@ -813,7 +812,7 @@ class Hash:
if incr > mask: if incr > mask:
incr = incr ^ poly incr = incr ^ poly
print n, "collisions" print(n, "collisions")
self.collisions = n self.collisions = n
for i in range(len(table)): for i in range(len(table)):
@ -845,7 +844,7 @@ class Array:
# write data to file, as a C array # write data to file, as a C array
size = getsize(self.data) size = getsize(self.data)
if trace: if trace:
print >>sys.stderr, self.name+":", size*len(self.data), "bytes" print(self.name+":", size*len(self.data), "bytes", file=sys.stderr)
file.write("static ") file.write("static ")
if size == 1: if size == 1:
file.write("unsigned char") file.write("unsigned char")
@ -895,10 +894,10 @@ def splitbins(t, trace=0):
import sys import sys
if trace: if trace:
def dump(t1, t2, shift, bytes): def dump(t1, t2, shift, bytes):
print >>sys.stderr, "%d+%d bins at shift %d; %d bytes" % ( print("%d+%d bins at shift %d; %d bytes" % (
len(t1), len(t2), shift, bytes) len(t1), len(t2), shift, bytes), file=sys.stderr)
print >>sys.stderr, "Size of original table:", len(t)*getsize(t), \ print("Size of original table:", len(t)*getsize(t), \
"bytes" "bytes", file=sys.stderr)
n = len(t)-1 # last valid index n = len(t)-1 # last valid index
maxshift = 0 # the most we can shift n and still have something left maxshift = 0 # the most we can shift n and still have something left
if n > 0: if n > 0:
@ -930,7 +929,7 @@ def splitbins(t, trace=0):
bytes = b bytes = b
t1, t2, shift = best t1, t2, shift = best
if trace: if trace:
print >>sys.stderr, "Best:", print("Best:", end=' ', file=sys.stderr)
dump(t1, t2, shift, bytes) dump(t1, t2, shift, bytes)
if __debug__: if __debug__:
# exhaustively verify that the decomposition is correct # exhaustively verify that the decomposition is correct

View File

@ -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.
\"\"\" \"\"\"
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))
# 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]
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():
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():
# 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):
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]
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"
# 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))
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
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):
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"
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) +
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"
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"
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"
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"
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"
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"
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"
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"
""" """)

View File

@ -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():
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':

View File

@ -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):
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):
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)

View File

@ -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

View File

@ -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():
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():
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:
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:
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):

View File

@ -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():
('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):
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)