Commit 99002ffc authored by Walter Dörwald's avatar Walter Dörwald

Apply diff2.txt from SF patch http://www.python.org/sf/572113

(with one small bugfix in bgen/bgen/scantools.py)

This replaces string module functions with string methods
for the stuff in the Tools directory. Several uses of
string.letters etc. are still remaining.
parent 51d3c5cb
...@@ -47,7 +47,6 @@ Other options are: ...@@ -47,7 +47,6 @@ Other options are:
import sys import sys
import os import os
import string
import errno import errno
import sunaudiodev import sunaudiodev
from SUNAUDIODEV import * from SUNAUDIODEV import *
...@@ -372,9 +371,9 @@ class Helpwin: ...@@ -372,9 +371,9 @@ class Helpwin:
fp = open(readmefile) fp = open(readmefile)
contents = fp.read() contents = fp.read()
# wax the last page, it contains Emacs cruft # wax the last page, it contains Emacs cruft
i = string.rfind(contents, '\f') i = contents.rfind('\f')
if i > 0: if i > 0:
contents = string.rstrip(contents[:i]) contents = contents[:i].rstrip()
finally: finally:
if fp: if fp:
fp.close() fp.close()
......
...@@ -131,7 +131,6 @@ class FunctionGenerator(BaseFunctionGenerator): ...@@ -131,7 +131,6 @@ class FunctionGenerator(BaseFunctionGenerator):
self.argumentList.append(arg) self.argumentList.append(arg)
def docstring(self): def docstring(self):
import string
input = [] input = []
output = [] output = []
for arg in self.argumentList: for arg in self.argumentList:
...@@ -156,11 +155,11 @@ class FunctionGenerator(BaseFunctionGenerator): ...@@ -156,11 +155,11 @@ class FunctionGenerator(BaseFunctionGenerator):
if not input: if not input:
instr = "()" instr = "()"
else: else:
instr = "(%s)" % string.joinfields(input, ", ") instr = "(%s)" % ", ".join(input)
if not output or output == ["void"]: if not output or output == ["void"]:
outstr = "None" outstr = "None"
else: else:
outstr = "(%s)" % string.joinfields(output, ", ") outstr = "(%s)" % ", ".join(output)
return instr + " -> " + outstr return instr + " -> " + outstr
def functionbody(self): def functionbody(self):
......
...@@ -69,12 +69,11 @@ def VaOutput(format, args): ...@@ -69,12 +69,11 @@ def VaOutput(format, args):
text = format % args text = format % args
if _Level > 0: if _Level > 0:
indent = '\t' * _Level indent = '\t' * _Level
import string lines = text.split('\n')
lines = string.splitfields(text, '\n')
for i in range(len(lines)): for i in range(len(lines)):
if lines[i] and lines[i][0] != '#': if lines[i] and lines[i][0] != '#':
lines[i] = indent + lines[i] lines[i] = indent + lines[i]
text = string.joinfields(lines, '\n') text = '\n'.join(lines)
_File.write(text + '\n') _File.write(text + '\n')
def IndentLevel(by = 1): def IndentLevel(by = 1):
...@@ -168,13 +167,12 @@ def Out(text): ...@@ -168,13 +167,12 @@ def Out(text):
""" """
# (Don't you love using triple quotes *inside* triple quotes? :-) # (Don't you love using triple quotes *inside* triple quotes? :-)
import string lines = text.split('\n')
lines = string.splitfields(text, '\n')
indent = "" indent = ""
for line in lines: for line in lines:
if string.strip(line): if line.strip():
for c in line: for c in line:
if c not in string.whitespace: if not c.isspace():
break break
indent = indent + c indent = indent + c
break break
......
...@@ -15,7 +15,6 @@ although most Mac specific details are contained in header-specific subclasses. ...@@ -15,7 +15,6 @@ although most Mac specific details are contained in header-specific subclasses.
""" """
import re import re
import string
import sys import sys
import os import os
import fnmatch import fnmatch
...@@ -67,8 +66,8 @@ class Scanner: ...@@ -67,8 +66,8 @@ class Scanner:
for type in types: for type in types:
modes = self.usedtypes[type].keys() modes = self.usedtypes[type].keys()
modes.sort() modes.sort()
self.report("%s %s", type, string.join(modes)) self.report("%s %s", type, " ".join(modes))
def gentypetest(self, file): def gentypetest(self, file):
fp = open(file, "w") fp = open(file, "w")
fp.write("types=[\n") fp.write("types=[\n")
...@@ -163,9 +162,9 @@ if missing: raise "Missing Types" ...@@ -163,9 +162,9 @@ if missing: raise "Missing Types"
while line[-2:] == '\\\n': while line[-2:] == '\\\n':
line = line[:-2] + ' ' + f.readline() line = line[:-2] + ' ' + f.readline()
lineno = lineno + 1 lineno = lineno + 1
i = string.find(line, '#') i = line.find('#')
if i >= 0: line = line[:i] if i >= 0: line = line[:i]
words = map(string.strip, string.splitfields(line, ':')) 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,
...@@ -179,8 +178,8 @@ if missing: raise "Missing Types" ...@@ -179,8 +178,8 @@ if missing: raise "Missing Types"
print "Empty pattern" print "Empty pattern"
print `line` print `line`
continue continue
patparts = map(string.strip, string.splitfields(pat, ',')) patparts = [s.strip() for s in pat.split(',')]
repparts = map(string.strip, string.splitfields(rep, ',')) repparts = [s.strip() for s in rep.split(',')]
patterns = [] patterns = []
for p in patparts: for p in patparts:
if not p: if not p:
...@@ -188,7 +187,7 @@ if missing: raise "Missing Types" ...@@ -188,7 +187,7 @@ if missing: raise "Missing Types"
print "Empty pattern part" print "Empty pattern part"
print `line` print `line`
continue continue
pattern = string.split(p) pattern = p.split()
if len(pattern) > 3: if len(pattern) > 3:
print "Line", startlineno, print "Line", startlineno,
print "Pattern part has > 3 words" print "Pattern part has > 3 words"
...@@ -205,7 +204,7 @@ if missing: raise "Missing Types" ...@@ -205,7 +204,7 @@ if missing: raise "Missing Types"
print "Empty replacement part" print "Empty replacement part"
print `line` print `line`
continue continue
replacement = string.split(p) replacement = p.split()
if len(replacement) > 3: if len(replacement) > 3:
print "Line", startlineno, print "Line", startlineno,
print "Pattern part has > 3 words" print "Pattern part has > 3 words"
...@@ -502,10 +501,10 @@ if missing: raise "Missing Types" ...@@ -502,10 +501,10 @@ if missing: raise "Missing Types"
self.generate(type, name, arglist) self.generate(type, name, arglist)
def extractarglist(self, args): def extractarglist(self, args):
args = string.strip(args) args = args.strip()
if not args or args == "void": if not args or args == "void":
return [] return []
parts = map(string.strip, string.splitfields(args, ",")) parts = [s.strip() for s in args.split(",")]
arglist = [] arglist = []
for part in parts: for part in parts:
arg = self.extractarg(part) arg = self.extractarg(part)
...@@ -524,7 +523,7 @@ if missing: raise "Missing Types" ...@@ -524,7 +523,7 @@ if missing: raise "Missing Types"
# array matches an optional [] after the argument name # array matches an optional [] after the argument name
type = type + " ptr " type = type + " ptr "
type = re.sub("\*", " ptr ", type) type = re.sub("\*", " ptr ", type)
type = string.strip(type) type = type.strip()
type = re.sub("[ \t]+", "_", type) type = re.sub("[ \t]+", "_", type)
return self.modifyarg(type, name, mode) return self.modifyarg(type, name, mode)
...@@ -581,7 +580,7 @@ if missing: raise "Missing Types" ...@@ -581,7 +580,7 @@ if missing: raise "Missing Types"
if item[i] == '*': if item[i] == '*':
newitem[i] = old[k][i] newitem[i] = old[k][i]
elif item[i][:1] == '$': elif item[i][:1] == '$':
index = string.atoi(item[i][1:]) - 1 index = int(item[i][1:]) - 1
newitem[i] = old[index][i] newitem[i] = old[index][i]
new.append(tuple(newitem)) new.append(tuple(newitem))
##self.report("old: %s", `old`) ##self.report("old: %s", `old`)
......
...@@ -11,7 +11,7 @@ The actual script to place in cgi-bin is faqw.py. ...@@ -11,7 +11,7 @@ The actual script to place in cgi-bin is faqw.py.
""" """
import sys, string, time, os, stat, re, cgi, faqconf import sys, time, os, stat, re, cgi, faqconf
from faqconf import * # This imports all uppercase names from faqconf import * # This imports all uppercase names
now = time.time() now = time.time()
...@@ -33,14 +33,14 @@ class NoSuchFile(FileError): ...@@ -33,14 +33,14 @@ class NoSuchFile(FileError):
self.why = why self.why = why
def escape(s): def escape(s):
s = string.replace(s, '&', '&amp;') s = s.replace('&', '&amp;')
s = string.replace(s, '<', '&lt;') s = s.replace('<', '&lt;')
s = string.replace(s, '>', '&gt;') s = s.replace('>', '&gt;')
return s return s
def escapeq(s): def escapeq(s):
s = escape(s) s = escape(s)
s = string.replace(s, '"', '&quot;') s = s.replace('"', '&quot;')
return s return s
def _interpolate(format, args, kw): def _interpolate(format, args, kw):
...@@ -95,7 +95,7 @@ def translate(text, pre=0): ...@@ -95,7 +95,7 @@ def translate(text, pre=0):
list.append(repl) list.append(repl)
j = len(text) j = len(text)
list.append(escape(text[i:j])) list.append(escape(text[i:j]))
return string.join(list, '') return ''.join(list)
def emphasize(line): def emphasize(line):
return re.sub(r'\*([a-zA-Z]+)\*', r'<I>\1</I>', line) return re.sub(r'\*([a-zA-Z]+)\*', r'<I>\1</I>', line)
...@@ -109,7 +109,7 @@ def revparse(rev): ...@@ -109,7 +109,7 @@ def revparse(rev):
m = revparse_prog.match(rev) m = revparse_prog.match(rev)
if not m: if not m:
return None return None
[major, minor] = map(string.atoi, m.group(1, 2)) [major, minor] = map(int, m.group(1, 2))
return major, minor return major, minor
logon = 0 logon = 0
...@@ -123,10 +123,10 @@ def load_cookies(): ...@@ -123,10 +123,10 @@ def load_cookies():
if not os.environ.has_key('HTTP_COOKIE'): if not os.environ.has_key('HTTP_COOKIE'):
return {} return {}
raw = os.environ['HTTP_COOKIE'] raw = os.environ['HTTP_COOKIE']
words = map(string.strip, string.split(raw, ';')) words = [s.strip() for s in raw.split(';')]
cookies = {} cookies = {}
for word in words: for word in words:
i = string.find(word, '=') i = word.find('=')
if i >= 0: if i >= 0:
key, value = word[:i], word[i+1:] key, value = word[:i], word[i+1:]
cookies[key] = value cookies[key] = value
...@@ -140,10 +140,10 @@ def load_my_cookie(): ...@@ -140,10 +140,10 @@ def load_my_cookie():
return {} return {}
import urllib import urllib
value = urllib.unquote(value) value = urllib.unquote(value)
words = string.split(value, '/') words = value.split('/')
while len(words) < 3: while len(words) < 3:
words.append('') words.append('')
author = string.join(words[:-2], '/') author = '/'.join(words[:-2])
email = words[-2] email = words[-2]
password = words[-1] password = words[-1]
return {'author': author, return {'author': author,
...@@ -194,7 +194,7 @@ class UserInput: ...@@ -194,7 +194,7 @@ class UserInput:
except (TypeError, KeyError): except (TypeError, KeyError):
value = '' value = ''
else: else:
value = string.strip(value) value = value.strip()
setattr(self, name, value) setattr(self, name, value)
return value return value
...@@ -209,7 +209,7 @@ class FaqEntry: ...@@ -209,7 +209,7 @@ class FaqEntry:
if fp: if fp:
import rfc822 import rfc822
self.__headers = rfc822.Message(fp) self.__headers = rfc822.Message(fp)
self.body = string.strip(fp.read()) self.body = fp.read().strip()
else: else:
self.__headers = {'title': "%d.%d. " % sec_num} self.__headers = {'title': "%d.%d. " % sec_num}
self.body = '' self.body = ''
...@@ -217,7 +217,7 @@ class FaqEntry: ...@@ -217,7 +217,7 @@ class FaqEntry:
def __getattr__(self, name): def __getattr__(self, name):
if name[0] == '_': if name[0] == '_':
raise AttributeError raise AttributeError
key = string.join(string.split(name, '_'), '-') key = '-'.join(name.split('_'))
try: try:
value = self.__headers[key] value = self.__headers[key]
except KeyError: except KeyError:
...@@ -237,7 +237,7 @@ class FaqEntry: ...@@ -237,7 +237,7 @@ class FaqEntry:
if not line: if not line:
break break
if line[:5] == 'head:': if line[:5] == 'head:':
version = string.strip(line[5:]) version = line[5:].strip()
p.close() p.close()
self.version = version self.version = version
...@@ -262,10 +262,10 @@ class FaqEntry: ...@@ -262,10 +262,10 @@ class FaqEntry:
emit(ENTRY_HEADER2, self) emit(ENTRY_HEADER2, self)
pre = 0 pre = 0
raw = 0 raw = 0
for line in string.split(self.body, '\n'): for line in self.body.split('\n'):
# Allow the user to insert raw html into a FAQ answer # Allow the user to insert raw html into a FAQ answer
# (Skip Montanaro, with changes by Guido) # (Skip Montanaro, with changes by Guido)
tag = string.lower(string.rstrip(line)) tag = line.rstrip().lower()
if tag == '<html>': if tag == '<html>':
raw = 1 raw = 1
continue continue
...@@ -275,14 +275,14 @@ class FaqEntry: ...@@ -275,14 +275,14 @@ class FaqEntry:
if raw: if raw:
print line print line
continue continue
if not string.strip(line): 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 line[0] not in string.whitespace: if not line[0].isspace():
if pre: if pre:
print '</PRE>' print '</PRE>'
pre = 0 pre = 0
...@@ -335,7 +335,7 @@ class FaqDir: ...@@ -335,7 +335,7 @@ class FaqDir:
if not m: if not m:
return None return None
sec, num = m.group(1, 2) sec, num = m.group(1, 2)
return string.atoi(sec), string.atoi(num) return int(sec), int(num)
def list(self): def list(self):
# XXX Caller shouldn't modify result # XXX Caller shouldn't modify result
...@@ -432,7 +432,7 @@ class FaqWizard: ...@@ -432,7 +432,7 @@ class FaqWizard:
return return
words = map(lambda w: r'\b%s\b' % w, words) words = map(lambda w: r'\b%s\b' % w, words)
if self.ui.querytype[:3] == 'any': if self.ui.querytype[:3] == 'any':
queries = [string.join(words, '|')] queries = ['|'.join(words)]
else: else:
# Each of the individual queries must match # Each of the individual queries must match
queries = words queries = words
...@@ -551,7 +551,7 @@ class FaqWizard: ...@@ -551,7 +551,7 @@ class FaqWizard:
if not self.ui.days: if not self.ui.days:
days = 1 days = 1
else: else:
days = string.atof(self.ui.days) days = float(self.ui.days)
try: try:
cutoff = now - days * 24 * 3600 cutoff = now - days * 24 * 3600
except OverflowError: except OverflowError:
...@@ -623,7 +623,7 @@ class FaqWizard: ...@@ -623,7 +623,7 @@ class FaqWizard:
output = os.popen(command).read() output = os.popen(command).read()
sys.stdout.write('<PRE>') sys.stdout.write('<PRE>')
athead = 0 athead = 0
lines = string.split(output, '\n') lines = output.split('\n')
while lines and not lines[-1]: while lines and not lines[-1]:
del lines[-1] del lines[-1]
if lines: if lines:
...@@ -634,7 +634,7 @@ class FaqWizard: ...@@ -634,7 +634,7 @@ class FaqWizard:
headrev = None headrev = None
for line in lines: for line in lines:
if entry and athead and line[:9] == 'revision ': if entry and athead and line[:9] == 'revision ':
rev = string.strip(line[9:]) rev = line[9:].split()
mami = revparse(rev) mami = revparse(rev)
if not mami: if not mami:
print line print line
...@@ -690,7 +690,7 @@ class FaqWizard: ...@@ -690,7 +690,7 @@ class FaqWizard:
print '</PRE>' print '</PRE>'
def do_new(self): def do_new(self):
entry = self.dir.new(section=string.atoi(self.ui.section)) entry = self.dir.new(section=int(self.ui.section))
entry.version = '*new*' entry.version = '*new*'
self.prologue(T_EDIT) self.prologue(T_EDIT)
emit(EDITHEAD) emit(EDITHEAD)
...@@ -723,7 +723,7 @@ class FaqWizard: ...@@ -723,7 +723,7 @@ class FaqWizard:
entry = self.dir.open(self.ui.file) entry = self.dir.open(self.ui.file)
entry.load_version() entry.load_version()
# Check that the FAQ entry number didn't change # Check that the FAQ entry number didn't change
if string.split(self.ui.title)[:1] != string.split(entry.title)[:1]: if self.ui.title.split()[:1] != entry.title.split()[:1]:
self.error("Don't change the entry number please!") self.error("Don't change the entry number please!")
return return
# Check that the edited version is the current version # Check that the edited version is the current version
...@@ -779,7 +779,7 @@ class FaqWizard: ...@@ -779,7 +779,7 @@ class FaqWizard:
if '\r' in self.ui.body: if '\r' in self.ui.body:
self.ui.body = re.sub('\r\n?', '\n', self.ui.body) self.ui.body = re.sub('\r\n?', '\n', self.ui.body)
# Normalize whitespace in title # Normalize whitespace in title
self.ui.title = string.join(string.split(self.ui.title)) self.ui.title = ' '.join(self.ui.title.split())
# Check that there were any changes # Check that there were any changes
if self.ui.body == entry.body and self.ui.title == entry.title: if self.ui.body == entry.body and self.ui.title == entry.title:
self.error("You didn't make any changes!") self.error("You didn't make any changes!")
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
# and one or more .o files or a lib.a file. # and one or more .o files or a lib.a file.
import os import os
import string
import parsesetup import parsesetup
def checkextensions(unknown, extensions): def checkextensions(unknown, extensions):
...@@ -44,7 +43,7 @@ def select(e, mods, vars, mod, skipofiles): ...@@ -44,7 +43,7 @@ def select(e, mods, vars, mod, skipofiles):
if not w: if not w:
continue continue
w = expandvars(w, vars) w = expandvars(w, vars)
for w in string.split(w): for w in w.split():
if skipofiles and w[-2:] == '.o': if skipofiles and w[-2:] == '.o':
continue continue
# Assume $var expands to absolute pathname # Assume $var expands to absolute pathname
...@@ -73,14 +72,14 @@ def treatword(w): ...@@ -73,14 +72,14 @@ def treatword(w):
def expandvars(str, vars): def expandvars(str, vars):
i = 0 i = 0
while i < len(str): while i < len(str):
i = k = string.find(str, '$', i) i = k = str.find('$', i)
if i < 0: if i < 0:
break break
i = i+1 i = i+1
var = str[i:i+1] var = str[i:i+1]
i = i+1 i = i+1
if var == '(': if var == '(':
j = string.find(str, ')', i) j = str.find(')', i)
if j < 0: if j < 0:
break break
var = str[i:j] var = str[i:j]
......
...@@ -22,7 +22,7 @@ At the moment the name and location of this INI file is hardcoded, ...@@ -22,7 +22,7 @@ At the moment the name and location of this INI file is hardcoded,
but an obvious enhancement would be to provide command line options. but an obvious enhancement would be to provide command line options.
""" """
import os, string, sys import os, sys
try: try:
import win32api import win32api
except ImportError: except ImportError:
...@@ -107,12 +107,12 @@ def get_extension_defn(moduleName, mapFileName, prefix): ...@@ -107,12 +107,12 @@ def get_extension_defn(moduleName, mapFileName, prefix):
module.AddCompilerOption(win32api.ExpandEnvironmentStrings(cl_options)) module.AddCompilerOption(win32api.ExpandEnvironmentStrings(cl_options))
exclude = win32api.GetProfileVal(moduleName, "exclude", "", mapFileName) exclude = win32api.GetProfileVal(moduleName, "exclude", "", mapFileName)
exclude = string.split(exclude) exclude = exclude.split()
if win32api.GetProfileVal(moduleName, "Unicode", 0, mapFileName): if win32api.GetProfileVal(moduleName, "Unicode", 0, mapFileName):
module.AddCompilerOption('/D UNICODE /D _UNICODE') module.AddCompilerOption('/D UNICODE /D _UNICODE')
libs = string.split(win32api.GetProfileVal(moduleName, "libs", "", mapFileName)) libs = win32api.GetProfileVal(moduleName, "libs", "", mapFileName).split()
for lib in libs: for lib in libs:
module.AddLinkerLib(win32api.ExpandEnvironmentStrings(lib)) module.AddLinkerLib(win32api.ExpandEnvironmentStrings(lib))
...@@ -135,9 +135,9 @@ def parse_dsp(dsp): ...@@ -135,9 +135,9 @@ def parse_dsp(dsp):
sys.stderr.write("%s: %s\n" % (dsp, msg)) sys.stderr.write("%s: %s\n" % (dsp, msg))
return None return None
for line in lines: for line in lines:
fields = string.split(string.strip(line), "=", 2) fields = line.strip().split("=", 2)
if fields[0]=="SOURCE": if fields[0]=="SOURCE":
if string.lower(os.path.splitext(fields[1])[1]) in ['.cpp', '.c']: if os.path.splitext(fields[1])[1].lower() in ['.cpp', '.c']:
ret.append( win32api.GetFullPathName(os.path.join(dsp_path, fields[1] ) ) ) ret.append( win32api.GetFullPathName(os.path.join(dsp_path, fields[1] ) ) )
return ret return ret
...@@ -148,12 +148,12 @@ def write_extension_table(fname, modules): ...@@ -148,12 +148,12 @@ def write_extension_table(fname, modules):
# Write fn protos # Write fn protos
for module in modules: for module in modules:
# bit of a hack for .pyd's as part of packages. # bit of a hack for .pyd's as part of packages.
name = string.split(module.name,'.')[-1] name = module.name.split('.')[-1]
fp.write('extern void init%s(void);\n' % (name) ) fp.write('extern void init%s(void);\n' % (name) )
# Write the table # Write the table
fp.write (ext_tab_header) fp.write (ext_tab_header)
for module in modules: for module in modules:
name = string.split(module.name,'.')[-1] name = module.name.split('.')[-1]
fp.write('\t{"%s", init%s},\n' % (name, name) ) fp.write('\t{"%s", init%s},\n' % (name, name) )
fp.write (ext_tab_footer) fp.write (ext_tab_footer)
......
...@@ -91,7 +91,6 @@ if it does, the resulting binary is not self-contained. ...@@ -91,7 +91,6 @@ if it does, the resulting binary is not self-contained.
import getopt import getopt
import os import os
import string
import sys import sys
...@@ -148,7 +147,7 @@ def main(): ...@@ -148,7 +147,7 @@ def main():
# last option can not be "-i", so this ensures "pos+1" is in range! # last option can not be "-i", so this ensures "pos+1" is in range!
if sys.argv[pos] == '-i': if sys.argv[pos] == '-i':
try: try:
options = string.split(open(sys.argv[pos+1]).read()) options = open(sys.argv[pos+1]).read().split()
except IOError, why: except IOError, why:
usage("File name '%s' specified with the -i option " usage("File name '%s' specified with the -i option "
"can not be read - %s" % (sys.argv[pos+1], why) ) "can not be read - %s" % (sys.argv[pos+1], why) )
...@@ -198,9 +197,9 @@ def main(): ...@@ -198,9 +197,9 @@ def main():
if o == '-l': if o == '-l':
addn_link.append(a) addn_link.append(a)
if o == '-a': if o == '-a':
apply(modulefinder.AddPackagePath, tuple(string.split(a,"=", 2))) apply(modulefinder.AddPackagePath, tuple(a.split("=", 2)))
if o == '-r': if o == '-r':
f,r = string.split(a,"=", 2) f,r = a.split("=", 2)
replace_paths.append( (f,r) ) replace_paths.append( (f,r) )
# default prefix and exec_prefix # default prefix and exec_prefix
...@@ -419,7 +418,7 @@ def main(): ...@@ -419,7 +418,7 @@ def main():
# report unknown modules # report unknown modules
if unknown: if unknown:
sys.stderr.write('Warning: unknown modules remain: %s\n' % sys.stderr.write('Warning: unknown modules remain: %s\n' %
string.join(unknown)) ' '.join(unknown))
# windows gets different treatment # windows gets different treatment
if win: if win:
...@@ -462,8 +461,8 @@ def main(): ...@@ -462,8 +461,8 @@ def main():
for key in makevars.keys(): for key in makevars.keys():
somevars[key] = makevars[key] somevars[key] = makevars[key]
somevars['CFLAGS'] = string.join(cflags) # override somevars['CFLAGS'] = ' '.join(cflags) # override
somevars['CPPFLAGS'] = string.join(cppflags) # override somevars['CPPFLAGS'] = ' '.join(cppflags) # override
files = [base_config_c, base_frozen_c] + \ files = [base_config_c, base_frozen_c] + \
files + supp_sources + addfiles + libs + \ files + supp_sources + addfiles + libs + \
['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)'] ['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)']
......
import marshal import marshal
import string
import bkfile import bkfile
...@@ -38,7 +37,7 @@ def makefreeze(base, dict, debug=0, entry_point=None, fail_import=()): ...@@ -38,7 +37,7 @@ def makefreeze(base, dict, debug=0, entry_point=None, fail_import=()):
mods.sort() mods.sort()
for mod in mods: for mod in mods:
m = dict[mod] m = dict[mod]
mangled = string.join(string.split(mod, "."), "__") mangled = "__".join(mod.split("."))
if m.__code__: if m.__code__:
file = 'M_' + mangled + '.c' file = 'M_' + mangled + '.c'
outfp = bkfile.open(base + file, 'w') outfp = bkfile.open(base + file, 'w')
...@@ -88,4 +87,4 @@ def writecode(outfp, mod, str): ...@@ -88,4 +87,4 @@ def writecode(outfp, mod, str):
## def writecode(outfp, mod, str): ## def writecode(outfp, mod, str):
## outfp.write('unsigned char M_%s[%d] = "%s";\n' % (mod, len(str), ## outfp.write('unsigned char M_%s[%d] = "%s";\n' % (mod, len(str),
## string.join(map(lambda s: `s`[1:-1], string.split(str, '"')), '\\"'))) ## '\\"'.join(map(lambda s: `s`[1:-1], str.split('"')))))
# Write the actual Makefile. # Write the actual Makefile.
import os import os
import string
def makemakefile(outfp, makevars, files, target): def makemakefile(outfp, makevars, files, target):
outfp.write("# Makefile generated by freeze.py script\n\n") outfp.write("# Makefile generated by freeze.py script\n\n")
...@@ -23,8 +22,8 @@ def makemakefile(outfp, makevars, files, target): ...@@ -23,8 +22,8 @@ def makemakefile(outfp, makevars, files, target):
files[i] = dest files[i] = dest
deps.append(dest) deps.append(dest)
outfp.write("\n%s: %s\n" % (target, string.join(deps))) outfp.write("\n%s: %s\n" % (target, ' '.join(deps)))
outfp.write("\t$(LINKCC) $(LDFLAGS) $(LINKFORSHARED) %s -o %s $(LDLAST)\n" % outfp.write("\t$(LINKCC) $(LDFLAGS) $(LINKFORSHARED) %s -o %s $(LDLAST)\n" %
(string.join(files), target)) (' '.join(files), target))
outfp.write("\nclean:\n\t-rm -f *.o %s\n" % target) outfp.write("\nclean:\n\t-rm -f *.o %s\n" % target)
...@@ -5,7 +5,6 @@ import imp ...@@ -5,7 +5,6 @@ import imp
import marshal import marshal
import os import os
import re import re
import string
import sys import sys
import new import new
...@@ -150,7 +149,7 @@ class ModuleFinder: ...@@ -150,7 +149,7 @@ class ModuleFinder:
self.msgout(4, "determine_parent ->", parent) self.msgout(4, "determine_parent ->", parent)
return parent return parent
if '.' in pname: if '.' in pname:
i = string.rfind(pname, '.') i = pname.rfind('.')
pname = pname[:i] pname = pname[:i]
parent = self.modules[pname] parent = self.modules[pname]
assert parent.__name__ == pname assert parent.__name__ == pname
...@@ -162,7 +161,7 @@ class ModuleFinder: ...@@ -162,7 +161,7 @@ class ModuleFinder:
def find_head_package(self, parent, name): def find_head_package(self, parent, name):
self.msgin(4, "find_head_package", parent, name) self.msgin(4, "find_head_package", parent, name)
if '.' in name: if '.' in name:
i = string.find(name, '.') i = name.find('.')
head = name[:i] head = name[:i]
tail = name[i+1:] tail = name[i+1:]
else: else:
...@@ -190,7 +189,7 @@ class ModuleFinder: ...@@ -190,7 +189,7 @@ class ModuleFinder:
self.msgin(4, "load_tail", q, tail) self.msgin(4, "load_tail", q, tail)
m = q m = q
while tail: while tail:
i = string.find(tail, '.') i = tail.find('.')
if i < 0: i = len(tail) if i < 0: i = len(tail)
head, tail = tail[:i], tail[i+1:] head, tail = tail[:i], tail[i+1:]
mname = "%s.%s" % (m.__name__, head) mname = "%s.%s" % (m.__name__, head)
...@@ -357,7 +356,7 @@ class ModuleFinder: ...@@ -357,7 +356,7 @@ class ModuleFinder:
def find_module(self, name, path): def find_module(self, name, path):
if path: if path:
fullname = string.join(path, '.')+'.'+name fullname = '.'.join(path)+'.'+name
else: else:
fullname = name fullname = name
if fullname in self.excludes: if fullname in self.excludes:
...@@ -399,7 +398,7 @@ class ModuleFinder: ...@@ -399,7 +398,7 @@ class ModuleFinder:
if key not in self.excludes: if key not in self.excludes:
mods = self.badmodules[key].keys() mods = self.badmodules[key].keys()
mods.sort() mods.sort()
print "?", key, "from", string.join(mods, ', ') print "?", key, "from", ', '.join(mods)
def any_missing(self): def any_missing(self):
keys = self.badmodules.keys() keys = self.badmodules.keys()
...@@ -457,7 +456,7 @@ def test(): ...@@ -457,7 +456,7 @@ def test():
if o == '-m': if o == '-m':
domods = 1 domods = 1
if o == '-p': if o == '-p':
addpath = addpath + string.split(a, os.pathsep) addpath = addpath + a.split(os.pathsep)
if o == '-q': if o == '-q':
debug = 0 debug = 0
if o == '-x': if o == '-x':
......
# Parse Makefiles and Python Setup(.in) files. # Parse Makefiles and Python Setup(.in) files.
import re import re
import string
# Extract variable definitions from a Makefile. # Extract variable definitions from a Makefile.
...@@ -29,10 +28,10 @@ def getmakevars(filename): ...@@ -29,10 +28,10 @@ def getmakevars(filename):
continue continue
(name, value) = matchobj.group(1, 2) (name, value) = matchobj.group(1, 2)
# Strip trailing comment # Strip trailing comment
i = string.find(value, '#') i = value.find('#')
if i >= 0: if i >= 0:
value = value[:i] value = value[:i]
value = string.strip(value) value = value.strip()
variables[name] = value variables[name] = value
finally: finally:
fp.close() fp.close()
...@@ -60,7 +59,7 @@ def getsetupinfo(filename): ...@@ -60,7 +59,7 @@ def getsetupinfo(filename):
if not line: if not line:
break break
# Strip comments # Strip comments
i = string.find(line, '#') i = line.find('#')
if i >= 0: if i >= 0:
line = line[:i] line = line[:i]
if line.endswith('\\\n'): if line.endswith('\\\n'):
...@@ -69,9 +68,9 @@ def getsetupinfo(filename): ...@@ -69,9 +68,9 @@ def getsetupinfo(filename):
matchobj = setupvardef.match(line) matchobj = setupvardef.match(line)
if matchobj: if matchobj:
(name, value) = matchobj.group(1, 2) (name, value) = matchobj.group(1, 2)
variables[name] = string.strip(value) variables[name] = value.strip()
else: else:
words = string.split(line) words = line.split()
if words: if words:
modules[words[0]] = words[1:] modules[words[0]] = words[1:]
finally: finally:
......
import sys, os, string import sys, os
# Template used then the program is a GUI program # Template used then the program is a GUI program
WINMAINTEMPLATE = """ WINMAINTEMPLATE = """
...@@ -112,7 +112,7 @@ def realwork(vars, moddefns, target): ...@@ -112,7 +112,7 @@ def realwork(vars, moddefns, target):
print "\t\t$(cflags) $(cdebug) $(cinclude) \\" print "\t\t$(cflags) $(cdebug) $(cinclude) \\"
extra = moddefn.GetCompilerOptions() extra = moddefn.GetCompilerOptions()
if extra: if extra:
print "\t\t%s \\" % (string.join(extra),) print "\t\t%s \\" % (' '.join(extra),)
print '\t\t"%s"' % file print '\t\t"%s"' % file
print print
......
import string
#from Tkinter import TclError #from Tkinter import TclError
#import tkMessageBox #import tkMessageBox
#import tkSimpleDialog #import tkSimpleDialog
...@@ -168,15 +167,15 @@ class AutoIndent: ...@@ -168,15 +167,15 @@ class AutoIndent:
return "break" return "break"
# Ick. It may require *inserting* spaces if we back up over a # Ick. It may require *inserting* spaces if we back up over a
# tab character! This is written to be clear, not fast. # tab character! This is written to be clear, not fast.
expand, tabwidth = string.expandtabs, self.tabwidth tabwidth = self.tabwidth
have = len(expand(chars, tabwidth)) have = len(chars.expandtabs(tabwidth))
assert have > 0 assert have > 0
want = ((have - 1) // self.indentwidth) * self.indentwidth want = ((have - 1) // self.indentwidth) * self.indentwidth
ncharsdeleted = 0 ncharsdeleted = 0
while 1: while 1:
chars = chars[:-1] chars = chars[:-1]
ncharsdeleted = ncharsdeleted + 1 ncharsdeleted = ncharsdeleted + 1
have = len(expand(chars, tabwidth)) have = len(chars.expandtabs(tabwidth))
if have <= want or chars[-1] not in " \t": if have <= want or chars[-1] not in " \t":
break break
text.undo_block_start() text.undo_block_start()
...@@ -210,8 +209,7 @@ class AutoIndent: ...@@ -210,8 +209,7 @@ class AutoIndent:
if self.usetabs: if self.usetabs:
pad = '\t' pad = '\t'
else: else:
effective = len(string.expandtabs(prefix, effective = len(prefix.expandtabs(self.tabwidth))
self.tabwidth))
n = self.indentwidth n = self.indentwidth
pad = ' ' * (n - effective % n) pad = ' ' * (n - effective % n)
text.insert("insert", pad) text.insert("insert", pad)
...@@ -376,7 +374,7 @@ class AutoIndent: ...@@ -376,7 +374,7 @@ class AutoIndent:
head, tail, chars, lines = self.get_region() head, tail, chars, lines = self.get_region()
tabwidth = self._asktabwidth() tabwidth = self._asktabwidth()
for pos in range(len(lines)): for pos in range(len(lines)):
lines[pos] = string.expandtabs(lines[pos], tabwidth) lines[pos] = lines[pos].expandtabs(tabwidth)
self.set_region(head, tail, chars, lines) self.set_region(head, tail, chars, lines)
def toggle_tabs_event(self, event): def toggle_tabs_event(self, event):
...@@ -417,12 +415,12 @@ class AutoIndent: ...@@ -417,12 +415,12 @@ class AutoIndent:
head = text.index("insert linestart") head = text.index("insert linestart")
tail = text.index("insert lineend +1c") tail = text.index("insert lineend +1c")
chars = text.get(head, tail) chars = text.get(head, tail)
lines = string.split(chars, "\n") lines = chars.split("\n")
return head, tail, chars, lines return head, tail, chars, lines
def set_region(self, head, tail, chars, lines): def set_region(self, head, tail, chars, lines):
text = self.text text = self.text
newchars = string.join(lines, "\n") newchars = "\n".join(lines)
if newchars == chars: if newchars == chars:
text.bell() text.bell()
return return
......
...@@ -6,7 +6,6 @@ ...@@ -6,7 +6,6 @@
# Debug menu here, which is only present in the PythonShell window. # Debug menu here, which is only present in the PythonShell window.
import sys import sys
import string
from keydefs import * from keydefs import *
menudefs = [ menudefs = [
......
...@@ -141,7 +141,7 @@ def get_arg_text(ob): ...@@ -141,7 +141,7 @@ def get_arg_text(ob):
items.append("...") items.append("...")
if fob.func_code.co_flags & 0x8: if fob.func_code.co_flags & 0x8:
items.append("***") items.append("***")
argText = string.join(items , ", ") argText = ", ".join(items)
argText = "(%s)" % argText argText = "(%s)" % argText
except: except:
pass pass
......
...@@ -12,7 +12,6 @@ XXX TO DO: ...@@ -12,7 +12,6 @@ XXX TO DO:
import os import os
import sys import sys
import string
import pyclbr import pyclbr
# XXX Patch pyclbr with dummies if it's vintage Python 1.5.2: # XXX Patch pyclbr with dummies if it's vintage Python 1.5.2:
...@@ -117,7 +116,7 @@ class ModuleBrowserTreeItem(TreeItem): ...@@ -117,7 +116,7 @@ class ModuleBrowserTreeItem(TreeItem):
if sup.module != cl.module: if sup.module != cl.module:
sname = "%s.%s" % (sup.module, sname) sname = "%s.%s" % (sup.module, sname)
supers.append(sname) supers.append(sname)
s = s + "(%s)" % string.join(supers, ", ") s = s + "(%s)" % ", ".join(supers)
items.append((cl.lineno, s)) items.append((cl.lineno, s))
self.classes[s] = cl self.classes[s] = cl
items.sort() items.sort()
......
import time import time
import string
import re import re
import keyword import keyword
from Tkinter import * from Tkinter import *
...@@ -14,7 +13,7 @@ DEBUG = 0 ...@@ -14,7 +13,7 @@ DEBUG = 0
def any(name, list): def any(name, list):
return "(?P<%s>" % name + string.join(list, "|") + ")" return "(?P<%s>" % name + "|".join(list) + ")"
def make_pat(): def make_pat():
kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b" kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b"
......
import sys import sys
import os import os
import string
import re import re
import imp import imp
from Tkinter import * from Tkinter import *
...@@ -221,7 +220,7 @@ class EditorWindow: ...@@ -221,7 +220,7 @@ class EditorWindow:
self.text.after_idle(self.set_line_and_column) self.text.after_idle(self.set_line_and_column)
def set_line_and_column(self, event=None): def set_line_and_column(self, event=None):
line, column = string.split(self.text.index(INSERT), '.') line, column = self.text.index(INSERT).split('.')
self.status_bar.set_label('column', 'Col: %s' % column) self.status_bar.set_label('column', 'Col: %s' % column)
self.status_bar.set_label('line', 'Ln: %s' % line) self.status_bar.set_label('line', 'Ln: %s' % line)
...@@ -344,14 +343,14 @@ class EditorWindow: ...@@ -344,14 +343,14 @@ class EditorWindow:
except TclError: except TclError:
name = "" name = ""
else: else:
name = string.strip(name) name = name.strip()
if not name: if not name:
name = tkSimpleDialog.askstring("Module", name = tkSimpleDialog.askstring("Module",
"Enter the name of a Python module\n" "Enter the name of a Python module\n"
"to search on sys.path and open:", "to search on sys.path and open:",
parent=self.text) parent=self.text)
if name: if name:
name = string.strip(name) name = name.strip()
if not name: if not name:
return return
# XXX Ought to insert current file's directory in front of path # XXX Ought to insert current file's directory in front of path
...@@ -408,7 +407,7 @@ class EditorWindow: ...@@ -408,7 +407,7 @@ class EditorWindow:
f.close() f.close()
except IOError: except IOError:
return False return False
return line[:2] == '#!' and string.find(line, 'python') >= 0 return line.startswith('#!') and 'python' in line
def close_hook(self): def close_hook(self):
if self.flist: if self.flist:
...@@ -580,7 +579,7 @@ class EditorWindow: ...@@ -580,7 +579,7 @@ class EditorWindow:
if keydefs: if keydefs:
self.apply_bindings(keydefs) self.apply_bindings(keydefs)
for vevent in keydefs.keys(): for vevent in keydefs.keys():
methodname = string.replace(vevent, "-", "_") methodname = vevent.replace("-", "_")
while methodname[:1] == '<': while methodname[:1] == '<':
methodname = methodname[1:] methodname = methodname[1:]
while methodname[-1:] == '>': while methodname[-1:] == '>':
...@@ -700,7 +699,7 @@ class EditorWindow: ...@@ -700,7 +699,7 @@ class EditorWindow:
def prepstr(s): def prepstr(s):
# Helper to extract the underscore from a string, e.g. # Helper to extract the underscore from a string, e.g.
# prepstr("Co_py") returns (2, "Copy"). # prepstr("Co_py") returns (2, "Copy").
i = string.find(s, '_') i = s.find('_')
if i >= 0: if i >= 0:
s = s[:i] + s[i+1:] s = s[:i] + s[i+1:]
return i, s return i, s
...@@ -717,7 +716,7 @@ def get_accelerator(keydefs, event): ...@@ -717,7 +716,7 @@ def get_accelerator(keydefs, event):
if not keylist: if not keylist:
return "" return ""
s = keylist[0] s = keylist[0]
s = re.sub(r"-[a-z]\b", lambda m: string.upper(m.group()), s) s = re.sub(r"-[a-z]\b", lambda m: m.group().upper(), s)
s = re.sub(r"\b\w+\b", lambda m: keynames.get(m.group(), m.group()), s) s = re.sub(r"\b\w+\b", lambda m: keynames.get(m.group(), m.group()), s)
s = re.sub("Key-", "", s) s = re.sub("Key-", "", s)
s = re.sub("Control-", "Ctrl-", s) s = re.sub("Control-", "Ctrl-", s)
......
...@@ -14,7 +14,6 @@ ...@@ -14,7 +14,6 @@
# spaces, they will not be considered part of the same block. # spaces, they will not be considered part of the same block.
# * Fancy comments, like this bulleted list, arent handled :-) # * Fancy comments, like this bulleted list, arent handled :-)
import string
import re import re
class FormatParagraph: class FormatParagraph:
...@@ -50,14 +49,14 @@ class FormatParagraph: ...@@ -50,14 +49,14 @@ class FormatParagraph:
find_paragraph(text, text.index("insert")) find_paragraph(text, text.index("insert"))
if comment_header: if comment_header:
# Reformat the comment lines - convert to text sans header. # Reformat the comment lines - convert to text sans header.
lines = string.split(data, "\n") lines = data.split("\n")
lines = map(lambda st, l=len(comment_header): st[l:], lines) lines = map(lambda st, l=len(comment_header): st[l:], lines)
data = string.join(lines, "\n") data = "\n".join(lines)
# Reformat to 70 chars or a 20 char width, whichever is greater. # Reformat to 70 chars or a 20 char width, whichever is greater.
format_width = max(70-len(comment_header), 20) format_width = max(70-len(comment_header), 20)
newdata = reformat_paragraph(data, format_width) newdata = reformat_paragraph(data, format_width)
# re-split and re-insert the comment header. # re-split and re-insert the comment header.
newdata = string.split(newdata, "\n") newdata = newdata.split("\n")
# If the block ends in a \n, we dont want the comment # If the block ends in a \n, we dont want the comment
# prefix inserted after it. (Im not sure it makes sense to # prefix inserted after it. (Im not sure it makes sense to
# reformat a comment block that isnt made of complete # reformat a comment block that isnt made of complete
...@@ -68,7 +67,7 @@ class FormatParagraph: ...@@ -68,7 +67,7 @@ class FormatParagraph:
block_suffix = "\n" block_suffix = "\n"
newdata = newdata[:-1] newdata = newdata[:-1]
builder = lambda item, prefix=comment_header: prefix+item builder = lambda item, prefix=comment_header: prefix+item
newdata = string.join(map(builder, newdata), '\n') + block_suffix newdata = '\n'.join(map(builder, newdata)) + block_suffix
else: else:
# Just a normal text format # Just a normal text format
newdata = reformat_paragraph(data) newdata = reformat_paragraph(data)
...@@ -84,7 +83,7 @@ class FormatParagraph: ...@@ -84,7 +83,7 @@ class FormatParagraph:
text.see("insert") text.see("insert")
def find_paragraph(text, mark): def find_paragraph(text, mark):
lineno, col = map(int, string.split(mark, ".")) lineno, col = map(int, mark.split("."))
line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno) line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno)
while text.compare("%d.0" % lineno, "<", "end") and is_all_white(line): while text.compare("%d.0" % lineno, "<", "end") and is_all_white(line):
lineno = lineno + 1 lineno = lineno + 1
...@@ -109,7 +108,7 @@ def find_paragraph(text, mark): ...@@ -109,7 +108,7 @@ def find_paragraph(text, mark):
return first, last, comment_header, text.get(first, last) return first, last, comment_header, text.get(first, last)
def reformat_paragraph(data, limit=70): def reformat_paragraph(data, limit=70):
lines = string.split(data, "\n") lines = data.split("\n")
i = 0 i = 0
n = len(lines) n = len(lines)
while i < n and is_all_white(lines[i]): while i < n and is_all_white(lines[i]):
...@@ -130,18 +129,18 @@ def reformat_paragraph(data, limit=70): ...@@ -130,18 +129,18 @@ def reformat_paragraph(data, limit=70):
word = words[j] word = words[j]
if not word: if not word:
continue # Can happen when line ends in whitespace continue # Can happen when line ends in whitespace
if len(string.expandtabs(partial + word)) > limit and \ if len((partial + word).expandtabs()) > limit and \
partial != indent1: partial != indent1:
new.append(string.rstrip(partial)) new.append(partial.rstrip())
partial = indent2 partial = indent2
partial = partial + word + " " partial = partial + word + " "
if j+1 < len(words) and words[j+1] != " ": if j+1 < len(words) and words[j+1] != " ":
partial = partial + " " partial = partial + " "
i = i+1 i = i+1
new.append(string.rstrip(partial)) new.append(partial.rstrip())
# XXX Should reformat remaining paragraphs as well # XXX Should reformat remaining paragraphs as well
new.extend(lines[i:]) new.extend(lines[i:])
return string.join(new, "\n") return "\n".join(new)
def is_all_white(line): def is_all_white(line):
return re.match(r"^\s*$", line) is not None return re.match(r"^\s*$", line) is not None
......
import string
import os import os
import re import re
import fnmatch import fnmatch
......
import string
class History: class History:
def __init__(self, text, output_sep = "\n"): def __init__(self, text, output_sep = "\n"):
...@@ -22,11 +20,11 @@ class History: ...@@ -22,11 +20,11 @@ class History:
def _get_source(self, start, end): def _get_source(self, start, end):
# Get source code from start index to end index. Lines in the # Get source code from start index to end index. Lines in the
# text control may be separated by sys.ps2 . # text control may be separated by sys.ps2 .
lines = string.split(self.text.get(start, end), self.output_sep) lines = self.text.get(start, end).split(self.output_sep)
return string.join(lines, "\n") return "\n".join(lines)
def _put_source(self, where, source): def _put_source(self, where, source):
output = string.join(string.split(source, "\n"), self.output_sep) output = self.output_sep.join(source.split("\n"))
self.text.insert(where, output) self.text.insert(where, output)
def history_do(self, reverse): def history_do(self, reverse):
...@@ -68,7 +66,7 @@ class History: ...@@ -68,7 +66,7 @@ class History:
self.history_prefix = prefix self.history_prefix = prefix
def history_store(self, source): def history_store(self, source):
source = string.strip(source) source = source.strip()
if len(source) > 2: if len(source) > 2:
# avoid duplicates # avoid duplicates
try: try:
...@@ -80,7 +78,7 @@ class History: ...@@ -80,7 +78,7 @@ class History:
self.history_prefix = None self.history_prefix = None
def recall(self, s): def recall(self, s):
s = string.strip(s) s = s.strip()
self.text.tag_remove("sel", "1.0", "end") self.text.tag_remove("sel", "1.0", "end")
self.text.delete("iomark", "end-1c") self.text.delete("iomark", "end-1c")
self.text.mark_set("insert", "end-1c") self.text.mark_set("insert", "end-1c")
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
# the right list displays the substructure of the selected item # the right list displays the substructure of the selected item
# in the left list. # in the left list.
import string
from Tkinter import * from Tkinter import *
from WindowList import ListedToplevel from WindowList import ListedToplevel
from Separator import HSeparator from Separator import HSeparator
......
import string
import sys import sys
import os import os
from Tkinter import * from Tkinter import *
...@@ -121,7 +120,7 @@ class StackViewer(ScrolledList): ...@@ -121,7 +120,7 @@ class StackViewer(ScrolledList):
filename = code.co_filename filename = code.co_filename
funcname = code.co_name funcname = code.co_name
sourceline = linecache.getline(filename, lineno) sourceline = linecache.getline(filename, lineno)
sourceline = string.strip(sourceline) sourceline = sourceline.strip()
if funcname in ("?", "", None): if funcname in ("?", "", None):
item = "%s, line %d: %s" % (modname, lineno, sourceline) item = "%s, line %d: %s" % (modname, lineno, sourceline)
else: else:
......
...@@ -10,8 +10,6 @@ We'll have to fix IDLE to do something reasonable when two or more ...@@ -10,8 +10,6 @@ We'll have to fix IDLE to do something reasonable when two or more
extensions what to capture the same event. extensions what to capture the same event.
""" """
import string
import PyParse import PyParse
from AutoIndent import AutoIndent, index2line from AutoIndent import AutoIndent, index2line
from IdleConf import idleconf from IdleConf import idleconf
...@@ -177,10 +175,10 @@ class LastOpenBracketFinder: ...@@ -177,10 +175,10 @@ class LastOpenBracketFinder:
if i is None \ if i is None \
or keysym_type(buf[i]) != right_keysym_type: or keysym_type(buf[i]) != right_keysym_type:
return None return None
lines_back = string.count(buf[i:], "\n") - 1 lines_back = buf[i:].count("\n") - 1
# subtract one for the "\n" added to please the parser # subtract one for the "\n" added to please the parser
upto_open = buf[:i] upto_open = buf[:i]
j = string.rfind(upto_open, "\n") + 1 # offset of column 0 of line j = upto_open.rfind("\n") + 1 # offset of column 0 of line
offset = i - j offset = i - j
return "%d.%d" % (lno - lines_back, offset) return "%d.%d" % (lno - lines_back, offset)
......
import string
import re import re
import sys import sys
...@@ -7,7 +6,7 @@ C_NONE, C_BACKSLASH, C_STRING, C_BRACKET = range(4) ...@@ -7,7 +6,7 @@ C_NONE, C_BACKSLASH, C_STRING, C_BRACKET = range(4)
if 0: # for throwaway debugging output if 0: # for throwaway debugging output
def dump(*stuff): def dump(*stuff):
sys.__stdout__.write(string.join(map(str, stuff), " ") + "\n") sys.__stdout__.write(" ".join(map(str, stuff)) + "\n")
# Find what looks like the start of a popular stmt. # Find what looks like the start of a popular stmt.
...@@ -103,7 +102,7 @@ for ch in ")}]": ...@@ -103,7 +102,7 @@ for ch in ")}]":
_tran[ord(ch)] = ')' _tran[ord(ch)] = ')'
for ch in "\"'\\\n#": for ch in "\"'\\\n#":
_tran[ord(ch)] = ch _tran[ord(ch)] = ch
_tran = string.join(_tran, '') _tran = ''.join(_tran)
del ch del ch
try: try:
...@@ -153,13 +152,12 @@ class Parser: ...@@ -153,13 +152,12 @@ class Parser:
# Python 1.5.2 (#0, Apr 13 1999, ... # Python 1.5.2 (#0, Apr 13 1999, ...
def find_good_parse_start(self, use_ps1, is_char_in_string=None, def find_good_parse_start(self, use_ps1, is_char_in_string=None,
_rfind=string.rfind,
_synchre=_synchre): _synchre=_synchre):
str, pos = self.str, None str, pos = self.str, None
if use_ps1: if use_ps1:
# shell window # shell window
ps1 = '\n' + sys.ps1 ps1 = '\n' + sys.ps1
i = _rfind(str, ps1) i = str.rfind(ps1)
if i >= 0: if i >= 0:
pos = i + len(ps1) pos = i + len(ps1)
# make it look like there's a newline instead # make it look like there's a newline instead
...@@ -178,10 +176,10 @@ class Parser: ...@@ -178,10 +176,10 @@ class Parser:
# bumped to a legitimate synch point. # bumped to a legitimate synch point.
limit = len(str) limit = len(str)
for tries in range(5): for tries in range(5):
i = _rfind(str, ":\n", 0, limit) i = str.rfind(":\n", 0, limit)
if i < 0: if i < 0:
break break
i = _rfind(str, '\n', 0, i) + 1 # start of colon line i = str.rfind('\n', 0, i) + 1 # start of colon line
m = _synchre(str, i, limit) m = _synchre(str, i, limit)
if m and not is_char_in_string(m.start()): if m and not is_char_in_string(m.start()):
pos = m.start() pos = m.start()
...@@ -226,7 +224,7 @@ class Parser: ...@@ -226,7 +224,7 @@ class Parser:
# based) of the non-continuation lines. # based) of the non-continuation lines.
# Creates self.{goodlines, continuation}. # Creates self.{goodlines, continuation}.
def _study1(self, _replace=string.replace, _find=string.find): def _study1(self):
if self.study_level >= 1: if self.study_level >= 1:
return return
self.study_level = 1 self.study_level = 1
...@@ -236,12 +234,12 @@ class Parser: ...@@ -236,12 +234,12 @@ class Parser:
# uninteresting characters. This can cut the number of chars # uninteresting characters. This can cut the number of chars
# by a factor of 10-40, and so greatly speed the following loop. # by a factor of 10-40, and so greatly speed the following loop.
str = self.str str = self.str
str = string.translate(str, _tran) str = str.translate(_tran)
str = _replace(str, 'xxxxxxxx', 'x') str = str.replace('xxxxxxxx', 'x')
str = _replace(str, 'xxxx', 'x') str = str.replace('xxxx', 'x')
str = _replace(str, 'xx', 'x') str = str.replace('xx', 'x')
str = _replace(str, 'xx', 'x') str = str.replace('xx', 'x')
str = _replace(str, '\nx', '\n') str = str.replace('\nx', '\n')
# note that replacing x\n with \n would be incorrect, because # note that replacing x\n with \n would be incorrect, because
# x may be preceded by a backslash # x may be preceded by a backslash
...@@ -322,7 +320,7 @@ class Parser: ...@@ -322,7 +320,7 @@ class Parser:
if ch == '#': if ch == '#':
# consume the comment # consume the comment
i = _find(str, '\n', i) i = str.find('\n', i)
assert i >= 0 assert i >= 0
continue continue
...@@ -363,8 +361,7 @@ class Parser: ...@@ -363,8 +361,7 @@ class Parser:
# self.lastopenbracketpos # self.lastopenbracketpos
# if continuation is C_BRACKET, index of last open bracket # if continuation is C_BRACKET, index of last open bracket
def _study2(self, _rfind=string.rfind, _find=string.find, def _study2(self):
_ws=string.whitespace):
if self.study_level >= 2: if self.study_level >= 2:
return return
self._study1() self._study1()
...@@ -381,7 +378,7 @@ class Parser: ...@@ -381,7 +378,7 @@ class Parser:
q = p q = p
for nothing in range(goodlines[i-1], goodlines[i]): for nothing in range(goodlines[i-1], goodlines[i]):
# tricky: sets p to 0 if no preceding newline # tricky: sets p to 0 if no preceding newline
p = _rfind(str, '\n', 0, p-1) + 1 p = str.rfind('\n', 0, p-1) + 1
# The stmt str[p:q] isn't a continuation, but may be blank # The stmt str[p:q] isn't a continuation, but may be blank
# or a non-indenting comment line. # or a non-indenting comment line.
if _junkre(str, p): if _junkre(str, p):
...@@ -444,7 +441,7 @@ class Parser: ...@@ -444,7 +441,7 @@ class Parser:
if ch == '#': if ch == '#':
# consume comment and trailing newline # consume comment and trailing newline
p = _find(str, '\n', p, q) + 1 p = str.find('\n', p, q) + 1
assert p > 0 assert p > 0
continue continue
...@@ -465,13 +462,13 @@ class Parser: ...@@ -465,13 +462,13 @@ class Parser:
# Assuming continuation is C_BRACKET, return the number # Assuming continuation is C_BRACKET, return the number
# of spaces the next line should be indented. # of spaces the next line should be indented.
def compute_bracket_indent(self, _find=string.find): def compute_bracket_indent(self):
self._study2() self._study2()
assert self.continuation == C_BRACKET assert self.continuation == C_BRACKET
j = self.lastopenbracketpos j = self.lastopenbracketpos
str = self.str str = self.str
n = len(str) n = len(str)
origi = i = string.rfind(str, '\n', 0, j) + 1 origi = i = str.rfind('\n', 0, j) + 1
j = j+1 # one beyond open bracket j = j+1 # one beyond open bracket
# find first list item; set i to start of its line # find first list item; set i to start of its line
while j < n: while j < n:
...@@ -482,7 +479,7 @@ class Parser: ...@@ -482,7 +479,7 @@ class Parser:
break break
else: else:
# this line is junk; advance to next line # this line is junk; advance to next line
i = j = _find(str, '\n', j) + 1 i = j = str.find('\n', j) + 1
else: else:
# nothing interesting follows the bracket; # nothing interesting follows the bracket;
# reproduce the bracket line's indentation + a level # reproduce the bracket line's indentation + a level
...@@ -490,8 +487,7 @@ class Parser: ...@@ -490,8 +487,7 @@ class Parser:
while str[j] in " \t": while str[j] in " \t":
j = j+1 j = j+1
extra = self.indentwidth extra = self.indentwidth
return len(string.expandtabs(str[i:j], return len(str[i:j].expandtabs(self.tabwidth)) + extra
self.tabwidth)) + extra
# Return number of physical lines in last stmt (whether or not # Return number of physical lines in last stmt (whether or not
# it's an interesting stmt! this is intended to be called when # it's an interesting stmt! this is intended to be called when
...@@ -517,7 +513,7 @@ class Parser: ...@@ -517,7 +513,7 @@ class Parser:
# See whether the initial line starts an assignment stmt; i.e., # See whether the initial line starts an assignment stmt; i.e.,
# look for an = operator # look for an = operator
endpos = string.find(str, '\n', startpos) + 1 endpos = str.find('\n', startpos) + 1
found = level = 0 found = level = 0
while i < endpos: while i < endpos:
ch = str[i] ch = str[i]
...@@ -553,8 +549,7 @@ class Parser: ...@@ -553,8 +549,7 @@ class Parser:
while str[i] not in " \t\n": while str[i] not in " \t\n":
i = i+1 i = i+1
return len(string.expandtabs(str[self.stmt_start : return len(str[self.stmt_start:i].expandtabs(\
i],
self.tabwidth)) + 1 self.tabwidth)) + 1
# Return the leading whitespace on the initial line of the last # Return the leading whitespace on the initial line of the last
......
...@@ -208,7 +208,7 @@ class ModifiedInterpreter(InteractiveInterpreter): ...@@ -208,7 +208,7 @@ class ModifiedInterpreter(InteractiveInterpreter):
# Stuff source in the filename cache # Stuff source in the filename cache
filename = "<pyshell#%d>" % self.gid filename = "<pyshell#%d>" % self.gid
self.gid = self.gid + 1 self.gid = self.gid + 1
lines = string.split(source, "\n") lines = source.split("\n")
linecache.cache[filename] = len(source)+1, 0, lines, filename linecache.cache[filename] = len(source)+1, 0, lines, filename
return filename return filename
...@@ -582,7 +582,7 @@ class PyShell(OutputWindow): ...@@ -582,7 +582,7 @@ class PyShell(OutputWindow):
# If we're in the current input and there's only whitespace # If we're in the current input and there's only whitespace
# beyond the cursor, erase that whitespace first # beyond the cursor, erase that whitespace first
s = self.text.get("insert", "end-1c") s = self.text.get("insert", "end-1c")
if s and not string.strip(s): if s and not s.strip():
self.text.delete("insert", "end-1c") self.text.delete("insert", "end-1c")
# If we're in the current input before its last line, # If we're in the current input before its last line,
# insert a newline right at the insert point # insert a newline right at the insert point
......
import string
import os import os
import re import re
import fnmatch import fnmatch
......
import string
from Tkinter import * from Tkinter import *
class SearchDialogBase: class SearchDialogBase:
......
import string
import re import re
from Tkinter import * from Tkinter import *
import tkMessageBox import tkMessageBox
...@@ -175,7 +174,7 @@ class SearchEngine: ...@@ -175,7 +174,7 @@ class SearchEngine:
wrapped = 1 wrapped = 1
wrap = 0 wrap = 0
pos = text.index("end-1c") pos = text.index("end-1c")
line, col = map(int, string.split(pos, ".")) line, col = map(int, pos.split("."))
chars = text.get("%d.0" % line, "%d.0" % (line+1)) chars = text.get("%d.0" % line, "%d.0" % (line+1))
col = len(chars) - 1 col = len(chars) - 1
return None return None
...@@ -217,5 +216,5 @@ def get_selection(text): ...@@ -217,5 +216,5 @@ def get_selection(text):
# Helper to parse a text index into a (line, col) tuple. # Helper to parse a text index into a (line, col) tuple.
def get_line_col(index): def get_line_col(index):
line, col = map(int, string.split(index, ".")) # Fails on invalid index line, col = map(int, index.split(".")) # Fails on invalid index
return line, col return line, col
import os import os
import sys import sys
import string
import linecache import linecache
from TreeWidget import TreeNode, TreeItem, ScrolledCanvas from TreeWidget import TreeNode, TreeItem, ScrolledCanvas
...@@ -50,7 +49,7 @@ class FrameTreeItem(TreeItem): ...@@ -50,7 +49,7 @@ class FrameTreeItem(TreeItem):
filename = code.co_filename filename = code.co_filename
funcname = code.co_name funcname = code.co_name
sourceline = linecache.getline(filename, lineno) sourceline = linecache.getline(filename, lineno)
sourceline = string.strip(sourceline) sourceline = sourceline.strip()
if funcname in ("?", "", None): if funcname in ("?", "", None):
item = "%s, line %d: %s" % (modname, lineno, sourceline) item = "%s, line %d: %s" % (modname, lineno, sourceline)
else: else:
......
...@@ -16,7 +16,6 @@ ...@@ -16,7 +16,6 @@
import os import os
import sys import sys
import string
from Tkinter import * from Tkinter import *
import imp import imp
......
...@@ -311,7 +311,7 @@ class CommandSequence(Command): ...@@ -311,7 +311,7 @@ class CommandSequence(Command):
strs = [] strs = []
for cmd in self.cmds: for cmd in self.cmds:
strs.append(" " + `cmd`) strs.append(" " + `cmd`)
return s + "(\n" + string.join(strs, ",\n") + "\n)" return s + "(\n" + ",\n".join(strs) + "\n)"
def __len__(self): def __len__(self):
return len(self.cmds) return len(self.cmds)
......
...@@ -5,7 +5,6 @@ ...@@ -5,7 +5,6 @@
import re import re
import sys import sys
import os import os
import string
import getopt import getopt
import glob import glob
import fileinput import fileinput
...@@ -25,7 +24,7 @@ def main(): ...@@ -25,7 +24,7 @@ def main():
if not sublist: if not sublist:
sublist.append('file %s' % fileinput.filename()) sublist.append('file %s' % fileinput.filename())
sublist.append('line %d' % fileinput.lineno()) sublist.append('line %d' % fileinput.lineno())
sublist.append(string.strip(line[2:-1])) sublist.append(line[2:-1].strip())
else: else:
if sublist: if sublist:
hits.append(sublist) hits.append(sublist)
...@@ -37,7 +36,7 @@ def main(): ...@@ -37,7 +36,7 @@ def main():
for sublist in hits: for sublist in hits:
d = {} d = {}
for line in sublist: for line in sublist:
words = string.split(line, None, 1) words = line.split(None, 1)
if len(words) != 2: if len(words) != 2:
continue continue
tag = words[0] tag = words[0]
......
...@@ -20,7 +20,6 @@ ...@@ -20,7 +20,6 @@
import sys import sys
import os import os
import varsubst import varsubst
import string
error = 'genmodule.error' error = 'genmodule.error'
...@@ -43,7 +42,7 @@ class writer: ...@@ -43,7 +42,7 @@ class writer:
if not self._subst: if not self._subst:
if not self.__dict__.has_key('abbrev'): if not self.__dict__.has_key('abbrev'):
self.abbrev = self.name self.abbrev = self.name
self.Abbrev = string.upper(self.abbrev[0])+self.abbrev[1:] self.Abbrev = self.abbrev[0].upper()+self.abbrev[1:]
subst = varsubst.Varsubst(self.__dict__) subst = varsubst.Varsubst(self.__dict__)
subst.useindent(1) subst.useindent(1)
self._subst = subst.subst self._subst = subst.subst
......
...@@ -223,7 +223,7 @@ class UI_module: ...@@ -223,7 +223,7 @@ class UI_module:
rv = rv + (name+'.name = '+`self.name_entry.get()`+'\n') rv = rv + (name+'.name = '+`self.name_entry.get()`+'\n')
rv = rv + (name+'.abbrev = '+`self.abbrev_entry.get()`+'\n') rv = rv + (name+'.abbrev = '+`self.abbrev_entry.get()`+'\n')
rv = rv + (name+'.methodlist = '+`getlistlist(self.method_list)`+'\n') rv = rv + (name+'.methodlist = '+`getlistlist(self.method_list)`+'\n')
rv = rv + (name+'.objects = ['+string.joinfields(onames, ',')+']\n') rv = rv + (name+'.objects = ['+','.join(onames)+']\n')
rv = rv + ('\n') rv = rv + ('\n')
return rv return rv
......
# #
# Variable substitution. Variables are $delimited$ # Variable substitution. Variables are $delimited$
# #
import string
import re import re
error = 'varsubst.error' error = 'varsubst.error'
...@@ -37,7 +36,7 @@ class Varsubst: ...@@ -37,7 +36,7 @@ class Varsubst:
rv = rv + value rv = rv + value
def _modindent(self, value, old): def _modindent(self, value, old):
lastnl = string.rfind(old, '\n', 0) + 1 lastnl = old.rfind('\n', 0) + 1
lastnl = len(old) - lastnl lastnl = len(old) - lastnl
sub = '\n' + (' '*lastnl) sub = '\n' + (' '*lastnl)
return re.sub('\n', sub, value) return re.sub('\n', sub, value)
......
...@@ -7,7 +7,6 @@ ...@@ -7,7 +7,6 @@
# Options -[amc] select atime, mtime (default) or ctime as age. # Options -[amc] select atime, mtime (default) or ctime as age.
import sys, os, time import sys, os, time
import string
from stat import * from stat import *
# Use lstat() to stat files if it exists, else stat() # Use lstat() to stat files if it exists, else stat()
...@@ -51,7 +50,7 @@ for file in sys.argv[1:]: ...@@ -51,7 +50,7 @@ for file in sys.argv[1:]:
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 string.ljust(file, maxlen), print file.ljust(maxlen),
print string.rjust(`int(byteyears)`, 8) print repr(int(byteyears)).rjust(8)
sys.exit(status) sys.exit(status)
...@@ -35,14 +35,13 @@ __version__ = 1, 0, 0 ...@@ -35,14 +35,13 @@ __version__ = 1, 0, 0
import os import os
import sys import sys
import string
import getopt import getopt
import tokenize import tokenize
verbose = 0 verbose = 0
def errprint(*args): def errprint(*args):
msg = string.join(args) msg = ' '.join(args)
sys.stderr.write(msg) sys.stderr.write(msg)
sys.stderr.write("\n") sys.stderr.write("\n")
......
...@@ -156,8 +156,6 @@ classprog = regex.compile(classexpr) ...@@ -156,8 +156,6 @@ classprog = regex.compile(classexpr)
baseexpr = '^ *\(.*\) *( *) *$' baseexpr = '^ *\(.*\) *( *) *$'
baseprog = regex.compile(baseexpr) baseprog = regex.compile(baseexpr)
import string
def fixline(line): def fixline(line):
if classprog.match(line) < 0: # No 'class' keyword -- no change if classprog.match(line) < 0: # No 'class' keyword -- no change
return line return line
...@@ -176,7 +174,7 @@ def fixline(line): ...@@ -176,7 +174,7 @@ def fixline(line):
basepart = line[a2+1:b2] basepart = line[a2+1:b2]
# Extract list of base expressions # Extract list of base expressions
bases = string.splitfields(basepart, ',') bases = basepart.split(',')
# Strip trailing '()' from each base expression # Strip trailing '()' from each base expression
for i in range(len(bases)): for i in range(len(bases)):
...@@ -185,7 +183,7 @@ def fixline(line): ...@@ -185,7 +183,7 @@ def fixline(line):
bases[i] = bases[i][x1:y1] bases[i] = bases[i][x1:y1]
# Join the bases back again and build the new line # Join the bases back again and build the new line
basepart = string.joinfields(bases, ', ') basepart = ', '.join(bases)
return head + '(' + basepart + '):' + tail return head + '(' + basepart + '):' + tail
......
...@@ -14,7 +14,6 @@ import os ...@@ -14,7 +14,6 @@ import os
import sys import sys
import stat import stat
import getopt import getopt
import string
cutofftime = 0 cutofftime = 0
...@@ -51,7 +50,7 @@ def process(dir): ...@@ -51,7 +50,7 @@ def process(dir):
if cvsdir: if cvsdir:
entries = os.path.join(cvsdir, "Entries") entries = os.path.join(cvsdir, "Entries")
for e in open(entries).readlines(): for e in open(entries).readlines():
words = string.split(e, '/') words = e.split('/')
if words[0] == '' and words[1:]: if words[0] == '' and words[1:]:
name = words[1] name = words[1]
fullname = os.path.join(dir, name) fullname = os.path.join(dir, name)
......
#! /usr/bin/env python #! /usr/bin/env python
# Format du output in a tree shape # Format du output in a tree shape
import os, string, sys, errno import os, sys, errno
def main(): def main():
p = os.popen('du ' + string.join(sys.argv[1:]), 'r') p = os.popen('du ' + ' '.join(sys.argv[1:]), 'r')
total, d = None, {} total, d = None, {}
for line in p.readlines(): for line in p.readlines():
i = 0 i = 0
...@@ -12,7 +12,7 @@ def main(): ...@@ -12,7 +12,7 @@ def main():
size = eval(line[:i]) size = eval(line[:i])
while line[i] in ' \t': i = i+1 while line[i] in ' \t': i = i+1
file = line[i:-1] file = line[i:-1]
comps = string.splitfields(file, '/') comps = file.split('/')
if comps[0] == '': comps[0] = '/' if comps[0] == '': comps[0] = '/'
if comps[len(comps)-1] == '': del comps[len(comps)-1] if comps[len(comps)-1] == '': del comps[len(comps)-1]
total, d = store(size, comps, total, d) total, d = store(size, comps, total, d)
...@@ -51,7 +51,7 @@ def show(total, d, prefix): ...@@ -51,7 +51,7 @@ def show(total, d, prefix):
if tsub is None: if tsub is None:
psub = prefix psub = prefix
else: else:
print prefix + string.rjust(`tsub`, 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)
......
...@@ -36,7 +36,6 @@ ...@@ -36,7 +36,6 @@
import sys import sys
import regex import regex
import string
import os import os
from stat import * from stat import *
import getopt import getopt
...@@ -213,11 +212,11 @@ Number = Floatnumber + '\|' + Intnumber ...@@ -213,11 +212,11 @@ Number = Floatnumber + '\|' + Intnumber
# Anything else is an operator -- don't list this explicitly because of '/*' # Anything else is an operator -- don't list this explicitly because of '/*'
OutsideComment = (Identifier, Number, String, Char, CommentStart) OutsideComment = (Identifier, Number, String, Char, CommentStart)
OutsideCommentPattern = '\(' + string.joinfields(OutsideComment, '\|') + '\)' OutsideCommentPattern = '\(' + '\|'.join(OutsideComment) + '\)'
OutsideCommentProgram = regex.compile(OutsideCommentPattern) OutsideCommentProgram = regex.compile(OutsideCommentPattern)
InsideComment = (Identifier, Number, CommentEnd) InsideComment = (Identifier, Number, CommentEnd)
InsideCommentPattern = '\(' + string.joinfields(InsideComment, '\|') + '\)' InsideCommentPattern = '\(' + '\|'.join(InsideComment) + '\)'
InsideCommentProgram = regex.compile(InsideCommentPattern) InsideCommentProgram = regex.compile(InsideCommentPattern)
def initfixline(): def initfixline():
...@@ -286,10 +285,10 @@ def addsubst(substfile): ...@@ -286,10 +285,10 @@ def addsubst(substfile):
if not line: break if not line: break
lineno = lineno + 1 lineno = lineno + 1
try: try:
i = string.index(line, '#') i = line.index('#')
except string.index_error: except ValueError:
i = -1 # Happens to delete trailing \n i = -1 # Happens to delete trailing \n
words = string.split(line[:i]) words = line[:i].split()
if not words: continue if not words: continue
if len(words) == 3 and words[0] == 'struct': if len(words) == 3 and words[0] == 'struct':
words[:2] = [words[0] + ' ' + words[1]] words[:2] = [words[0] + ' ' + words[1]]
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
# Add some standard cpp magic to a header file # Add some standard cpp magic to a header file
import sys import sys
import string
def main(): def main():
args = sys.argv[1:] args = sys.argv[1:]
...@@ -29,8 +28,8 @@ def process(file): ...@@ -29,8 +28,8 @@ def process(file):
sys.stderr.write('Processing %s ...\n' % file) sys.stderr.write('Processing %s ...\n' % file)
magic = 'Py_' magic = 'Py_'
for c in file: for c in file:
if c in string.ascii_letters + string.digits: if ord(c)<=0x80 and c.isalnum():
magic = magic + string.upper(c) magic = magic + c.upper()
else: magic = magic + '_' else: magic = magic + '_'
sys.stdout = f sys.stdout = f
print '#ifndef', magic print '#ifndef', magic
......
...@@ -22,7 +22,6 @@ import os ...@@ -22,7 +22,6 @@ import os
import sys import sys
import time import time
import getopt import getopt
import string
import ftplib import ftplib
import netrc import netrc
from fnmatch import fnmatch from fnmatch import fnmatch
...@@ -127,7 +126,7 @@ def mirrorsubdir(f, localdir): ...@@ -127,7 +126,7 @@ def mirrorsubdir(f, localdir):
if mac: if mac:
# Mac listing has just filenames; # Mac listing has just filenames;
# trailing / means subdirectory # trailing / means subdirectory
filename = string.strip(line) filename = line.strip()
mode = '-' mode = '-'
if filename[-1:] == '/': if filename[-1:] == '/':
filename = filename[:-1] filename = filename[:-1]
...@@ -135,12 +134,12 @@ def mirrorsubdir(f, localdir): ...@@ -135,12 +134,12 @@ def mirrorsubdir(f, localdir):
infostuff = '' infostuff = ''
else: else:
# Parse, assuming a UNIX listing # Parse, assuming a UNIX listing
words = string.split(line, 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 = string.lstrip(words[-1]) filename = words[-1].lstrip()
i = string.find(filename, " -> ") 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:
...@@ -360,7 +359,7 @@ class LoggingFile: ...@@ -360,7 +359,7 @@ class LoggingFile:
def askabout(filetype, filename, pwd): def askabout(filetype, filename, pwd):
prompt = 'Retrieve %s %s from %s ? [ny] ' % (filetype, filename, pwd) prompt = 'Retrieve %s %s from %s ? [ny] ' % (filetype, filename, pwd)
while 1: while 1:
reply = string.lower(string.strip(raw_input(prompt))) reply = raw_input(prompt).strip().lower()
if reply in ['y', 'ye', 'yes']: if reply in ['y', 'ye', 'yes']:
return 1 return 1
if reply in ['', 'n', 'no', 'nop', 'nope']: if reply in ['', 'n', 'no', 'nop', 'nope']:
......
...@@ -22,7 +22,7 @@ Written by Marc-Andre Lemburg (mal@lemburg.com). ...@@ -22,7 +22,7 @@ Written by Marc-Andre Lemburg (mal@lemburg.com).
"""#" """#"
import string,re,os,time,marshal import re,os,time,marshal
# Create numeric tables or character based ones ? # Create numeric tables or character based ones ?
numeric = 1 numeric = 1
...@@ -34,9 +34,7 @@ mapRE = re.compile('((?:0x[0-9a-fA-F]+\+?)+)' ...@@ -34,9 +34,7 @@ mapRE = re.compile('((?:0x[0-9a-fA-F]+\+?)+)'
'(#.+)?') '(#.+)?')
def parsecodes(codes, def parsecodes(codes,
len=len, filter=filter,range=range):
split=string.split,atoi=string.atoi,len=len,
filter=filter,range=range):
""" Converts code combinations to either a single code integer """ Converts code combinations to either a single code integer
or a tuple of integers. or a tuple of integers.
...@@ -49,12 +47,12 @@ def parsecodes(codes, ...@@ -49,12 +47,12 @@ def parsecodes(codes,
""" """
if not codes: if not codes:
return None return None
l = split(codes,'+') l = codes.split('+')
if len(l) == 1: if len(l) == 1:
return atoi(l[0],16) return int(l[0],16)
for i in range(len(l)): for i in range(len(l)):
try: try:
l[i] = atoi(l[i],16) l[i] = int(l[i],16)
except ValueError: except ValueError:
l[i] = None l[i] = None
l = filter(lambda x: x is not None, l) l = filter(lambda x: x is not None, l)
...@@ -63,9 +61,7 @@ def parsecodes(codes, ...@@ -63,9 +61,7 @@ def parsecodes(codes,
else: else:
return tuple(l) return tuple(l)
def readmap(filename, def readmap(filename):
strip=string.strip):
f = open(filename,'r') f = open(filename,'r')
lines = f.readlines() lines = f.readlines()
...@@ -76,7 +72,7 @@ def readmap(filename, ...@@ -76,7 +72,7 @@ def readmap(filename,
for i in range(256): for i in range(256):
unmapped[i] = i unmapped[i] = i
for line in lines: for line in lines:
line = strip(line) line = line.strip()
if not line or line[0] == '#': if not line or line[0] == '#':
continue continue
m = mapRE.match(line) m = mapRE.match(line)
...@@ -108,9 +104,7 @@ def readmap(filename, ...@@ -108,9 +104,7 @@ def readmap(filename,
return enc2uni return enc2uni
def hexrepr(t, def hexrepr(t):
join=string.join):
if t is None: if t is None:
return 'None' return 'None'
...@@ -118,11 +112,9 @@ def hexrepr(t, ...@@ -118,11 +112,9 @@ def hexrepr(t,
len(t) len(t)
except: except:
return '0x%04x' % t return '0x%04x' % t
return '(' + join(map(lambda t: '0x%04x' % t, t),', ') + ')' return '(' + ', '.join(map(lambda t: '0x%04x' % t, t)) + ')'
def unicoderepr(t, def unicoderepr(t):
join=string.join):
if t is None: if t is None:
return 'None' return 'None'
...@@ -133,11 +125,9 @@ def unicoderepr(t, ...@@ -133,11 +125,9 @@ def unicoderepr(t,
len(t) len(t)
except: except:
return repr(unichr(t)) return repr(unichr(t))
return repr(join(map(unichr, t),'')) return repr(''.join(map(unichr, t)))
def keyrepr(t,
join=string.join): def keyrepr(t):
if t is None: if t is None:
return 'None' return 'None'
...@@ -151,7 +141,7 @@ def keyrepr(t, ...@@ -151,7 +141,7 @@ def keyrepr(t,
return repr(chr(t)) return repr(chr(t))
else: else:
return repr(unichr(t)) return repr(unichr(t))
return repr(join(map(chr, t),'')) return repr(''.join(map(chr, t)))
def codegen(name,map,comments=1): def codegen(name,map,comments=1):
...@@ -246,7 +236,7 @@ def getregentry(): ...@@ -246,7 +236,7 @@ def getregentry():
encoding_map = codecs.make_encoding_map(decoding_map) encoding_map = codecs.make_encoding_map(decoding_map)
''') ''')
return string.join(l,'\n') return '\n'.join(l)
def pymap(name,map,pyfile,comments=1): def pymap(name,map,pyfile,comments=1):
...@@ -269,9 +259,9 @@ def convertdir(dir,prefix='',comments=1): ...@@ -269,9 +259,9 @@ def convertdir(dir,prefix='',comments=1):
mapnames = os.listdir(dir) mapnames = os.listdir(dir)
for mapname in mapnames: for mapname in mapnames:
name = os.path.split(mapname)[1] name = os.path.split(mapname)[1]
name = string.replace(name,'-','_') name = name.replace('-','_')
name = string.split(name, '.')[0] name = name.split('.')[0]
name = string.lower(name) name = name.lower()
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,
......
...@@ -29,7 +29,6 @@ ...@@ -29,7 +29,6 @@
import sys import sys
import regex import regex
import getopt import getopt
import string
defs = [] defs = []
undefs = [] undefs = []
...@@ -62,12 +61,12 @@ def process(fpi, fpo): ...@@ -62,12 +61,12 @@ def process(fpi, fpo):
nextline = fpi.readline() nextline = fpi.readline()
if not nextline: break if not nextline: break
line = line + nextline line = line + nextline
tmp = string.strip(line) tmp = line.strip()
if tmp[:1] != '#': if tmp[:1] != '#':
if ok: fpo.write(line) if ok: fpo.write(line)
continue continue
tmp = string.strip(tmp[1:]) tmp = tmp[1:].strip()
words = string.split(tmp) words = tmp.split()
keyword = words[0] keyword = words[0]
if keyword not in keywords: if keyword not in keywords:
if ok: fpo.write(line) if ok: fpo.write(line)
......
...@@ -24,7 +24,7 @@ from their output. ...@@ -24,7 +24,7 @@ from their output.
""" """
import os, sys, getopt, string, re import os, sys, getopt, re
sep1 = '='*77 + '\n' # file separator sep1 = '='*77 + '\n' # file separator
sep2 = '-'*28 + '\n' # revision separator sep2 = '-'*28 + '\n' # revision separator
...@@ -84,7 +84,7 @@ def digest_chunk(chunk): ...@@ -84,7 +84,7 @@ def digest_chunk(chunk):
keylen = len(key) keylen = len(key)
for line in lines: for line in lines:
if line[:keylen] == key: if line[:keylen] == key:
working_file = string.strip(line[keylen:]) working_file = line[keylen:].strip()
break break
else: else:
working_file = None working_file = None
...@@ -93,7 +93,7 @@ def digest_chunk(chunk): ...@@ -93,7 +93,7 @@ def digest_chunk(chunk):
revline = lines[0] revline = lines[0]
dateline = lines[1] dateline = lines[1]
text = lines[2:] text = lines[2:]
words = string.split(dateline) words = dateline.split()
author = None author = None
if len(words) >= 3 and words[0] == 'date:': if len(words) >= 3 and words[0] == 'date:':
dateword = words[1] dateword = words[1]
...@@ -108,7 +108,7 @@ def digest_chunk(chunk): ...@@ -108,7 +108,7 @@ def digest_chunk(chunk):
else: else:
date = None date = None
text.insert(0, revline) text.insert(0, revline)
words = string.split(revline) words = revline.split()
if len(words) >= 2 and words[0] == 'revision': if len(words) >= 2 and words[0] == 'revision':
rev = words[1] rev = words[1]
else: else:
......
"""mailerdaemon - classes to parse mailer-daemon messages""" """mailerdaemon - classes to parse mailer-daemon messages"""
import string
import rfc822 import rfc822
import calendar import calendar
import re import re
...@@ -18,9 +17,9 @@ class ErrorMessage(rfc822.Message): ...@@ -18,9 +17,9 @@ class ErrorMessage(rfc822.Message):
sub = self.getheader('Subject') sub = self.getheader('Subject')
if not sub: if not sub:
return 0 return 0
sub = string.lower(sub) sub = sub.lower()
if sub[:12] == 'waiting mail': return 1 if sub.startswith('waiting mail'): return 1
if string.find(sub, 'warning') >= 0: return 1 if 'warning' in sub: return 1
self.sub = sub self.sub = sub
return 0 return 0
...@@ -132,10 +131,10 @@ def emparse_list(fp, sub): ...@@ -132,10 +131,10 @@ def emparse_list(fp, sub):
if type(regexp) is type(''): if type(regexp) is type(''):
for i in range(len(emails)-1,-1,-1): for i in range(len(emails)-1,-1,-1):
email = emails[i] email = emails[i]
exp = re.compile(string.join(string.split(regexp, '<>'), re.escape(email)), re.MULTILINE) exp = re.compile(re.escape(email).join(regexp.split('<>')), re.MULTILINE)
res = exp.search(data) res = exp.search(data)
if res is not None: if res is not None:
errors.append(string.join(string.split(string.strip(email)+': '+res.group('reason')))) errors.append(' '.join((email.strip()+': '+res.group('reason')).split()))
del emails[i] del emails[i]
continue continue
res = regexp.search(data) res = regexp.search(data)
...@@ -143,14 +142,14 @@ def emparse_list(fp, sub): ...@@ -143,14 +142,14 @@ def emparse_list(fp, sub):
reason = res.group('reason') reason = res.group('reason')
break break
for email in emails: for email in emails:
errors.append(string.join(string.split(string.strip(email)+': '+reason))) errors.append(' '.join((email.strip()+': '+reason).split()))
return errors return errors
EMPARSERS = [emparse_list, ] EMPARSERS = [emparse_list, ]
def sort_numeric(a, b): def sort_numeric(a, b):
a = string.atoi(a) a = int(a)
b = string.atoi(b) b = int(b)
if a < b: return -1 if a < b: return -1
elif a > b: return 1 elif a > b: return 1
else: return 0 else: return 0
......
...@@ -30,7 +30,6 @@ import sys ...@@ -30,7 +30,6 @@ import sys
import regex import regex
import os import os
from stat import * from stat import *
import string
err = sys.stderr.write err = sys.stderr.write
dbg = err dbg = err
...@@ -101,7 +100,7 @@ def fix(filename): ...@@ -101,7 +100,7 @@ def fix(filename):
return 1 return 1
if lineno == 1 and g is None and line[:2] == '#!': if lineno == 1 and g is None and line[:2] == '#!':
# Check for non-Python scripts # Check for non-Python scripts
words = string.split(line[2:]) words = line[2:].split()
if words and regex.search('[pP]ython', words[0]) < 0: if words and regex.search('[pP]ython', words[0]) < 0:
msg = filename + ': ' + words[0] msg = filename + ': ' + words[0]
msg = msg + ' script; not fixed\n' msg = msg + ' script; not fixed\n'
......
...@@ -34,7 +34,7 @@ Even if this isn't the default output of your nm, there is generally an ...@@ -34,7 +34,7 @@ Even if this isn't the default output of your nm, there is generally an
option to produce this format (since it is the original v7 Unix format). option to produce this format (since it is the original v7 Unix format).
""" """
import os,re,string,sys import os,re,sys
PYTHONLIB = 'libpython'+sys.version[:3]+'.a' PYTHONLIB = 'libpython'+sys.version[:3]+'.a'
PC_PYTHONLIB = 'Python'+sys.version[0]+sys.version[2]+'.dll' PC_PYTHONLIB = 'Python'+sys.version[0]+sys.version[2]+'.dll'
...@@ -43,12 +43,12 @@ NM = 'nm -p -g %s' # For Linux, use "nm -g %s" ...@@ -43,12 +43,12 @@ NM = 'nm -p -g %s' # For Linux, use "nm -g %s"
def symbols(lib=PYTHONLIB,types=('T','C','D')): def symbols(lib=PYTHONLIB,types=('T','C','D')):
lines = os.popen(NM % lib).readlines() lines = os.popen(NM % lib).readlines()
lines = map(string.strip,lines) lines = [s.strip() for s in lines]
symbols = {} symbols = {}
for line in lines: for line in lines:
if len(line) == 0 or ':' in line: if len(line) == 0 or ':' in line:
continue continue
items = string.split(line) items = line.split()
if len(items) != 3: if len(items) != 3:
continue continue
address, type, name = items address, type, name = items
...@@ -69,7 +69,7 @@ def export_list(symbols): ...@@ -69,7 +69,7 @@ def export_list(symbols):
data.sort() data.sort()
data.append('') data.append('')
code.sort() code.sort()
return string.join(data,' DATA\n')+'\n'+string.join(code,'\n') return ' DATA\n'.join(data)+'\n'+'\n'.join(code)
# Definition file template # Definition file template
DEF_TEMPLATE = """\ DEF_TEMPLATE = """\
......
...@@ -20,7 +20,6 @@ ...@@ -20,7 +20,6 @@
import sys import sys
import string
import os import os
import getopt import getopt
import regex import regex
......
...@@ -23,7 +23,6 @@ import sys ...@@ -23,7 +23,6 @@ import sys
import regex import regex
import os import os
from stat import * from stat import *
import string
import getopt import getopt
err = sys.stderr.write err = sys.stderr.write
...@@ -140,9 +139,9 @@ def fix(filename): ...@@ -140,9 +139,9 @@ def fix(filename):
return 0 return 0
def fixline(line): def fixline(line):
if line[:2] != '#!': if not line.startswith('#!'):
return line return line
if string.find(line, "python") < 0: if "python" not in line:
return line return line
return '#! %s\n' % new_interpreter return '#! %s\n' % new_interpreter
......
...@@ -23,7 +23,6 @@ ...@@ -23,7 +23,6 @@
import sys import sys
import regex import regex
import os import os
import string
# Main program # Main program
...@@ -82,10 +81,10 @@ def process(filename, table): ...@@ -82,10 +81,10 @@ def process(filename, table):
elif m_from.match(line) >= 0: elif m_from.match(line) >= 0:
(a, b), (a1, b1) = m_from.regs[:2] (a, b), (a1, b1) = m_from.regs[:2]
else: continue else: continue
words = string.splitfields(line[a1:b1], ',') words = line[a1:b1].split(',')
# print '#', line, words # print '#', line, words
for word in words: for word in words:
word = string.strip(word) word = word.strip()
if word not in list: if word not in list:
list.append(word) list.append(word)
...@@ -152,7 +151,7 @@ def printresults(table): ...@@ -152,7 +151,7 @@ def printresults(table):
for mod in modules: for mod in modules:
list = table[mod] list = table[mod]
list.sort() list.sort()
print string.ljust(mod, maxlen), ':', print mod.ljust(maxlen), ':',
if mod in list: if mod in list:
print '(*)', print '(*)',
for ref in list: for ref in list:
......
...@@ -83,7 +83,6 @@ EXPANDTABS = 0 ...@@ -83,7 +83,6 @@ EXPANDTABS = 0
import os import os
import re import re
import string
import sys import sys
next = {} next = {}
...@@ -119,7 +118,7 @@ class PythonIndenter: ...@@ -119,7 +118,7 @@ class PythonIndenter:
def write(self, line): def write(self, line):
if self.expandtabs: if self.expandtabs:
self._write(string.expandtabs(line, self.tabsize)) self._write(line.expandtabs(self.tabsize))
else: else:
self._write(line) self._write(line)
# end if # end if
...@@ -270,7 +269,7 @@ class PythonIndenter: ...@@ -270,7 +269,7 @@ class PythonIndenter:
thiskw = '' thiskw = ''
# end if # end if
# end if # end if
indent = len(string.expandtabs(line[:i], self.tabsize)) indent = len(line[:i].expandtabs(self.tabsize))
while indent < current: while indent < current:
if firstkw: if firstkw:
if topid: if topid:
...@@ -370,7 +369,7 @@ class StringReader: ...@@ -370,7 +369,7 @@ class StringReader:
return r return r
# end def read # end def read
def readline(self): def readline(self):
i = string.find(self.buf, '\n', self.pos) i = self.buf.find('\n', self.pos)
return self.read(i + 1 - self.pos) return self.read(i + 1 - self.pos)
# end def readline # end def readline
def readlines(self): def readlines(self):
...@@ -514,9 +513,9 @@ def test(): ...@@ -514,9 +513,9 @@ def test():
# end if # end if
action = 'reformat' action = 'reformat'
elif o == '-s': elif o == '-s':
stepsize = string.atoi(a) stepsize = int(a)
elif o == '-t': elif o == '-t':
tabsize = string.atoi(a) tabsize = int(a)
elif o == '-e': elif o == '-e':
expandtabs = 1 expandtabs = 1
# end if # end if
......
...@@ -7,7 +7,6 @@ Usage: rgrep [-i] pattern file ...@@ -7,7 +7,6 @@ Usage: rgrep [-i] pattern file
import sys import sys
import re import re
import string
import getopt import getopt
def main(): def main():
...@@ -38,7 +37,7 @@ def main(): ...@@ -38,7 +37,7 @@ def main():
pos = pos - size pos = pos - size
f.seek(pos) f.seek(pos)
buffer = f.read(size) buffer = f.read(size)
lines = string.split(buffer, "\n") lines = buffer.split("\n")
del buffer del buffer
if leftover is None: if leftover is None:
if not lines[-1]: if not lines[-1]:
......
...@@ -16,7 +16,6 @@ file ... : files to sum; '-' or no files means stdin ...@@ -16,7 +16,6 @@ file ... : files to sum; '-' or no files means stdin
""" % bufsize """ % bufsize
import sys import sys
import string
import os import os
import md5 import md5
import regsub import regsub
...@@ -89,7 +88,7 @@ def main(args = sys.argv[1:], out = sys.stdout): ...@@ -89,7 +88,7 @@ def main(args = sys.argv[1:], out = sys.stdout):
if o == '-t': if o == '-t':
rmode = 'r' rmode = 'r'
if o == '-s': if o == '-s':
bufsize = string.atoi(a) bufsize = int(a)
if not args: args = ['-'] if not args: args = ['-']
return sum(args, out) return sum(args, out)
......
...@@ -83,7 +83,7 @@ Sample use, programmatically ...@@ -83,7 +83,7 @@ Sample use, programmatically
trace.print_results(show_missing=1) trace.print_results(show_missing=1)
""" """
import sys, os, string, tempfile, types, copy, operator, inspect, exceptions, marshal import sys, os, tempfile, types, copy, operator, inspect, exceptions, marshal
try: try:
import cPickle import cPickle
pickle = cPickle pickle = cPickle
...@@ -177,7 +177,7 @@ class Ignore: ...@@ -177,7 +177,7 @@ class Ignore:
# or # or
# d = "/usr/local.py" # d = "/usr/local.py"
# filename = "/usr/local.py" # filename = "/usr/local.py"
if string.find(filename, d + os.sep) == 0: if filename.startswith(d + os.sep):
self._ignore[modulename] = 1 self._ignore[modulename] = 1
return 1 return 1
...@@ -341,13 +341,12 @@ class CoverageResults: ...@@ -341,13 +341,12 @@ class CoverageResults:
# '#pragma: NO COVER' (it is possible to embed this into # '#pragma: NO COVER' (it is possible to embed this into
# the text as a non-comment; no easy fix) # the text as a non-comment; no easy fix)
if executable_linenos.has_key(i+1) and \ if executable_linenos.has_key(i+1) and \
string.find(lines[i], lines[i].find(' '.join(['#pragma', 'NO COVER'])) == -1:
string.join(['#pragma', 'NO COVER'])) == -1:
outfile.write('>>>>>> ') outfile.write('>>>>>> ')
else: else:
outfile.write(' '*7) outfile.write(' '*7)
n_lines = n_lines + 1 n_lines = n_lines + 1
outfile.write(string.expandtabs(lines[i], 8)) outfile.write(lines[i].expandtabs(8))
outfile.close() outfile.close()
...@@ -675,16 +674,16 @@ def main(argv=None): ...@@ -675,16 +674,16 @@ def main(argv=None):
continue continue
if opt == "--ignore-dir": if opt == "--ignore-dir":
for s in string.split(val, os.pathsep): for s in val.split(os.pathsep):
s = os.path.expandvars(s) s = os.path.expandvars(s)
# should I also call expanduser? (after all, could use $HOME) # should I also call expanduser? (after all, could use $HOME)
s = string.replace(s, "$prefix", s = s.replace("$prefix",
os.path.join(sys.prefix, "lib", os.path.join(sys.prefix, "lib",
"python" + sys.version[:3])) "python" + sys.version[:3]))
s = string.replace(s, "$exec_prefix", s = s.replace("$exec_prefix",
os.path.join(sys.exec_prefix, "lib", os.path.join(sys.exec_prefix, "lib",
"python" + sys.version[:3])) "python" + sys.version[:3]))
s = os.path.normpath(s) s = os.path.normpath(s)
ignore_dirs.append(s) ignore_dirs.append(s)
continue continue
......
...@@ -23,7 +23,7 @@ entry in the master tree are synchronized. This means: ...@@ -23,7 +23,7 @@ entry in the master tree are synchronized. This means:
""" """
import os, sys, stat, string, getopt import os, sys, stat, getopt
# Interactivity options # Interactivity options
default_answer = "ask" default_answer = "ask"
...@@ -97,7 +97,7 @@ def process(slave, master): ...@@ -97,7 +97,7 @@ def process(slave, master):
if cvsdir: if cvsdir:
entries = os.path.join(cvsdir, "Entries") entries = os.path.join(cvsdir, "Entries")
for e in open(entries).readlines(): for e in open(entries).readlines():
words = string.split(e, '/') words = e.split('/')
if words[0] == '' and words[1:]: if words[0] == '' and words[1:]:
name = words[1] name = words[1]
s = os.path.join(slave, name) s = os.path.join(slave, name)
...@@ -188,10 +188,10 @@ def copy(src, dst, rmode="rb", wmode="wb", answer='ask'): ...@@ -188,10 +188,10 @@ def copy(src, dst, rmode="rb", wmode="wb", answer='ask'):
g.close() g.close()
def okay(prompt, answer='ask'): def okay(prompt, answer='ask'):
answer = string.lower(string.strip(answer)) answer = answer.strip().lower()
if not answer or answer[0] not in 'ny': if not answer or answer[0] not in 'ny':
answer = raw_input(prompt) answer = raw_input(prompt)
answer = string.lower(string.strip(answer)) answer = answer.strip().lower()
if not answer: if not answer:
answer = default_answer answer = default_answer
if answer[:1] == 'y': if answer[:1] == 'y':
......
...@@ -4,7 +4,6 @@ ...@@ -4,7 +4,6 @@
import os import os
import sys import sys
import string
import getopt import getopt
def main(): def main():
...@@ -32,7 +31,7 @@ def process(file, tabsize): ...@@ -32,7 +31,7 @@ def process(file, tabsize):
except IOError, msg: except IOError, msg:
print "%s: I/O error: %s" % (`file`, str(msg)) print "%s: I/O error: %s" % (`file`, str(msg))
return return
newtext = string.expandtabs(text, tabsize) newtext = text.expandtabs(tabsize)
if newtext == text: if newtext == text:
return return
backup = file + "~" backup = file + "~"
......
...@@ -7,13 +7,13 @@ ...@@ -7,13 +7,13 @@
import sys import sys
if sys.path[0] in (".", ""): del sys.path[0] if sys.path[0] in (".", ""): del sys.path[0]
import sys, os, string import sys, os
from stat import * from stat import *
def msg(str): def msg(str):
sys.stderr.write(str + '\n') sys.stderr.write(str + '\n')
pathlist = string.splitfields(os.environ['PATH'], ':') pathlist = os.environ['PATH'].split(':')
sts = 0 sts = 0
longlist = '' longlist = ''
......
...@@ -9,7 +9,6 @@ import os ...@@ -9,7 +9,6 @@ import os
from stat import * from stat import *
import commands import commands
import fnmatch import fnmatch
import string
EXECMAGIC = '\001\140\000\010' EXECMAGIC = '\001\140\000\010'
...@@ -57,7 +56,7 @@ def setup(): ...@@ -57,7 +56,7 @@ def setup():
f = open('.xxcign', 'r') f = open('.xxcign', 'r')
except IOError: except IOError:
return return
ignore[:] = ignore + string.split(f.read()) ignore[:] = ignore + f.read().split()
def skipfile(file): def skipfile(file):
for p in ignore: for p in ignore:
......
...@@ -100,7 +100,7 @@ def makeunicodedata(unicode, trace): ...@@ -100,7 +100,7 @@ def makeunicodedata(unicode, trace):
record = unicode.table[char] record = unicode.table[char]
if record: if record:
if record[5]: if record[5]:
decomp = string.split(record[5]) decomp = record[5].split()
# prefix # prefix
if decomp[0][0] == "<": if decomp[0][0] == "<":
prefix = decomp.pop(0) prefix = decomp.pop(0)
...@@ -362,7 +362,7 @@ def makeunicodename(unicode, trace): ...@@ -362,7 +362,7 @@ def makeunicodename(unicode, trace):
# indicates the last character in an entire string) # indicates the last character in an entire string)
ww = w[:-1] + chr(ord(w[-1])+128) ww = w[:-1] + chr(ord(w[-1])+128)
# reuse string tails, when possible # reuse string tails, when possible
o = string.find(lexicon, ww) o = lexicon.find(ww)
if o < 0: if o < 0:
o = offset o = offset
lexicon = lexicon + ww lexicon = lexicon + ww
...@@ -442,7 +442,7 @@ def makeunicodename(unicode, trace): ...@@ -442,7 +442,7 @@ def makeunicodename(unicode, trace):
# load a unicode-data file from disk # load a unicode-data file from disk
import string, sys import sys
class UnicodeData: class UnicodeData:
...@@ -453,8 +453,8 @@ class UnicodeData: ...@@ -453,8 +453,8 @@ class UnicodeData:
s = file.readline() s = file.readline()
if not s: if not s:
break break
s = string.split(string.strip(s), ";") s = s.strip().split(";")
char = string.atoi(s[0], 16) char = int(s[0], 16)
table[char] = s table[char] = s
# expand first-last ranges (ignore surrogates and private use) # expand first-last ranges (ignore surrogates and private use)
...@@ -490,7 +490,7 @@ class UnicodeData: ...@@ -490,7 +490,7 @@ class UnicodeData:
def myhash(s, magic): def myhash(s, magic):
h = 0 h = 0
for c in map(ord, string.upper(s)): for c in map(ord, s.upper()):
h = (h * magic) + c h = (h * magic) + c
ix = h & 0xff000000 ix = h & 0xff000000
if ix: if ix:
...@@ -598,7 +598,7 @@ class Array: ...@@ -598,7 +598,7 @@ class Array:
s = " " + i s = " " + i
else: else:
s = s + i s = s + i
if string.strip(s): if s.strip():
file.write(s + "\n") file.write(s + "\n")
file.write("};\n\n") file.write("};\n\n")
......
...@@ -5,7 +5,6 @@ new versions available for any packages you have installed.""" ...@@ -5,7 +5,6 @@ new versions available for any packages you have installed."""
import os import os
import getopt import getopt
import sys import sys
import string
import pyversioncheck import pyversioncheck
CHECKNAME="_checkversion.py" CHECKNAME="_checkversion.py"
...@@ -43,7 +42,7 @@ def main(): ...@@ -43,7 +42,7 @@ def main():
sys.exit(1) sys.exit(1)
for o, a in options: for o, a in options:
if o == '-v': if o == '-v':
VERBOSE = string.atoi(a) VERBOSE = int(a)
if not arguments: if not arguments:
arguments = [sys.prefix] arguments = [sys.prefix]
for dir in arguments: for dir in arguments:
......
...@@ -3,7 +3,6 @@ import types ...@@ -3,7 +3,6 @@ import types
import rfc822 import rfc822
import urllib import urllib
import sys import sys
import string
# Verbose options # Verbose options
VERBOSE_SILENT=0 # Single-line reports per package VERBOSE_SILENT=0 # Single-line reports per package
...@@ -60,8 +59,8 @@ def _check1version(package, url, version, verbose=0): ...@@ -60,8 +59,8 @@ def _check1version(package, url, version, verbose=0):
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 = string.strip(string.lower(version)) version = version.lower().strip()
newversion = string.strip(string.lower(newversion)) 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
......
"""Assorted Tk-related subroutines used in Grail.""" """Assorted Tk-related subroutines used in Grail."""
import string
from types import * from types import *
from Tkinter import * from Tkinter import *
...@@ -335,7 +334,7 @@ def flatten(msg): ...@@ -335,7 +334,7 @@ def flatten(msg):
"""Turn a list or tuple into a single string -- recursively.""" """Turn a list or tuple into a single string -- recursively."""
t = type(msg) t = type(msg)
if t in (ListType, TupleType): if t in (ListType, TupleType):
msg = string.join(map(flatten, msg)) msg = ' '.join(map(flatten, msg))
elif t is ClassType: elif t is ClassType:
msg = msg.__name__ msg = msg.__name__
else: else:
...@@ -345,7 +344,7 @@ def flatten(msg): ...@@ -345,7 +344,7 @@ def flatten(msg):
def boolean(s): def boolean(s):
"""Test whether a string is a Tk boolean, without error checking.""" """Test whether a string is a Tk boolean, without error checking."""
if string.lower(s) in ('', '0', 'no', 'off', 'false'): return 0 if s.lower() in ('', '0', 'no', 'off', 'false'): return 0
else: return 1 else: return 1
......
...@@ -60,7 +60,6 @@ XXX The multipanel user interface is clumsy. ...@@ -60,7 +60,6 @@ XXX The multipanel user interface is clumsy.
import sys import sys
import getopt import getopt
import string
from Tkinter import * from Tkinter import *
import tktools import tktools
import webchecker import webchecker
...@@ -86,7 +85,7 @@ def main(): ...@@ -86,7 +85,7 @@ def main():
extra_roots = [] extra_roots = []
for o, a in opts: for o, a in opts:
if o == '-m': if o == '-m':
webchecker.maxpage = string.atoi(a) webchecker.maxpage = int(a)
if o == '-q': if o == '-q':
webchecker.verbose = 0 webchecker.verbose = 0
if o == '-v': if o == '-v':
...@@ -169,7 +168,7 @@ class CheckerWindow(webchecker.Checker): ...@@ -169,7 +168,7 @@ class CheckerWindow(webchecker.Checker):
self.root_seed = None self.root_seed = None
webchecker.Checker.__init__(self) webchecker.Checker.__init__(self)
if root: if root:
root = string.strip(str(root)) root = str(root).strip()
if root: if root:
self.suggestroot(root) self.suggestroot(root)
self.newstatus() self.newstatus()
...@@ -189,7 +188,7 @@ class CheckerWindow(webchecker.Checker): ...@@ -189,7 +188,7 @@ class CheckerWindow(webchecker.Checker):
def enterroot(self, event=None): def enterroot(self, event=None):
root = self.__rootentry.get() root = self.__rootentry.get()
root = string.strip(root) root = root.strip()
if root: if root:
self.__checking.config(text="Adding root "+root) self.__checking.config(text="Adding root "+root)
self.__checking.update_idletasks() self.__checking.update_idletasks()
...@@ -353,7 +352,7 @@ class ListPanel: ...@@ -353,7 +352,7 @@ class ListPanel:
def selectedindices(self): def selectedindices(self):
l = self.list.curselection() l = self.list.curselection()
if not l: return [] if not l: return []
return map(string.atoi, l) return map(int, l)
def insert(self, url): def insert(self, url):
if url not in self.items: if url not in self.items:
......
...@@ -109,7 +109,6 @@ __version__ = "$Revision$" ...@@ -109,7 +109,6 @@ __version__ = "$Revision$"
import sys import sys
import os import os
from types import * from types import *
import string
import StringIO import StringIO
import getopt import getopt
import pickle import pickle
...@@ -124,7 +123,7 @@ import robotparser ...@@ -124,7 +123,7 @@ import robotparser
# Extract real version number if necessary # Extract real version number if necessary
if __version__[0] == '$': if __version__[0] == '$':
_v = string.split(__version__) _v = __version__.split()
if len(_v) == 3: if len(_v) == 3:
__version__ = _v[1] __version__ = _v[1]
...@@ -170,13 +169,13 @@ def main(): ...@@ -170,13 +169,13 @@ def main():
if o == '-d': if o == '-d':
dumpfile = a dumpfile = a
if o == '-m': if o == '-m':
maxpage = string.atoi(a) maxpage = int(a)
if o == '-n': if o == '-n':
norun = 1 norun = 1
if o == '-q': if o == '-q':
verbose = 0 verbose = 0
if o == '-r': if o == '-r':
roundsize = string.atoi(a) roundsize = int(a)
if o == '-t': if o == '-t':
extra_roots.append(a) extra_roots.append(a)
if o == '-a': if o == '-a':
...@@ -248,7 +247,7 @@ def load_pickle(dumpfile=DUMPFILE, verbose=VERBOSE): ...@@ -248,7 +247,7 @@ def load_pickle(dumpfile=DUMPFILE, verbose=VERBOSE):
f.close() f.close()
if verbose > 0: if verbose > 0:
print "Done." print "Done."
print "Root:", string.join(c.roots, "\n ") print "Root:", "\n ".join(c.roots)
return c return c
...@@ -316,7 +315,7 @@ class Checker: ...@@ -316,7 +315,7 @@ class Checker:
troot = root troot = root
scheme, netloc, path, params, query, fragment = \ scheme, netloc, path, params, query, fragment = \
urlparse.urlparse(root) urlparse.urlparse(root)
i = string.rfind(path, "/") + 1 i = path.rfind("/") + 1
if 0 < i < len(path): if 0 < i < len(path):
path = path[:i] path = path[:i]
troot = urlparse.urlunparse((scheme, netloc, path, troot = urlparse.urlunparse((scheme, netloc, path,
...@@ -544,7 +543,7 @@ class Checker: ...@@ -544,7 +543,7 @@ class Checker:
def checkforhtml(self, info, url): def checkforhtml(self, info, url):
if info.has_key('content-type'): if info.has_key('content-type'):
ctype = string.lower(cgi.parse_header(info['content-type'])[0]) ctype = cgi.parse_header(info['content-type'])[0].lower()
else: else:
if url[-1:] == "/": if url[-1:] == "/":
return 1 return 1
...@@ -809,7 +808,7 @@ class MyHTMLParser(sgmllib.SGMLParser): ...@@ -809,7 +808,7 @@ class MyHTMLParser(sgmllib.SGMLParser):
def do_link(self, attributes): def do_link(self, attributes):
for name, value in attributes: for name, value in attributes:
if name == "rel": if name == "rel":
parts = string.split(string.lower(value)) parts = value.lower().split()
if ( parts == ["stylesheet"] if ( parts == ["stylesheet"]
or parts == ["alternate", "stylesheet"]): or parts == ["alternate", "stylesheet"]):
self.link_attr(attributes, "href") self.link_attr(attributes, "href")
...@@ -836,13 +835,13 @@ class MyHTMLParser(sgmllib.SGMLParser): ...@@ -836,13 +835,13 @@ class MyHTMLParser(sgmllib.SGMLParser):
def link_attr(self, attributes, *args): def link_attr(self, attributes, *args):
for name, value in attributes: for name, value in attributes:
if name in args: if name in args:
if value: value = string.strip(value) if value: value = value.strip()
if value: self.links[value] = None if value: self.links[value] = None
def do_base(self, attributes): def do_base(self, attributes):
for name, value in attributes: for name, value in attributes:
if name == 'href': if name == 'href':
if value: value = string.strip(value) if value: value = value.strip()
if value: if value:
if self.checker: if self.checker:
self.checker.note(1, " Base %s", value) self.checker.note(1, " Base %s", value)
......
...@@ -6,7 +6,6 @@ __version__ = "$Revision$" ...@@ -6,7 +6,6 @@ __version__ = "$Revision$"
import os import os
import sys import sys
import string
import urllib import urllib
import getopt import getopt
...@@ -14,7 +13,7 @@ import webchecker ...@@ -14,7 +13,7 @@ import webchecker
# Extract real version number if necessary # Extract real version number if necessary
if __version__[0] == '$': if __version__[0] == '$':
_v = string.split(__version__) _v = __version__.split()
if len(_v) == 3: if len(_v) == 3:
__version__ = _v[1] __version__ = _v[1]
...@@ -90,14 +89,14 @@ class Sucker(webchecker.Checker): ...@@ -90,14 +89,14 @@ class Sucker(webchecker.Checker):
def savefilename(self, url): def savefilename(self, url):
type, rest = urllib.splittype(url) type, rest = urllib.splittype(url)
host, path = urllib.splithost(rest) host, path = urllib.splithost(rest)
while path[:1] == "/": path = path[1:] path = path.lstrip("/")
user, host = urllib.splituser(host) user, host = urllib.splituser(host)
host, port = urllib.splitnport(host) host, port = urllib.splitnport(host)
host = string.lower(host) host = host.lower()
if not path or path[-1] == "/": if not path or path[-1] == "/":
path = path + "index.html" path = path + "index.html"
if os.sep != "/": if os.sep != "/":
path = string.join(string.split(path, "/"), os.sep) path = os.sep.join(path.split("/"))
if os.name == "mac": if os.name == "mac":
path = os.sep + path path = os.sep + path
path = os.path.join(host, path) path = os.path.join(host, path)
......
...@@ -8,7 +8,6 @@ their respective text boxes, click GO or hit return, and presto. ...@@ -8,7 +8,6 @@ their respective text boxes, click GO or hit return, and presto.
from Tkinter import * from Tkinter import *
import Tkinter import Tkinter
import string
import websucker import websucker
import sys import sys
import os import os
...@@ -150,13 +149,13 @@ class App: ...@@ -150,13 +149,13 @@ class App:
return return
self.url_entry.selection_range(0, END) self.url_entry.selection_range(0, END)
url = self.url_entry.get() url = self.url_entry.get()
url = string.strip(url) url = url.strip()
if not url: if not url:
self.top.bell() self.top.bell()
self.message("[Error: No URL entered]") self.message("[Error: No URL entered]")
return return
self.rooturl = url self.rooturl = url
dir = string.strip(self.dir_entry.get()) dir = self.dir_entry.get().strip()
if not dir: if not dir:
self.sucker.savedir = None self.sucker.savedir = None
else: else:
...@@ -184,7 +183,7 @@ class App: ...@@ -184,7 +183,7 @@ class App:
text = self.top.selection_get(selection=t) text = self.top.selection_get(selection=t)
except TclError: except TclError:
continue continue
text = string.strip(text) text = text.strip()
if text: if text:
break break
if not text: if not text:
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment