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

@ -109,14 +109,14 @@ class Stats:
cols.insert(0, "ext")
def printheader():
for col in cols:
print "%*s" % (colwidth[col], col),
print
print("%*s" % (colwidth[col], col), end=' ')
print()
printheader()
for ext in exts:
for col in cols:
value = self.stats[ext].get(col, "")
print "%*s" % (colwidth[col], value),
print
print("%*s" % (colwidth[col], value), end=' ')
print()
printheader() # Another header at the bottom
def main():

View file

@ -52,8 +52,8 @@ def main():
size = st[ST_SIZE]
age = now - anytime
byteyears = float(size) * float(age) / secs_per_year
print filename.ljust(maxlen),
print repr(int(byteyears)).rjust(8)
print(filename.ljust(maxlen), end=' ')
print(repr(int(byteyears)).rjust(8))
sys.exit(status)

View file

@ -65,7 +65,7 @@ def main():
def check(file):
if os.path.isdir(file) and not os.path.islink(file):
if verbose:
print "%r: listing directory" % (file,)
print("%r: listing directory" % (file,))
names = os.listdir(file)
for name in names:
fullname = os.path.join(file, name)
@ -82,11 +82,11 @@ def check(file):
return
if verbose > 1:
print "checking %r ..." % (file,)
print("checking %r ..." % (file,))
ok = AppendChecker(file, f).run()
if verbose and ok:
print "%r: Clean bill of health." % (file,)
print("%r: Clean bill of health." % (file,))
[FIND_DOT,
FIND_APPEND,
@ -149,8 +149,8 @@ class AppendChecker:
state = FIND_DOT
elif token == "," and self.level == 1:
self.nerrors = self.nerrors + 1
print "%s(%d):\n%s" % (self.fname, self.lineno,
self.line)
print("%s(%d):\n%s" % (self.fname, self.lineno,
self.line))
# don't gripe about this stmt again
state = FIND_STMT

View file

@ -17,15 +17,15 @@ def main():
silent = 1
MAGIC = imp.get_magic()
if not silent:
print 'Using MAGIC word', repr(MAGIC)
print('Using MAGIC word', repr(MAGIC))
for dirname in sys.path:
try:
names = os.listdir(dirname)
except os.error:
print 'Cannot list directory', repr(dirname)
print('Cannot list directory', repr(dirname))
continue
if not silent:
print 'Checking ', repr(dirname), '...'
print('Checking ', repr(dirname), '...')
names.sort()
for name in names:
if name[-3:] == '.py':
@ -33,29 +33,29 @@ def main():
try:
st = os.stat(name)
except os.error:
print 'Cannot stat', repr(name)
print('Cannot stat', repr(name))
continue
if verbose:
print 'Check', repr(name), '...'
print('Check', repr(name), '...')
name_c = name + 'c'
try:
f = open(name_c, 'r')
except IOError:
print 'Cannot open', repr(name_c)
print('Cannot open', repr(name_c))
continue
magic_str = f.read(4)
mtime_str = f.read(4)
f.close()
if magic_str <> MAGIC:
print 'Bad MAGIC word in ".pyc" file',
print repr(name_c)
print('Bad MAGIC word in ".pyc" file', end=' ')
print(repr(name_c))
continue
mtime = get_long(mtime_str)
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]:
print 'Out-of-date ".pyc" file',
print repr(name_c)
print('Out-of-date ".pyc" file', end=' ')
print(repr(name_c))
def get_long(s):
if len(s) <> 4:

View file

@ -78,7 +78,7 @@ def main():
def check(file):
if os.path.isdir(file) and not os.path.islink(file):
if verbose:
print "listing directory", file
print("listing directory", file)
names = os.listdir(file)
for name in names:
fullname = os.path.join(file, name)
@ -89,7 +89,7 @@ def check(file):
return
if verbose:
print "checking", file, "...",
print("checking", file, "...", end=' ')
try:
f = open(file)
except IOError as msg:
@ -103,33 +103,33 @@ def check(file):
f.close()
if changed:
if verbose:
print "changed."
print("changed.")
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:
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):
print ff.lines[i],
print(ff.lines[i], end=' ')
if line is None:
print "-- deleted"
print("-- deleted")
else:
print "-- change to:"
print line,
print("-- change to:")
print(line, end=' ')
if not dryrun:
bak = file + ".bak"
if os.path.exists(bak):
os.remove(bak)
os.rename(file, bak)
if verbose:
print "renamed", file, "to", bak
print("renamed", file, "to", bak)
g = open(file, "w")
ff.write(g)
g.close()
if verbose:
print "wrote new", file
print("wrote new", file)
else:
if verbose:
print "unchanged."
print("unchanged.")
class FutureFinder:

View file

@ -102,7 +102,7 @@ def combine(fname):
addr, addr2rc[addr], addr2guts[addr] = m.groups()
before += 1
else:
print '??? skipped:', line
print('??? skipped:', line)
after = 0
for line in read(fi, crack, True):
@ -111,17 +111,17 @@ def combine(fname):
assert m
addr, rc, guts = m.groups() # guts is type name here
if addr not in addr2rc:
print '??? new object created while tearing down:', line.rstrip()
print('??? new object created while tearing down:', line.rstrip())
continue
print addr,
print(addr, end=' ')
if rc == addr2rc[addr]:
print '[%s]' % rc,
print('[%s]' % rc, end=' ')
else:
print '[%s->%s]' % (addr2rc[addr], rc),
print guts, addr2guts[addr]
print('[%s->%s]' % (addr2rc[addr], rc), end=' ')
print(guts, addr2guts[addr])
f.close()
print "%d objects before, %d after" % (before, after)
print("%d objects before, %d after" % (before, after))
if __name__ == '__main__':
combine(sys.argv[1])

View file

@ -6,15 +6,15 @@ import sys, os
def main():
for filename in sys.argv[1:]:
if os.path.isdir(filename):
print filename, "Directory!"
print(filename, "Directory!")
continue
data = open(filename, "rb").read()
if '\0' in data:
print filename, "Binary!"
print(filename, "Binary!")
continue
newdata = data.replace("\r\n", "\n")
if newdata != data:
print filename
print(filename)
f = open(filename, "wb")
f.write(newdata)
f.close()

View file

@ -21,8 +21,8 @@ def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "n:")
except getopt.error as msg:
print msg
print __doc__,
print(msg)
print(__doc__, end=' ')
return 1
global cutofftime
newerfile = None
@ -57,7 +57,7 @@ def process(dir):
if cutofftime and getmtime(fullname) <= cutofftime:
pass
else:
print fullname
print(fullname)
for sub in subdirs:
process(sub)

View file

@ -51,7 +51,7 @@ def show(total, d, prefix):
if tsub is None:
psub = prefix
else:
print prefix + repr(tsub).rjust(width) + ' ' + key
print(prefix + repr(tsub).rjust(width) + ' ' + key)
psub = prefix + ' '*(width-1) + '|' + ' '*(len(key)+1)
if d.has_key(key):
show(tsub, d[key][1], psub)

View file

@ -32,7 +32,7 @@ def main():
listnames = 0
for o, a in opts:
if o == "-h":
print __doc__
print(__doc__)
return
if o == "-l":
listnames = 1
@ -60,11 +60,11 @@ def process(filename, listnames):
for type, token, (row, col), end, line in g:
if token in ("/", "/="):
if listnames:
print filename
print(filename)
break
if row != lastrow:
lastrow = row
print "%s:%d:%s" % (filename, row, line),
print("%s:%d:%s" % (filename, row, line), end=' ')
fp.close()
def processdir(dir, listnames):

View file

@ -16,8 +16,8 @@ def main():
raise getopt.GetoptError('not enough arguments', None)
except getopt.GetoptError as msg:
sys.stdout = sys.stderr
print msg
print 'usage: findlinksto pattern directory ...'
print(msg)
print('usage: findlinksto pattern directory ...')
sys.exit(2)
pat, dirs = args[0], args[1:]
prog = re.compile(pat)
@ -29,13 +29,13 @@ def visit(prog, dirname, names):
names[:] = []
return
if os.path.ismount(dirname):
print 'descend into', dirname
print('descend into', dirname)
for name in names:
name = os.path.join(dirname, name)
try:
linkto = os.readlink(name)
if prog.search(linkto) is not None:
print name, '->', linkto
print(name, '->', linkto)
except os.error:
pass

View file

@ -28,8 +28,8 @@ except:
pysource = pysource()
print >>sys.stderr, ("The pysource module is not available; "
"no sophisticated Python source file search will be done.")
print("The pysource module is not available; "
"no sophisticated Python source file search will be done.", file=sys.stderr)
decl_re = re.compile(r"coding[=:]\s*([-\w.]+)")
@ -79,8 +79,8 @@ usage = """Usage: %s [-cd] paths...
try:
opts, args = getopt.getopt(sys.argv[1:], 'cd')
except getopt.error as msg:
print >>sys.stderr, msg
print >>sys.stderr, usage
print(msg, file=sys.stderr)
print(usage, file=sys.stderr)
sys.exit(1)
is_python = pysource.looks_like_python
@ -93,12 +93,12 @@ for o, a in opts:
debug = True
if not args:
print >>sys.stderr, usage
print(usage, file=sys.stderr)
sys.exit(1)
for fullpath in pysource.walk_python_files(args, is_python):
if debug:
print "Testing for coding: %s" % fullpath
print("Testing for coding: %s" % fullpath)
result = needs_declaration(fullpath)
if result:
print fullpath
print(fullpath)

View file

@ -244,7 +244,7 @@ def fixline(line):
subst = Dict[found]
if Program is InsideCommentProgram:
if not Docomments:
print 'Found in comment:', found
print('Found in comment:', found)
i = i + n
continue
if NotInComment.has_key(found):

View file

@ -145,7 +145,7 @@ def main():
return 2
for o, a in opts:
if o == "-h":
print __doc__
print(__doc__)
return
if o == "-m":
global multi_ok
@ -160,7 +160,7 @@ def main():
return 1
files = warnings.keys()
if not files:
print "No classic division warnings read from", args[0]
print("No classic division warnings read from", args[0])
return
files.sort()
exit = None
@ -203,14 +203,14 @@ def readwarnings(warningsfile):
return warnings
def process(filename, list):
print "-"*70
print("-"*70)
assert list # if this fails, readwarnings() is broken
try:
fp = open(filename)
except IOError as msg:
sys.stderr.write("can't open: %s\n" % msg)
return 1
print "Index:", filename
print("Index:", filename)
f = FileContext(fp)
list.sort()
index = 0 # list[:index] has been processed, list[index:] is still to do
@ -248,10 +248,10 @@ def process(filename, list):
lastrow = row
assert rows
if len(rows) == 1:
print "*** More than one / operator in line", rows[0]
print("*** More than one / operator in line", rows[0])
else:
print "*** More than one / operator per statement",
print "in lines %d-%d" % (rows[0], rows[-1])
print("*** More than one / operator per statement", end=' ')
print("in lines %d-%d" % (rows[0], rows[-1]))
intlong = []
floatcomplex = []
bad = []
@ -269,24 +269,24 @@ def process(filename, list):
lastrow = row
line = chop(line)
if line[col:col+1] != "/":
print "*** Can't find the / operator in line %d:" % row
print "*", line
print("*** Can't find the / operator in line %d:" % row)
print("*", line)
continue
if bad:
print "*** Bad warning for line %d:" % row, bad
print "*", line
print("*** Bad warning for line %d:" % row, bad)
print("*", line)
elif intlong and not floatcomplex:
print "%dc%d" % (row, row)
print "<", line
print "---"
print ">", line[:col] + "/" + line[col:]
print("%dc%d" % (row, row))
print("<", line)
print("---")
print(">", line[:col] + "/" + line[col:])
elif floatcomplex and not intlong:
print "True division / operator at line %d:" % row
print "=", line
print("True division / operator at line %d:" % row)
print("=", line)
elif intlong and floatcomplex:
print "*** Ambiguous / operator (%s, %s) at line %d:" % (
"|".join(intlong), "|".join(floatcomplex), row)
print "?", line
print("*** Ambiguous / operator (%s, %s) at line %d:" % (
"|".join(intlong), "|".join(floatcomplex), row))
print("?", line)
fp.close()
def reportphantomwarnings(warnings, f):
@ -301,15 +301,15 @@ def reportphantomwarnings(warnings, f):
for block in blocks:
row = block[0]
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="*")
def report(slashes, message):
lastrow = None
for (row, col), line in slashes:
if row != lastrow:
print "*** %s on line %d:" % (message, row)
print "*", chop(line)
print("*** %s on line %d:" % (message, row))
print("*", chop(line))
lastrow = row
class FileContext:
@ -354,7 +354,7 @@ class FileContext:
line = self[first]
except KeyError:
line = "<missing line>"
print mark, chop(line)
print(mark, chop(line))
def scanline(g):
slashes = []

View file

@ -32,18 +32,18 @@ def process(filename):
magic = magic + c.upper()
else: magic = magic + '_'
sys.stdout = f
print '#ifndef', magic
print '#define', magic
print '#ifdef __cplusplus'
print 'extern "C" {'
print '#endif'
print
print('#ifndef', magic)
print('#define', magic)
print('#ifdef __cplusplus')
print('extern "C" {')
print('#endif')
print()
f.write(data)
print
print '#ifdef __cplusplus'
print '}'
print '#endif'
print '#endif /*', '!'+magic, '*/'
print()
print('#ifdef __cplusplus')
print('}')
print('#endif')
print('#endif /*', '!'+magic, '*/')
if __name__ == '__main__':
main()

View file

@ -50,9 +50,9 @@ VERBOSE = 0
def usage(code, msg=''):
print __doc__ % globals()
print(__doc__ % globals())
if msg:
print msg
print(msg)
sys.exit(code)
@ -92,10 +92,10 @@ def process(file):
i = data.find(OLD_NOTICE)
if i < 0:
if VERBOSE:
print 'no change:', file
print('no change:', file)
return
elif DRYRUN or VERBOSE:
print ' change:', file
print(' change:', file)
if DRYRUN:
# Don't actually change the file
return

View file

@ -12,18 +12,18 @@ def main():
try:
f = open(filename, 'r')
except IOError as msg:
print filename, ': can\'t open :', msg
print(filename, ': can\'t open :', msg)
continue
line = f.readline()
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()
continue
rest = f.read()
f.close()
line = re.sub('/usr/local/bin/python',
'/usr/bin/env python', line)
print filename, ':', repr(line)
print(filename, ':', repr(line))
f = open(filename, "w")
f.write(line)
f.write(rest)

View file

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

View file

@ -5,7 +5,7 @@ import sys, webbrowser
def main():
args = sys.argv[1:]
if not args:
print "Usage: %s querystring" % sys.argv[0]
print("Usage: %s querystring" % sys.argv[0])
return
list = []
for arg in args:

View file

@ -7,15 +7,15 @@ import sys, re, os
def main():
for filename in sys.argv[1:]:
if os.path.isdir(filename):
print filename, "Directory!"
print(filename, "Directory!")
continue
data = open(filename, "rb").read()
if '\0' in data:
print filename, "Binary!"
print(filename, "Binary!")
continue
newdata = re.sub("\r?\n", "\r\n", data)
if newdata != data:
print filename
print(filename)
f = open(filename, "wb")
f.write(newdata)
f.close()

View file

@ -18,7 +18,7 @@ debug = 0
def main():
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
oldtree, newtree = sys.argv[1], sys.argv[2]
if len(sys.argv) > 3:
@ -28,46 +28,46 @@ def main():
link = LINK
link_may_fail = 0
if not os.path.isdir(oldtree):
print oldtree + ': not a directory'
print(oldtree + ': not a directory')
return 1
try:
os.mkdir(newtree, 0o777)
except os.error as msg:
print newtree + ': cannot mkdir:', msg
print(newtree + ': cannot mkdir:', msg)
return 1
linkname = os.path.join(newtree, link)
try:
os.symlink(os.path.join(os.pardir, oldtree), linkname)
except os.error as msg:
if not link_may_fail:
print linkname + ': cannot symlink:', msg
print(linkname + ': cannot symlink:', msg)
return 1
else:
print linkname + ': warning: cannot symlink:', msg
print(linkname + ': warning: cannot symlink:', msg)
linknames(oldtree, newtree, link)
return 0
def linknames(old, new, link):
if debug: print 'linknames', (old, new, link)
if debug: print('linknames', (old, new, link))
try:
names = os.listdir(old)
except os.error as msg:
print old + ': warning: cannot listdir:', msg
print(old + ': warning: cannot listdir:', msg)
return
for name in names:
if name not in (os.curdir, os.pardir):
oldname = os.path.join(old, name)
linkname = os.path.join(link, 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 \
not os.path.islink(oldname):
try:
os.mkdir(newname, 0o777)
ok = 1
except:
print newname + \
': warning: cannot mkdir:', msg
print(newname + \
': warning: cannot mkdir:', msg)
ok = 0
if ok:
linkname = os.path.join(os.pardir,

View file

@ -12,16 +12,16 @@ def lll(dirname):
if name not in (os.curdir, os.pardir):
full = os.path.join(dirname, name)
if os.path.islink(full):
print name, '->', os.readlink(full)
print(name, '->', os.readlink(full))
def main():
args = sys.argv[1:]
if not args: args = [os.curdir]
first = 1
for arg in args:
if len(args) > 1:
if not first: print
if not first: print()
first = 0
print arg + ':'
print(arg + ':')
lll(arg)
if __name__ == '__main__':

View file

@ -53,7 +53,7 @@ def main():
elif o == '-b':
branch = a
elif o == '-h':
print __doc__
print(__doc__)
sys.exit(0)
database = []
while 1:
@ -169,9 +169,9 @@ def format_output(database):
for (date, working_file, rev, author, text) in database:
if text != prevtext:
if prev:
print sep2,
print(sep2, end=' ')
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)
prev = []
prev.append((date, working_file, rev, author))

View file

@ -171,11 +171,11 @@ def parsedir(dir, modify):
fp = open(fn)
m = ErrorMessage(fp)
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():
fp.close()
print 'warning only'
print('warning only')
nwarn = nwarn + 1
if modify:
os.rename(fn, ','+fn)
@ -185,11 +185,11 @@ def parsedir(dir, modify):
try:
errors = m.get_errors()
except Unparseable:
print '** Not parseable'
print('** Not parseable')
nbad = nbad + 1
fp.close()
continue
print len(errors), 'errors'
print(len(errors), 'errors')
# Remember them
for e in errors:
@ -211,16 +211,16 @@ def parsedir(dir, modify):
os.rename(fn, ','+fn)
## os.unlink(fn)
print '--------------'
print nok, 'files parsed,',nwarn,'files warning-only,',
print nbad,'files unparseable'
print '--------------'
print('--------------')
print(nok, 'files parsed,',nwarn,'files warning-only,', end=' ')
print(nbad,'files unparseable')
print('--------------')
list = []
for e in errordict.keys():
list.append((errordict[e], errorfirst[e], errorlast[e], e))
list.sort()
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():
modify = 0

View file

@ -48,12 +48,12 @@ def main():
if progname == '-c': progname = 'mkreal'
args = sys.argv[1:]
if not args:
print 'usage:', progname, 'path ...'
print('usage:', progname, 'path ...')
sys.exit(2)
status = 0
for name in args:
if not os.path.islink(name):
print progname+':', name+':', 'not a symlink'
print(progname+':', name+':', 'not a symlink')
status = 1
else:
if os.path.isdir(name):

View file

@ -74,7 +74,7 @@ def fcompare(f1name, f2name):
a = f1.readlines(); f1.close()
b = f2.readlines(); f2.close()
for line in difflib.ndiff(a, b):
print line,
print(line, end=' ')
return 1
@ -109,8 +109,8 @@ def main(args):
return fail("need 2 filename args")
f1name, f2name = args
if noisy:
print '-:', f1name
print '+:', f2name
print('-:', f1name)
print('+:', f2name)
return fcompare(f1name, f2name)
# 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(undef2file, name, fn)
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
# defined.
@ -89,7 +89,7 @@ def printcallee():
flist = file2undef.keys()
flist.sort()
for filename in flist:
print filename + ':'
print(filename + ':')
elist = file2undef[filename]
elist.sort()
for ext in elist:
@ -98,9 +98,9 @@ def printcallee():
else:
tabs = '\t\t'
if not def2file.has_key(ext):
print '\t' + ext + tabs + ' *undefined'
print('\t' + ext + tabs + ' *undefined')
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.
#
@ -114,14 +114,14 @@ def printcaller():
callers = callers + undef2file[label]
if callers:
callers.sort()
print filename + ':'
print(filename + ':')
lastfn = ''
for fn in callers:
if fn <> lastfn:
print '\t' + fn
print('\t' + fn)
lastfn = fn
else:
print filename + ': unused'
print(filename + ': unused')
# Print undefined names and where they are used.
#
@ -134,11 +134,11 @@ def printundef():
elist = undefs.keys()
elist.sort()
for ext in elist:
print ext + ':'
print(ext + ':')
flist = undefs[ext]
flist.sort()
for filename in flist:
print '\t' + filename
print('\t' + filename)
# Print warning messages about names defined in more than one file.
#
@ -149,8 +149,8 @@ def warndups():
names.sort()
for name in names:
if len(def2file[name]) > 1:
print 'warning:', name, 'multiply defined:',
print flat(def2file[name])
print('warning:', name, 'multiply defined:', end=' ')
print(flat(def2file[name]))
sys.stdout = savestdout
# Main program
@ -160,14 +160,14 @@ def main():
optlist, args = getopt.getopt(sys.argv[1:], 'cdu')
except getopt.error:
sys.stdout = sys.stderr
print 'Usage:', os.path.basename(sys.argv[0]),
print '[-cdu] [file] ...'
print '-c: print callers per objectfile'
print '-d: print callees per objectfile'
print '-u: print usage of undefined symbols'
print 'If none of -cdu is specified, all are assumed.'
print 'Use "nm -o" to generate the input (on IRIX: "nm -Bo"),'
print 'e.g.: nm -o /lib/libc.a | objgraph'
print('Usage:', os.path.basename(sys.argv[0]), end=' ')
print('[-cdu] [file] ...')
print('-c: print callers per objectfile')
print('-d: print callees per objectfile')
print('-u: print usage of undefined symbols')
print('If none of -cdu is specified, all are assumed.')
print('Use "nm -o" to generate the input (on IRIX: "nm -Bo"),')
print('e.g.: nm -o /lib/libc.a | objgraph')
return 1
optu = optc = optd = 0
for opt, void in optlist:
@ -192,15 +192,15 @@ def main():
more = (optu + optc + optd > 1)
if optd:
if more:
print '---------------All callees------------------'
print('---------------All callees------------------')
printcallee()
if optu:
if more:
print '---------------Undefined callees------------'
print('---------------Undefined callees------------')
printundef()
if optc:
if more:
print '---------------All Callers------------------'
print('---------------All Callers------------------')
printcaller()
return 0

View file

@ -30,25 +30,25 @@ import os
def main():
args = sys.argv[1:]
if not args:
print 'usage: pdeps file.py file.py ...'
print('usage: pdeps file.py file.py ...')
return 2
#
table = {}
for arg in args:
process(arg, table)
#
print '--- Uses ---'
print('--- Uses ---')
printresults(table)
#
print '--- Used By ---'
print('--- Used By ---')
inv = inverse(table)
printresults(inv)
#
print '--- Closure of Uses ---'
print('--- Closure of Uses ---')
reach = closure(table)
printresults(reach)
#
print '--- Closure of Used By ---'
print('--- Closure of Used By ---')
invreach = inverse(reach)
printresults(invreach)
#
@ -151,12 +151,12 @@ def printresults(table):
for mod in modules:
list = table[mod]
list.sort()
print mod.ljust(maxlen), ':',
print(mod.ljust(maxlen), ':', end=' ')
if mod in list:
print '(*)',
print('(*)', end=' ')
for ref in list:
print ref,
print
print(ref, end=' ')
print()
# Call main and honor exit status

View file

@ -27,7 +27,7 @@ binary_re = re.compile('[\x00-\x08\x0E-\x1F\x7F]')
debug = False
def print_debug(msg):
if debug: print msg
if debug: print(msg)
def _open(fullpath):
@ -124,7 +124,7 @@ def walk_python_files(paths, is_python=looks_like_python, exclude_dirs=None):
if __name__ == "__main__":
# Two simple examples/tests
for fullpath in walk_python_files(['.']):
print fullpath
print "----------"
print(fullpath)
print("----------")
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()
for line in lines:
if prog.search(line):
print line
print(line)
def usage(msg, code=2):
sys.stdout = sys.stderr
print msg
print __doc__
print(msg)
print(__doc__)
sys.exit(code)
if __name__ == '__main__':

View file

@ -17,7 +17,7 @@ def main():
keys = suffixes.keys()
keys.sort()
for suff in keys:
print repr(suff), len(suffixes[suff])
print(repr(suff), len(suffixes[suff]))
def getsuffix(filename):
suff = ''

View file

@ -65,10 +65,10 @@ def matchclose(c_lineno, c_symbol, openers, pairmap):
try:
o_lineno, o_symbol = openers.pop()
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
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
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
for begend, name, punct in delimiters.findall(line):
if '-v' in opts:
print lineno, '|', begend, name, punct,
print(lineno, '|', begend, name, punct, end=' ')
if begend == 'begin' and '-d' not in opts:
openers.append((lineno, name))
elif punct in openpunct:
@ -130,7 +130,7 @@ def checkit(source, opts, morecmds=[]):
elif punct in pairmap:
matchclose(lineno, punct, openers, pairmap)
if '-v' in opts:
print ' --> ', openers
print(' --> ', openers)
# Balance opening and closing braces
for open, close in braces.findall(line):
@ -140,7 +140,7 @@ def checkit(source, opts, morecmds=[]):
try:
bracestack.pop()
except IndexError:
print r'Warning, unmatched } on line %s.' % (lineno,)
print(r'Warning, unmatched } on line %s.' % (lineno,))
# Optionally, skip LaTeX specific checks
if '-d' in opts:
@ -151,11 +151,11 @@ def checkit(source, opts, morecmds=[]):
if '822' in line or '.html' in line:
continue # Ignore false positives for urls and for /rfc822
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
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
nc = line.find(r'\newcommand')
@ -165,7 +165,7 @@ def checkit(source, opts, morecmds=[]):
validcmds.add(line[start+1:end])
for cmd in texcmd.findall(line):
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)
m = tablestart.search(line)
@ -174,23 +174,23 @@ def checkit(source, opts, morecmds=[]):
tablestartline = lineno
m = tableline.search(line)
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):
tablelevel = ''
# Style guide warnings
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):
print r'Doubled word warning. "%s" on line %d' % (dw, lineno)
print(r'Doubled word warning. "%s" on line %d' % (dw, lineno))
lastline = lineno
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:
print "Unmatched { on line %d" % (lineno,)
print 'Done checking %d lines.' % (lastline,)
print("Unmatched { on line %d" % (lineno,))
print('Done checking %d lines.' % (lastline,))
return 0
def main(args=None):
@ -199,11 +199,11 @@ def main(args=None):
optitems, arglist = getopt.getopt(args, "k:mdhs:v")
opts = dict(optitems)
if '-h' in opts or args==[]:
print __doc__
print(__doc__)
return 0
if len(arglist) < 1:
print 'Please specify a file to be checked'
print('Please specify a file to be checked')
return 1
for i, filespec in enumerate(arglist):
@ -214,12 +214,12 @@ def main(args=None):
err = []
for filename in arglist:
print '=' * 30
print "Checking", filename
print('=' * 30)
print("Checking", filename)
try:
f = open(filename)
except IOError:
print 'Cannot open file %s.' % arglist[0]
print('Cannot open file %s.' % arglist[0])
return 2
try:

View file

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

View file

@ -54,35 +54,35 @@ def main():
try:
[slave, master] = args
except ValueError:
print "usage: python", sys.argv[0] or "treesync.py",
print "[-n] [-y] [-m y|n|a] [-s y|n|a] [-d y|n|a] [-f n|y|a]",
print "slavedir masterdir"
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]", end=' ')
print("slavedir masterdir")
return
process(slave, master)
def process(slave, master):
cvsdir = os.path.join(master, "CVS")
if not os.path.isdir(cvsdir):
print "skipping master subdirectory", master
print "-- not under CVS"
print("skipping master subdirectory", master)
print("-- not under CVS")
return
print "-"*40
print "slave ", slave
print "master", master
print("-"*40)
print("slave ", slave)
print("master", master)
if not os.path.isdir(slave):
if not okay("create slave directory %s?" % slave,
answer=create_directories):
print "skipping master subdirectory", master
print "-- no corresponding slave", slave
print("skipping master subdirectory", master)
print("-- no corresponding slave", slave)
return
print "creating slave directory", slave
print("creating slave directory", slave)
try:
os.mkdir(slave)
except os.error as msg:
print "can't make slave directory", slave, ":", msg
print("can't make slave directory", slave, ":", msg)
return
else:
print "made slave directory", slave
print("made slave directory", slave)
cvsdir = None
subdirs = []
names = os.listdir(master)
@ -117,13 +117,13 @@ def compare(slave, master):
mf = None
if not sf:
if not mf:
print "Neither master nor slave exists", master
print("Neither master nor slave exists", master)
return
print "Creating missing slave", slave
print("Creating missing slave", slave)
copy(master, slave, answer=create_files)
return
if not mf:
print "Not updating missing master", master
print("Not updating missing master", master)
return
if sf and mf:
if identical(sf, mf):
@ -134,22 +134,22 @@ def compare(slave, master):
# Master is newer -- copy master to slave
sf.close()
mf.close()
print "Master ", master
print "is newer than slave", slave
print("Master ", master)
print("is newer than slave", slave)
copy(master, slave, answer=write_slave)
return
# 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
mf.seek(0)
fun = funnychars(mf)
mf.close()
sf.close()
if fun:
print "***UPDATING MASTER (BINARY COPY)***"
print("***UPDATING MASTER (BINARY COPY)***")
copy(slave, master, "rb", answer=write_master)
else:
print "***UPDATING MASTER***"
print("***UPDATING MASTER***")
copy(slave, master, "r", answer=write_master)
BUFSIZE = 16*1024
@ -174,8 +174,8 @@ def funnychars(f):
return 0
def copy(src, dst, rmode="rb", wmode="wb", answer='ask'):
print "copying", src
print " to", dst
print("copying", src)
print(" to", dst)
if not okay("okay to copy? ", answer):
return
f = open(src, rmode)
@ -203,7 +203,7 @@ def okay(prompt, answer='ask'):
return 1
if answer[:1] == 'n':
return 0
print "Yes or No please -- try again:"
print("Yes or No please -- try again:")
return okay(prompt)
if __name__ == '__main__':

View file

@ -13,8 +13,8 @@ def main():
if not args:
raise getopt.error, "At least one file argument required"
except getopt.error as msg:
print msg
print "usage:", sys.argv[0], "[-t tabwidth] file ..."
print(msg)
print("usage:", sys.argv[0], "[-t tabwidth] file ...")
return
for optname, optvalue in opts:
if optname == '-t':
@ -29,7 +29,7 @@ def process(filename, tabsize):
text = f.read()
f.close()
except IOError as msg:
print "%r: I/O error: %s" % (filename, msg)
print("%r: I/O error: %s" % (filename, msg))
return
newtext = text.expandtabs(tabsize)
if newtext == text:
@ -46,7 +46,7 @@ def process(filename, tabsize):
f = open(filename, "w")
f.write(newtext)
f.close()
print filename
print(filename)
if __name__ == '__main__':
main()

View file

@ -37,7 +37,7 @@ def main():
mode = S_IMODE(st[ST_MODE])
if mode & 0o111:
if not ident:
print filename
print(filename)
ident = st[:3]
else:
if st[:3] == ident:

View file

@ -18,14 +18,14 @@ def getargs():
args = sys.argv[1:]
if args:
return args
print 'No arguments, checking almost *, in "ls -t" order'
print('No arguments, checking almost *, in "ls -t" order')
list = []
for file in os.listdir(os.curdir):
if not skipfile(file):
list.append((getmtime(file), file))
list.sort()
if not list:
print 'Nothing to do -- exit 1'
print('Nothing to do -- exit 1')
sys.exit(1)
list.sort()
list.reverse()
@ -89,7 +89,7 @@ def badsuffix(file):
def go(args):
for file in args:
print file + ':'
print(file + ':')
if differing(file):
showdiffs(file)
if askyesno('Check in ' + file + ' ? '):
@ -119,4 +119,4 @@ if __name__ == '__main__':
setup()
go(getargs())
except KeyboardInterrupt:
print '[Intr]'
print('[Intr]')