Commit 9d72bb45 authored by Neal Norwitz's avatar Neal Norwitz

Remove functions in string module that are also string methods. Also remove:

 * all calls to functions in the string module (except maketrans)
 * everything from stropmodule except for maketrans() which is still used
parent ff113349
...@@ -307,15 +307,14 @@ _Translator = { ...@@ -307,15 +307,14 @@ _Translator = {
_idmap = ''.join(chr(x) for x in xrange(256)) _idmap = ''.join(chr(x) for x in xrange(256))
def _quote(str, LegalChars=_LegalChars, def _quote(str, LegalChars=_LegalChars, idmap=_idmap):
idmap=_idmap, translate=string.translate):
# #
# If the string does not need to be double-quoted, # If the string does not need to be double-quoted,
# then just return the string. Otherwise, surround # then just return the string. Otherwise, surround
# the string in doublequotes and precede quote (with a \) # the string in doublequotes and precede quote (with a \)
# special characters. # special characters.
# #
if "" == translate(str, idmap, LegalChars): if "" == str.translate(idmap, LegalChars):
return str return str
else: else:
return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"' return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
...@@ -440,14 +439,12 @@ class Morsel(dict): ...@@ -440,14 +439,12 @@ class Morsel(dict):
return K.lower() in self._reserved return K.lower() in self._reserved
# end isReservedKey # end isReservedKey
def set(self, key, val, coded_val, def set(self, key, val, coded_val, LegalChars=_LegalChars, idmap=_idmap):
LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
# First we verify that the key isn't a reserved word # First we verify that the key isn't a reserved word
# Second we make sure it only contains legal characters # Second we make sure it only contains legal characters
if key.lower() in self._reserved: if key.lower() in self._reserved:
raise CookieError("Attempt to set a reserved key: %s" % key) raise CookieError("Attempt to set a reserved key: %s" % key)
if "" != translate(key, idmap, LegalChars): if "" != key.translate(idmap, LegalChars):
raise CookieError("Illegal key value: %s" % key) raise CookieError("Illegal key value: %s" % key)
# It's a good key, so save it. # It's a good key, so save it.
......
...@@ -21,15 +21,14 @@ server.serve_forever() ...@@ -21,15 +21,14 @@ server.serve_forever()
class MyFuncs: class MyFuncs:
def __init__(self): def __init__(self):
# make all of the string functions available through # make all of the sys functions available through sys.func_name
# string.func_name import sys
import string self.sys = sys
self.string = string
def _listMethods(self): def _listMethods(self):
# implement this method so that system.listMethods # implement this method so that system.listMethods
# knows to advertise the strings methods # knows to advertise the sys methods
return list_public_methods(self) + \ return list_public_methods(self) + \
['string.' + method for method in list_public_methods(self.string)] ['sys.' + method for method in list_public_methods(self.sys)]
def pow(self, x, y): return pow(x, y) def pow(self, x, y): return pow(x, y)
def add(self, x, y) : return x + y def add(self, x, y) : return x + y
......
...@@ -29,7 +29,6 @@ From: ...@@ -29,7 +29,6 @@ From:
""" """
import errno import errno
import string
class DBRecIO: class DBRecIO:
def __init__(self, db, key, txn=None): def __init__(self, db, key, txn=None):
...@@ -83,9 +82,9 @@ class DBRecIO: ...@@ -83,9 +82,9 @@ class DBRecIO:
if self.closed: if self.closed:
raise ValueError, "I/O operation on closed file" raise ValueError, "I/O operation on closed file"
if self.buflist: if self.buflist:
self.buf = self.buf + string.joinfields(self.buflist, '') self.buf = self.buf + ''.join(self.buflist)
self.buflist = [] self.buflist = []
i = string.find(self.buf, '\n', self.pos) i = self.buf.find('\n', self.pos)
if i < 0: if i < 0:
newpos = self.len newpos = self.len
else: else:
...@@ -134,7 +133,7 @@ class DBRecIO: ...@@ -134,7 +133,7 @@ class DBRecIO:
self.pos = newpos self.pos = newpos
def writelines(self, list): def writelines(self, list):
self.write(string.joinfields(list, '')) self.write(''.join(list))
def flush(self): def flush(self):
if self.closed: if self.closed:
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
TestCases for DB.associate. TestCases for DB.associate.
""" """
import sys, os, string import sys, os
import tempfile import tempfile
import time import time
from pprint import pprint from pprint import pprint
...@@ -177,7 +177,7 @@ class AssociateTestCase(unittest.TestCase): ...@@ -177,7 +177,7 @@ class AssociateTestCase(unittest.TestCase):
for key, value in musicdata.items(): for key, value in musicdata.items():
if type(self.keytype) == type(''): if type(self.keytype) == type(''):
key = "%02d" % key key = "%02d" % key
d.put(key, string.join(value, '|'), txn=txn) d.put(key, '|'.join(value), txn=txn)
def createDB(self, txn=None): def createDB(self, txn=None):
self.cur = None self.cur = None
...@@ -263,7 +263,7 @@ class AssociateTestCase(unittest.TestCase): ...@@ -263,7 +263,7 @@ class AssociateTestCase(unittest.TestCase):
rec = self.cur.first() rec = self.cur.first()
while rec is not None: while rec is not None:
if type(self.keytype) == type(''): if type(self.keytype) == type(''):
assert string.atoi(rec[0]) # for primary db, key is a number assert int(rec[0]) # for primary db, key is a number
else: else:
assert rec[0] and type(rec[0]) == type(0) assert rec[0] and type(rec[0]) == type(0)
count = count + 1 count = count + 1
...@@ -305,7 +305,7 @@ class AssociateTestCase(unittest.TestCase): ...@@ -305,7 +305,7 @@ class AssociateTestCase(unittest.TestCase):
assert type(priData) == type("") assert type(priData) == type("")
if verbose: if verbose:
print('getGenre key: %r data: %r' % (priKey, priData)) print('getGenre key: %r data: %r' % (priKey, priData))
genre = string.split(priData, '|')[2] genre = priData.split('|')[2]
if genre == 'Blues': if genre == 'Blues':
return db.DB_DONOTINDEX return db.DB_DONOTINDEX
else: else:
...@@ -427,13 +427,13 @@ class ThreadedAssociateTestCase(AssociateTestCase): ...@@ -427,13 +427,13 @@ class ThreadedAssociateTestCase(AssociateTestCase):
for key, value in musicdata.items(): for key, value in musicdata.items():
if type(self.keytype) == type(''): if type(self.keytype) == type(''):
key = "%02d" % key key = "%02d" % key
d.put(key, string.join(value, '|')) d.put(key, '|'.join(value))
def writer2(self, d): def writer2(self, d):
for x in range(100, 600): for x in range(100, 600):
key = 'z%2d' % x key = 'z%2d' % x
value = [key] * 4 value = [key] * 4
d.put(key, string.join(value, '|')) d.put(key, '|'.join(value))
class ThreadedAssociateHashTestCase(ShelveAssociateTestCase): class ThreadedAssociateHashTestCase(ShelveAssociateTestCase):
......
...@@ -3,7 +3,7 @@ Test cases adapted from the test_bsddb.py module in Python's ...@@ -3,7 +3,7 @@ Test cases adapted from the test_bsddb.py module in Python's
regression test suite. regression test suite.
""" """
import sys, os, string import sys, os
import unittest import unittest
import tempfile import tempfile
...@@ -35,7 +35,7 @@ class CompatibilityTestCase(unittest.TestCase): ...@@ -35,7 +35,7 @@ class CompatibilityTestCase(unittest.TestCase):
self.do_bthash_test(hashopen, 'hashopen') self.do_bthash_test(hashopen, 'hashopen')
def test03_rnopen(self): def test03_rnopen(self):
data = string.split("The quick brown fox jumped over the lazy dog.") data = "The quick brown fox jumped over the lazy dog.".split()
if verbose: if verbose:
print("\nTesting: rnopen") print("\nTesting: rnopen")
......
import sys, os, string import sys, os
import unittest import unittest
import glob import glob
import tempfile import tempfile
...@@ -38,7 +38,7 @@ class dbobjTestCase(unittest.TestCase): ...@@ -38,7 +38,7 @@ class dbobjTestCase(unittest.TestCase):
class TestDBEnv(dbobj.DBEnv): pass class TestDBEnv(dbobj.DBEnv): pass
class TestDB(dbobj.DB): class TestDB(dbobj.DB):
def put(self, key, *args, **kwargs): def put(self, key, *args, **kwargs):
key = string.upper(key) key = key.upper()
# call our parent classes put method with an upper case key # call our parent classes put method with an upper case key
return dbobj.DB.put(self, key, *args, **kwargs) return dbobj.DB.put(self, key, *args, **kwargs)
self.env = TestDBEnv() self.env = TestDBEnv()
......
"""TestCases for using the DB.join and DBCursor.join_item methods. """TestCases for using the DB.join and DBCursor.join_item methods.
""" """
import sys, os, string import sys, os
import tempfile import tempfile
import time import time
from pprint import pprint from pprint import pprint
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
TestCases for testing the locking sub-system. TestCases for testing the locking sub-system.
""" """
import sys, os, string import sys, os
import tempfile import tempfile
import time import time
from pprint import pprint from pprint import pprint
......
import sys, os, string import sys, os
import pickle import pickle
try: try:
import cPickle import cPickle
......
...@@ -8,7 +8,7 @@ in the distutils.command package. ...@@ -8,7 +8,7 @@ in the distutils.command package.
__revision__ = "$Id$" __revision__ = "$Id$"
import sys, os, string, re import sys, os, re
from types import * from types import *
from distutils.errors import * from distutils.errors import *
from distutils import util, dir_util, file_util, archive_util, dep_util from distutils import util, dir_util, file_util, archive_util, dep_util
...@@ -166,7 +166,7 @@ class Command: ...@@ -166,7 +166,7 @@ class Command:
print(indent + header) print(indent + header)
indent = indent + " " indent = indent + " "
for (option, _, _) in self.user_options: for (option, _, _) in self.user_options:
option = string.translate(option, longopt_xlate) option = option.translate(longopt_xlate)
if option[-1] == "=": if option[-1] == "=":
option = option[:-1] option = option[:-1]
value = getattr(self, option) value = getattr(self, option)
...@@ -415,7 +415,7 @@ class Command: ...@@ -415,7 +415,7 @@ class Command:
""" """
if exec_msg is None: if exec_msg is None:
exec_msg = "generating %s from %s" % \ exec_msg = "generating %s from %s" % \
(outfile, string.join(infiles, ', ')) (outfile, ', '.join(infiles))
if skip_msg is None: if skip_msg is None:
skip_msg = "skipping %s (inputs unchanged)" % outfile skip_msg = "skipping %s (inputs unchanged)" % outfile
......
...@@ -7,7 +7,7 @@ distribution).""" ...@@ -7,7 +7,7 @@ distribution)."""
__revision__ = "$Id$" __revision__ = "$Id$"
import os, string import os
from types import * from types import *
from distutils.core import Command from distutils.core import Command
from distutils.errors import * from distutils.errors import *
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
Implements the bdist_msi command. Implements the bdist_msi command.
""" """
import sys, os, string import sys, os
from distutils.core import Command from distutils.core import Command
from distutils.util import get_platform from distutils.util import get_platform
from distutils.dir_util import remove_tree from distutils.dir_util import remove_tree
......
...@@ -7,7 +7,7 @@ distributions).""" ...@@ -7,7 +7,7 @@ distributions)."""
__revision__ = "$Id$" __revision__ = "$Id$"
import sys, os, string import sys, os
import glob import glob
from types import * from types import *
from distutils.core import Command from distutils.core import Command
...@@ -354,7 +354,7 @@ class bdist_rpm (Command): ...@@ -354,7 +354,7 @@ class bdist_rpm (Command):
line = out.readline() line = out.readline()
if not line: if not line:
break break
l = string.split(string.strip(line)) l = line.strip().split()
assert(len(l) == 2) assert(len(l) == 2)
binary_rpms.append(l[1]) binary_rpms.append(l[1])
# The source rpm is named after the first entry in the spec file # The source rpm is named after the first entry in the spec file
...@@ -437,9 +437,9 @@ class bdist_rpm (Command): ...@@ -437,9 +437,9 @@ class bdist_rpm (Command):
'Conflicts', 'Conflicts',
'Obsoletes', 'Obsoletes',
): ):
val = getattr(self, string.lower(field)) val = getattr(self, field.lower())
if type(val) is ListType: if type(val) is ListType:
spec_file.append('%s: %s' % (field, string.join(val))) spec_file.append('%s: %s' % (field, ' '.join(val)))
elif val is not None: elif val is not None:
spec_file.append('%s: %s' % (field, val)) spec_file.append('%s: %s' % (field, val))
...@@ -452,7 +452,7 @@ class bdist_rpm (Command): ...@@ -452,7 +452,7 @@ class bdist_rpm (Command):
if self.build_requires: if self.build_requires:
spec_file.append('BuildRequires: ' + spec_file.append('BuildRequires: ' +
string.join(self.build_requires)) ' '.join(self.build_requires))
if self.icon: if self.icon:
spec_file.append('Icon: ' + os.path.basename(self.icon)) spec_file.append('Icon: ' + os.path.basename(self.icon))
...@@ -513,7 +513,7 @@ class bdist_rpm (Command): ...@@ -513,7 +513,7 @@ class bdist_rpm (Command):
'', '',
'%' + rpm_opt,]) '%' + rpm_opt,])
if val: if val:
spec_file.extend(string.split(open(val, 'r').read(), '\n')) spec_file.extend(open(val, 'r').read().split('\n'))
else: else:
spec_file.append(default) spec_file.append(default)
...@@ -526,7 +526,7 @@ class bdist_rpm (Command): ...@@ -526,7 +526,7 @@ class bdist_rpm (Command):
]) ])
if self.doc_files: if self.doc_files:
spec_file.append('%doc ' + string.join(self.doc_files)) spec_file.append('%doc ' + ' '.join(self.doc_files))
if self.changelog: if self.changelog:
spec_file.extend([ spec_file.extend([
...@@ -544,8 +544,8 @@ class bdist_rpm (Command): ...@@ -544,8 +544,8 @@ class bdist_rpm (Command):
if not changelog: if not changelog:
return changelog return changelog
new_changelog = [] new_changelog = []
for line in string.split(string.strip(changelog), '\n'): for line in changelog.strip().split('\n'):
line = string.strip(line) line = line.strip()
if line[0] == '*': if line[0] == '*':
new_changelog.extend(['', line]) new_changelog.extend(['', line])
elif line[0] == '-': elif line[0] == '-':
......
...@@ -7,7 +7,7 @@ exe-program.""" ...@@ -7,7 +7,7 @@ exe-program."""
__revision__ = "$Id$" __revision__ = "$Id$"
import sys, os, string import sys, os
from distutils.core import Command from distutils.core import Command
from distutils.util import get_platform from distutils.util import get_platform
from distutils.dir_util import create_tree, remove_tree from distutils.dir_util import create_tree, remove_tree
...@@ -135,7 +135,7 @@ class bdist_wininst (Command): ...@@ -135,7 +135,7 @@ class bdist_wininst (Command):
# Use a custom scheme for the zip-file, because we have to decide # Use a custom scheme for the zip-file, because we have to decide
# at installation time which scheme to use. # at installation time which scheme to use.
for key in ('purelib', 'platlib', 'headers', 'scripts', 'data'): for key in ('purelib', 'platlib', 'headers', 'scripts', 'data'):
value = string.upper(key) value = key.upper()
if key == 'headers': if key == 'headers':
value = value + '/Include/$dist_name' value = value + '/Include/$dist_name'
setattr(install, setattr(install,
...@@ -192,14 +192,14 @@ class bdist_wininst (Command): ...@@ -192,14 +192,14 @@ class bdist_wininst (Command):
# Escape newline characters # Escape newline characters
def escape(s): def escape(s):
return string.replace(s, "\n", "\\n") return s.replace("\n", "\\n")
for name in ["author", "author_email", "description", "maintainer", for name in ["author", "author_email", "description", "maintainer",
"maintainer_email", "name", "url", "version"]: "maintainer_email", "name", "url", "version"]:
data = getattr(metadata, name, "") data = getattr(metadata, name, "")
if data: if data:
info = info + ("\n %s: %s" % \ info = info + ("\n %s: %s" % \
(string.capitalize(name), escape(data))) (name.capitalize(), escape(data)))
lines.append("%s=%s" % (name, escape(data))) lines.append("%s=%s" % (name, escape(data)))
# The [setup] section contains entries controlling # The [setup] section contains entries controlling
...@@ -220,7 +220,7 @@ class bdist_wininst (Command): ...@@ -220,7 +220,7 @@ class bdist_wininst (Command):
build_info = "Built %s with distutils-%s" % \ build_info = "Built %s with distutils-%s" % \
(time.ctime(time.time()), distutils.__version__) (time.ctime(time.time()), distutils.__version__)
lines.append("build_info=%s" % build_info) lines.append("build_info=%s" % build_info)
return string.join(lines, "\n") return "\n".join(lines)
# get_inidata() # get_inidata()
......
...@@ -18,7 +18,7 @@ __revision__ = "$Id$" ...@@ -18,7 +18,7 @@ __revision__ = "$Id$"
# two modules, mainly because a number of subtle details changed in the # two modules, mainly because a number of subtle details changed in the
# cut 'n paste. Sigh. # cut 'n paste. Sigh.
import os, string import os
from types import * from types import *
from distutils.core import Command from distutils.core import Command
from distutils.errors import * from distutils.errors import *
...@@ -93,8 +93,7 @@ class build_clib (Command): ...@@ -93,8 +93,7 @@ class build_clib (Command):
if self.include_dirs is None: if self.include_dirs is None:
self.include_dirs = self.distribution.include_dirs or [] self.include_dirs = self.distribution.include_dirs or []
if type(self.include_dirs) is StringType: if type(self.include_dirs) is StringType:
self.include_dirs = string.split(self.include_dirs, self.include_dirs = self.include_dirs.split(os.pathsep)
os.pathsep)
# XXX same as for build_ext -- what about 'self.define' and # XXX same as for build_ext -- what about 'self.define' and
# 'self.undef' ? # 'self.undef' ?
......
...@@ -8,7 +8,7 @@ extensions ASAP).""" ...@@ -8,7 +8,7 @@ extensions ASAP)."""
__revision__ = "$Id$" __revision__ = "$Id$"
import sys, os, string, re import sys, os, re
from types import * from types import *
from distutils.core import Command from distutils.core import Command
from distutils.errors import * from distutils.errors import *
...@@ -138,7 +138,7 @@ class build_ext (Command): ...@@ -138,7 +138,7 @@ class build_ext (Command):
if self.include_dirs is None: if self.include_dirs is None:
self.include_dirs = self.distribution.include_dirs or [] self.include_dirs = self.distribution.include_dirs or []
if type(self.include_dirs) is StringType: if type(self.include_dirs) is StringType:
self.include_dirs = string.split(self.include_dirs, os.pathsep) self.include_dirs = self.include_dirs.split(os.pathsep)
# Put the Python "system" include dir at the end, so that # Put the Python "system" include dir at the end, so that
# any local include dirs take precedence. # any local include dirs take precedence.
...@@ -156,12 +156,12 @@ class build_ext (Command): ...@@ -156,12 +156,12 @@ class build_ext (Command):
if self.library_dirs is None: if self.library_dirs is None:
self.library_dirs = [] self.library_dirs = []
elif type(self.library_dirs) is StringType: elif type(self.library_dirs) is StringType:
self.library_dirs = string.split(self.library_dirs, os.pathsep) self.library_dirs = self.library_dirs.split(os.pathsep)
if self.rpath is None: if self.rpath is None:
self.rpath = [] self.rpath = []
elif type(self.rpath) is StringType: elif type(self.rpath) is StringType:
self.rpath = string.split(self.rpath, os.pathsep) self.rpath = self.rpath.split(os.pathsep)
# for extensions under windows use different directories # for extensions under windows use different directories
# for Release and Debug builds. # for Release and Debug builds.
...@@ -186,7 +186,7 @@ class build_ext (Command): ...@@ -186,7 +186,7 @@ class build_ext (Command):
# for extensions under Cygwin and AtheOS Python's library directory must be # for extensions under Cygwin and AtheOS Python's library directory must be
# appended to library_dirs # appended to library_dirs
if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos': if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos':
if string.find(sys.executable, sys.exec_prefix) != -1: if sys.executable.find(sys.exec_prefix) != -1:
# building third party extensions # building third party extensions
self.library_dirs.append(os.path.join(sys.prefix, "lib", self.library_dirs.append(os.path.join(sys.prefix, "lib",
"python" + get_python_version(), "python" + get_python_version(),
...@@ -199,7 +199,7 @@ class build_ext (Command): ...@@ -199,7 +199,7 @@ class build_ext (Command):
# Python's library directory must be appended to library_dirs # Python's library directory must be appended to library_dirs
if (sys.platform.startswith('linux') or sys.platform.startswith('gnu')) \ if (sys.platform.startswith('linux') or sys.platform.startswith('gnu')) \
and sysconfig.get_config_var('Py_ENABLE_SHARED'): and sysconfig.get_config_var('Py_ENABLE_SHARED'):
if string.find(sys.executable, sys.exec_prefix) != -1: if sys.executable.find(sys.exec_prefix) != -1:
# building third party extensions # building third party extensions
self.library_dirs.append(sysconfig.get_config_var('LIBDIR')) self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
else: else:
...@@ -212,14 +212,14 @@ class build_ext (Command): ...@@ -212,14 +212,14 @@ class build_ext (Command):
# symbols can be separated with commas. # symbols can be separated with commas.
if self.define: if self.define:
defines = string.split(self.define, ',') defines = self.define.split(',')
self.define = map(lambda symbol: (symbol, '1'), defines) self.define = map(lambda symbol: (symbol, '1'), defines)
# The option for macros to undefine is also a string from the # The option for macros to undefine is also a string from the
# option parsing, but has to be a list. Multiple symbols can also # option parsing, but has to be a list. Multiple symbols can also
# be separated with commas here. # be separated with commas here.
if self.undef: if self.undef:
self.undef = string.split(self.undef, ',') self.undef = self.undef.split(',')
if self.swig_opts is None: if self.swig_opts is None:
self.swig_opts = [] self.swig_opts = []
...@@ -429,8 +429,8 @@ class build_ext (Command): ...@@ -429,8 +429,8 @@ class build_ext (Command):
# ignore build-lib -- put the compiled extension into # ignore build-lib -- put the compiled extension into
# the source tree along with pure Python modules # the source tree along with pure Python modules
modpath = string.split(fullname, '.') modpath = fullname.split('.')
package = string.join(modpath[0:-1], '.') package = '.'.join(modpath[0:-1])
base = modpath[-1] base = modpath[-1]
build_py = self.get_finalized_command('build_py') build_py = self.get_finalized_command('build_py')
...@@ -617,7 +617,7 @@ class build_ext (Command): ...@@ -617,7 +617,7 @@ class build_ext (Command):
""" """
from distutils.sysconfig import get_config_var from distutils.sysconfig import get_config_var
ext_path = string.split(ext_name, '.') ext_path = ext_name.split('.')
# OS/2 has an 8 character module (extension) limit :-( # OS/2 has an 8 character module (extension) limit :-(
if os.name == "os2": if os.name == "os2":
ext_path[len(ext_path) - 1] = ext_path[len(ext_path) - 1][:8] ext_path[len(ext_path) - 1] = ext_path[len(ext_path) - 1][:8]
...@@ -634,7 +634,7 @@ class build_ext (Command): ...@@ -634,7 +634,7 @@ class build_ext (Command):
the .pyd file (DLL) must export the module "init" function. the .pyd file (DLL) must export the module "init" function.
""" """
initfunc_name = "init" + string.split(ext.name,'.')[-1] initfunc_name = "init" + ext.name.split('.')[-1]
if initfunc_name not in ext.export_symbols: if initfunc_name not in ext.export_symbols:
ext.export_symbols.append(initfunc_name) ext.export_symbols.append(initfunc_name)
return ext.export_symbols return ext.export_symbols
......
...@@ -6,7 +6,7 @@ Implements the Distutils 'build_py' command.""" ...@@ -6,7 +6,7 @@ Implements the Distutils 'build_py' command."""
__revision__ = "$Id$" __revision__ = "$Id$"
import sys, string, os import sys, os
from types import * from types import *
from glob import glob from glob import glob
...@@ -150,7 +150,7 @@ class build_py (Command): ...@@ -150,7 +150,7 @@ class build_py (Command):
distribution, where package 'package' should be found distribution, where package 'package' should be found
(at least according to the 'package_dir' option, if any).""" (at least according to the 'package_dir' option, if any)."""
path = string.split(package, '.') path = package.split('.')
if not self.package_dir: if not self.package_dir:
if path: if path:
...@@ -161,7 +161,7 @@ class build_py (Command): ...@@ -161,7 +161,7 @@ class build_py (Command):
tail = [] tail = []
while path: while path:
try: try:
pdir = self.package_dir[string.join(path, '.')] pdir = self.package_dir['.'.join(path)]
except KeyError: except KeyError:
tail.insert(0, path[-1]) tail.insert(0, path[-1])
del path[-1] del path[-1]
...@@ -272,8 +272,8 @@ class build_py (Command): ...@@ -272,8 +272,8 @@ class build_py (Command):
# - don't check for __init__.py in directory for empty package # - don't check for __init__.py in directory for empty package
for module in self.py_modules: for module in self.py_modules:
path = string.split(module, '.') path = module.split('.')
package = string.join(path[0:-1], '.') package = '.'.join(path[0:-1])
module_base = path[-1] module_base = path[-1]
try: try:
...@@ -342,7 +342,7 @@ class build_py (Command): ...@@ -342,7 +342,7 @@ class build_py (Command):
modules = self.find_all_modules() modules = self.find_all_modules()
outputs = [] outputs = []
for (package, module, module_file) in modules: for (package, module, module_file) in modules:
package = string.split(package, '.') package = package.split('.')
filename = self.get_module_outfile(self.build_lib, package, module) filename = self.get_module_outfile(self.build_lib, package, module)
outputs.append(filename) outputs.append(filename)
if include_bytecode: if include_bytecode:
...@@ -362,7 +362,7 @@ class build_py (Command): ...@@ -362,7 +362,7 @@ class build_py (Command):
def build_module (self, module, module_file, package): def build_module (self, module, module_file, package):
if type(package) is StringType: if type(package) is StringType:
package = string.split(package, '.') package = package.split('.')
elif type(package) not in (ListType, TupleType): elif type(package) not in (ListType, TupleType):
raise TypeError, \ raise TypeError, \
"'package' must be a string (dot-separated), list, or tuple" "'package' must be a string (dot-separated), list, or tuple"
......
...@@ -13,7 +13,7 @@ this header file lives". ...@@ -13,7 +13,7 @@ this header file lives".
__revision__ = "$Id$" __revision__ = "$Id$"
import sys, os, string, re import sys, os, re
from types import * from types import *
from distutils.core import Command from distutils.core import Command
from distutils.errors import DistutilsExecError from distutils.errors import DistutilsExecError
...@@ -74,7 +74,7 @@ class config (Command): ...@@ -74,7 +74,7 @@ class config (Command):
if self.include_dirs is None: if self.include_dirs is None:
self.include_dirs = self.distribution.include_dirs or [] self.include_dirs = self.distribution.include_dirs or []
elif type(self.include_dirs) is StringType: elif type(self.include_dirs) is StringType:
self.include_dirs = string.split(self.include_dirs, os.pathsep) self.include_dirs = self.include_dirs.split(os.pathsep)
if self.libraries is None: if self.libraries is None:
self.libraries = [] self.libraries = []
...@@ -84,7 +84,7 @@ class config (Command): ...@@ -84,7 +84,7 @@ class config (Command):
if self.library_dirs is None: if self.library_dirs is None:
self.library_dirs = [] self.library_dirs = []
elif type(self.library_dirs) is StringType: elif type(self.library_dirs) is StringType:
self.library_dirs = string.split(self.library_dirs, os.pathsep) self.library_dirs = self.library_dirs.split(os.pathsep)
def run (self): def run (self):
...@@ -163,7 +163,7 @@ class config (Command): ...@@ -163,7 +163,7 @@ class config (Command):
if not filenames: if not filenames:
filenames = self.temp_files filenames = self.temp_files
self.temp_files = [] self.temp_files = []
log.info("removing: %s", string.join(filenames)) log.info("removing: %s", ' '.join(filenames))
for filename in filenames: for filename in filenames:
try: try:
os.remove(filename) os.remove(filename)
...@@ -322,7 +322,7 @@ class config (Command): ...@@ -322,7 +322,7 @@ class config (Command):
else: else:
body.append(" %s;" % func) body.append(" %s;" % func)
body.append("}") body.append("}")
body = string.join(body, "\n") + "\n" body = "\n".join(body) + "\n"
return self.try_link(body, headers, include_dirs, return self.try_link(body, headers, include_dirs,
libraries, library_dirs) libraries, library_dirs)
......
...@@ -8,7 +8,7 @@ from distutils import log ...@@ -8,7 +8,7 @@ from distutils import log
__revision__ = "$Id$" __revision__ = "$Id$"
import sys, os, string import sys, os
from types import * from types import *
from distutils.core import Command from distutils.core import Command
from distutils.debug import DEBUG from distutils.debug import DEBUG
...@@ -269,7 +269,7 @@ class install (Command): ...@@ -269,7 +269,7 @@ class install (Command):
# $platbase in the other installation directories and not worry # $platbase in the other installation directories and not worry
# about needing recursive variable expansion (shudder). # about needing recursive variable expansion (shudder).
py_version = (string.split(sys.version))[0] py_version = sys.version.split()[0]
(prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix') (prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix')
self.config_vars = {'dist_name': self.distribution.get_name(), self.config_vars = {'dist_name': self.distribution.get_name(),
'dist_version': self.distribution.get_version(), 'dist_version': self.distribution.get_version(),
...@@ -353,11 +353,11 @@ class install (Command): ...@@ -353,11 +353,11 @@ class install (Command):
if opt_name[-1] == "=": if opt_name[-1] == "=":
opt_name = opt_name[0:-1] opt_name = opt_name[0:-1]
if self.negative_opt.has_key(opt_name): if self.negative_opt.has_key(opt_name):
opt_name = string.translate(self.negative_opt[opt_name], opt_name = self.negative_opt[opt_name].translate(
longopt_xlate) longopt_xlate)
val = not getattr(self, opt_name) val = not getattr(self, opt_name)
else: else:
opt_name = string.translate(opt_name, longopt_xlate) opt_name = opt_name.translate(longopt_xlate)
val = getattr(self, opt_name) val = getattr(self, opt_name)
print(" %s: %s" % (opt_name, val)) print(" %s: %s" % (opt_name, val))
...@@ -464,7 +464,7 @@ class install (Command): ...@@ -464,7 +464,7 @@ class install (Command):
if self.extra_path is not None: if self.extra_path is not None:
if type(self.extra_path) is StringType: if type(self.extra_path) is StringType:
self.extra_path = string.split(self.extra_path, ',') self.extra_path = self.extra_path.split(',')
if len(self.extra_path) == 1: if len(self.extra_path) == 1:
path_file = extra_dirs = self.extra_path[0] path_file = extra_dirs = self.extra_path[0]
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
__revision__ = "$Id$" __revision__ = "$Id$"
import sys, os, string import sys, os
from types import IntType from types import IntType
from distutils.core import Command from distutils.core import Command
from distutils.errors import DistutilsOptionError from distutils.errors import DistutilsOptionError
......
...@@ -7,7 +7,7 @@ Implements the Distutils 'register' command (register with the repository). ...@@ -7,7 +7,7 @@ Implements the Distutils 'register' command (register with the repository).
__revision__ = "$Id$" __revision__ = "$Id$"
import sys, os, string, urllib2, getpass, urlparse import sys, os, urllib2, getpass, urlparse
import StringIO, ConfigParser import StringIO, ConfigParser
from distutils.core import Command from distutils.core import Command
...@@ -67,7 +67,7 @@ class register(Command): ...@@ -67,7 +67,7 @@ class register(Command):
if missing: if missing:
self.warn("missing required meta-data: " + self.warn("missing required meta-data: " +
string.join(missing, ", ")) ", ".join(missing))
if metadata.author: if metadata.author:
if not metadata.author_email: if not metadata.author_email:
......
...@@ -6,7 +6,7 @@ Implements the Distutils 'sdist' command (create a source distribution).""" ...@@ -6,7 +6,7 @@ Implements the Distutils 'sdist' command (create a source distribution)."""
__revision__ = "$Id$" __revision__ = "$Id$"
import sys, os, string import sys, os
from types import * from types import *
from glob import glob from glob import glob
from distutils.core import Command from distutils.core import Command
...@@ -166,7 +166,7 @@ class sdist (Command): ...@@ -166,7 +166,7 @@ class sdist (Command):
if missing: if missing:
self.warn("missing required meta-data: " + self.warn("missing required meta-data: " +
string.join(missing, ", ")) ", ".join(missing))
if metadata.author: if metadata.author:
if not metadata.author_email: if not metadata.author_email:
...@@ -279,7 +279,7 @@ class sdist (Command): ...@@ -279,7 +279,7 @@ class sdist (Command):
if not got_it: if not got_it:
self.warn("standard file not found: should have one of " + self.warn("standard file not found: should have one of " +
string.join(alts, ', ')) ', '.join(alts))
else: else:
if os.path.exists(fn): if os.path.exists(fn):
self.filelist.append(fn) self.filelist.append(fn)
......
...@@ -365,10 +365,9 @@ def check_config_h(): ...@@ -365,10 +365,9 @@ def check_config_h():
# "pyconfig.h" check -- should probably be renamed... # "pyconfig.h" check -- should probably be renamed...
from distutils import sysconfig from distutils import sysconfig
import string
# if sys.version contains GCC then python was compiled with # if sys.version contains GCC then python was compiled with
# GCC, and the pyconfig.h file should be OK # GCC, and the pyconfig.h file should be OK
if string.find(sys.version,"GCC") >= 0: if sys.version.find("GCC") >= 0:
return (CONFIG_H_OK, "sys.version mentions 'GCC'") return (CONFIG_H_OK, "sys.version mentions 'GCC'")
fn = sysconfig.get_config_h_filename() fn = sysconfig.get_config_h_filename()
...@@ -387,7 +386,7 @@ def check_config_h(): ...@@ -387,7 +386,7 @@ def check_config_h():
else: else:
# "pyconfig.h" contains an "#ifdef __GNUC__" or something similar # "pyconfig.h" contains an "#ifdef __GNUC__" or something similar
if string.find(s,"__GNUC__") >= 0: if s.find("__GNUC__") >= 0:
return (CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn) return (CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn)
else: else:
return (CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn) return (CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn)
......
...@@ -8,7 +8,7 @@ being built/installed/distributed. ...@@ -8,7 +8,7 @@ being built/installed/distributed.
__revision__ = "$Id$" __revision__ = "$Id$"
import sys, os, string, re import sys, os, re
from types import * from types import *
from copy import copy from copy import copy
...@@ -304,7 +304,7 @@ Common commands: (see '--help-commands' for more) ...@@ -304,7 +304,7 @@ Common commands: (see '--help-commands' for more)
else: else:
print(indent + "option dict for '%s' command:" % cmd_name) print(indent + "option dict for '%s' command:" % cmd_name)
out = pformat(opt_dict) out = pformat(opt_dict)
for line in string.split(out, "\n"): for line in out.split("\n"):
print(indent + " " + line) print(indent + " " + line)
# dump_option_dicts () # dump_option_dicts ()
...@@ -378,7 +378,7 @@ Common commands: (see '--help-commands' for more) ...@@ -378,7 +378,7 @@ Common commands: (see '--help-commands' for more)
for opt in options: for opt in options:
if opt != '__name__': if opt != '__name__':
val = parser.get(section,opt) val = parser.get(section,opt)
opt = string.replace(opt, '-', '_') opt = opt.replace('-', '_')
opt_dict[opt] = (filename, val) opt_dict[opt] = (filename, val)
# Make the ConfigParser forget everything (so we retain # Make the ConfigParser forget everything (so we retain
...@@ -599,14 +599,14 @@ Common commands: (see '--help-commands' for more) ...@@ -599,14 +599,14 @@ Common commands: (see '--help-commands' for more)
keywords = self.metadata.keywords keywords = self.metadata.keywords
if keywords is not None: if keywords is not None:
if type(keywords) is StringType: if type(keywords) is StringType:
keywordlist = string.split(keywords, ',') keywordlist = keywords.split(',')
self.metadata.keywords = map(string.strip, keywordlist) self.metadata.keywords = [x.strip() for x in keywordlist]
platforms = self.metadata.platforms platforms = self.metadata.platforms
if platforms is not None: if platforms is not None:
if type(platforms) is StringType: if type(platforms) is StringType:
platformlist = string.split(platforms, ',') platformlist = platforms.split(',')
self.metadata.platforms = map(string.strip, platformlist) self.metadata.platforms = [x.strip() for x in platformlist]
def _show_help (self, def _show_help (self,
parser, parser,
...@@ -695,10 +695,10 @@ Common commands: (see '--help-commands' for more) ...@@ -695,10 +695,10 @@ Common commands: (see '--help-commands' for more)
opt = translate_longopt(opt) opt = translate_longopt(opt)
value = getattr(self.metadata, "get_"+opt)() value = getattr(self.metadata, "get_"+opt)()
if opt in ['keywords', 'platforms']: if opt in ['keywords', 'platforms']:
print(string.join(value, ',')) print(','.join(value))
elif opt in ('classifiers', 'provides', 'requires', elif opt in ('classifiers', 'provides', 'requires',
'obsoletes'): 'obsoletes'):
print(string.join(value, '\n')) print('\n'.join(value))
else: else:
print(value) print(value)
any_display_options = 1 any_display_options = 1
...@@ -803,9 +803,9 @@ Common commands: (see '--help-commands' for more) ...@@ -803,9 +803,9 @@ Common commands: (see '--help-commands' for more)
"""Return a list of packages from which commands are loaded.""" """Return a list of packages from which commands are loaded."""
pkgs = self.command_packages pkgs = self.command_packages
if not isinstance(pkgs, type([])): if not isinstance(pkgs, type([])):
pkgs = string.split(pkgs or "", ",") pkgs = (pkgs or "").split(",")
for i in range(len(pkgs)): for i in range(len(pkgs)):
pkgs[i] = string.strip(pkgs[i]) pkgs[i] = pkgs[i].strip()
pkgs = filter(None, pkgs) pkgs = filter(None, pkgs)
if "distutils.command" not in pkgs: if "distutils.command" not in pkgs:
pkgs.insert(0, "distutils.command") pkgs.insert(0, "distutils.command")
...@@ -1100,7 +1100,7 @@ class DistributionMetadata: ...@@ -1100,7 +1100,7 @@ class DistributionMetadata:
long_desc = rfc822_escape( self.get_long_description() ) long_desc = rfc822_escape( self.get_long_description() )
file.write('Description: %s\n' % long_desc) file.write('Description: %s\n' % long_desc)
keywords = string.join( self.get_keywords(), ',') keywords = ','.join(self.get_keywords())
if keywords: if keywords:
file.write('Keywords: %s\n' % keywords ) file.write('Keywords: %s\n' % keywords )
......
...@@ -261,10 +261,9 @@ def check_config_h(): ...@@ -261,10 +261,9 @@ def check_config_h():
# "pyconfig.h" check -- should probably be renamed... # "pyconfig.h" check -- should probably be renamed...
from distutils import sysconfig from distutils import sysconfig
import string
# if sys.version contains GCC then python was compiled with # if sys.version contains GCC then python was compiled with
# GCC, and the pyconfig.h file should be OK # GCC, and the pyconfig.h file should be OK
if string.find(sys.version,"GCC") >= 0: if sys.version.find("GCC") >= 0:
return (CONFIG_H_OK, "sys.version mentions 'GCC'") return (CONFIG_H_OK, "sys.version mentions 'GCC'")
fn = sysconfig.get_config_h_filename() fn = sysconfig.get_config_h_filename()
...@@ -283,7 +282,7 @@ def check_config_h(): ...@@ -283,7 +282,7 @@ def check_config_h():
else: else:
# "pyconfig.h" contains an "#ifdef __GNUC__" or something similar # "pyconfig.h" contains an "#ifdef __GNUC__" or something similar
if string.find(s,"__GNUC__") >= 0: if s.find("__GNUC__") >= 0:
return (CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn) return (CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn)
else: else:
return (CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn) return (CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn)
......
...@@ -5,7 +5,7 @@ modules in setup scripts.""" ...@@ -5,7 +5,7 @@ modules in setup scripts."""
__revision__ = "$Id$" __revision__ = "$Id$"
import os, string, sys import os, sys
from types import * from types import *
try: try:
...@@ -128,7 +128,7 @@ class Extension: ...@@ -128,7 +128,7 @@ class Extension:
if len(kw): if len(kw):
L = kw.keys() ; L.sort() L = kw.keys() ; L.sort()
L = map(repr, L) L = map(repr, L)
msg = "Unknown Extension options: " + string.join(L, ', ') msg = "Unknown Extension options: " + ', '.join(L)
if warnings is not None: if warnings is not None:
warnings.warn(msg) warnings.warn(msg)
else: else:
...@@ -195,7 +195,7 @@ def read_setup_file (filename): ...@@ -195,7 +195,7 @@ def read_setup_file (filename):
elif switch == "-I": elif switch == "-I":
ext.include_dirs.append(value) ext.include_dirs.append(value)
elif switch == "-D": elif switch == "-D":
equals = string.find(value, "=") equals = value.find("=")
if equals == -1: # bare "-DFOO" -- no value if equals == -1: # bare "-DFOO" -- no value
ext.define_macros.append((value, None)) ext.define_macros.append((value, None))
else: # "-DFOO=blah" else: # "-DFOO=blah"
......
...@@ -115,7 +115,7 @@ class FancyGetopt: ...@@ -115,7 +115,7 @@ class FancyGetopt:
"""Translate long option name 'long_option' to the form it """Translate long option name 'long_option' to the form it
has as an attribute of some object: ie., translate hyphens has as an attribute of some object: ie., translate hyphens
to underscores.""" to underscores."""
return string.translate(long_option, longopt_xlate) return long_option.translate(longopt_xlate)
def _check_alias_dict (self, aliases, what): def _check_alias_dict (self, aliases, what):
...@@ -253,7 +253,7 @@ class FancyGetopt: ...@@ -253,7 +253,7 @@ class FancyGetopt:
self._grok_option_table() self._grok_option_table()
short_opts = string.join(self.short_opts) short_opts = ' '.join(self.short_opts)
try: try:
opts, args = getopt.getopt(args, short_opts, self.long_opts) opts, args = getopt.getopt(args, short_opts, self.long_opts)
except getopt.error as msg: except getopt.error as msg:
...@@ -420,8 +420,8 @@ def wrap_text (text, width): ...@@ -420,8 +420,8 @@ def wrap_text (text, width):
if len(text) <= width: if len(text) <= width:
return [text] return [text]
text = string.expandtabs(text) text = text.expandtabs()
text = string.translate(text, WS_TRANS) text = text.translate(WS_TRANS)
chunks = re.split(r'( +|-+)', text) chunks = re.split(r'( +|-+)', text)
chunks = filter(None, chunks) # ' - ' results in empty strings chunks = filter(None, chunks) # ' - ' results in empty strings
lines = [] lines = []
...@@ -460,7 +460,7 @@ def wrap_text (text, width): ...@@ -460,7 +460,7 @@ def wrap_text (text, width):
# and store this line in the list-of-all-lines -- as a single # and store this line in the list-of-all-lines -- as a single
# string, of course! # string, of course!
lines.append(string.join(cur_line, '')) lines.append(''.join(cur_line))
# while chunks # while chunks
...@@ -473,7 +473,7 @@ def translate_longopt (opt): ...@@ -473,7 +473,7 @@ def translate_longopt (opt):
"""Convert a long option name to a valid Python identifier by """Convert a long option name to a valid Python identifier by
changing "-" to "_". changing "-" to "_".
""" """
return string.translate(opt, longopt_xlate) return opt.translate(longopt_xlate)
class OptionDummy: class OptionDummy:
...@@ -498,5 +498,5 @@ say, "How should I know?"].)""" ...@@ -498,5 +498,5 @@ say, "How should I know?"].)"""
for w in (10, 20, 30, 40): for w in (10, 20, 30, 40):
print("width: %d" % w) print("width: %d" % w)
print(string.join(wrap_text(text, w), "\n")) print("\n".join(wrap_text(text, w)))
print() print()
...@@ -8,7 +8,7 @@ and building lists of files. ...@@ -8,7 +8,7 @@ and building lists of files.
__revision__ = "$Id$" __revision__ = "$Id$"
import os, string, re import os, re
import fnmatch import fnmatch
from types import * from types import *
from glob import glob from glob import glob
...@@ -84,7 +84,7 @@ class FileList: ...@@ -84,7 +84,7 @@ class FileList:
# -- "File template" methods --------------------------------------- # -- "File template" methods ---------------------------------------
def _parse_template_line (self, line): def _parse_template_line (self, line):
words = string.split(line) words = line.split()
action = words[0] action = words[0]
patterns = dir = dir_pattern = None patterns = dir = dir_pattern = None
...@@ -133,28 +133,28 @@ class FileList: ...@@ -133,28 +133,28 @@ class FileList:
# right number of words on the line for that action -- so we # right number of words on the line for that action -- so we
# can proceed with minimal error-checking. # can proceed with minimal error-checking.
if action == 'include': if action == 'include':
self.debug_print("include " + string.join(patterns)) self.debug_print("include " + ' '.join(patterns))
for pattern in patterns: for pattern in patterns:
if not self.include_pattern(pattern, anchor=1): if not self.include_pattern(pattern, anchor=1):
log.warn("warning: no files found matching '%s'", log.warn("warning: no files found matching '%s'",
pattern) pattern)
elif action == 'exclude': elif action == 'exclude':
self.debug_print("exclude " + string.join(patterns)) self.debug_print("exclude " + ' '.join(patterns))
for pattern in patterns: for pattern in patterns:
if not self.exclude_pattern(pattern, anchor=1): if not self.exclude_pattern(pattern, anchor=1):
log.warn(("warning: no previously-included files " log.warn(("warning: no previously-included files "
"found matching '%s'"), pattern) "found matching '%s'"), pattern)
elif action == 'global-include': elif action == 'global-include':
self.debug_print("global-include " + string.join(patterns)) self.debug_print("global-include " + ' '.join(patterns))
for pattern in patterns: for pattern in patterns:
if not self.include_pattern(pattern, anchor=0): if not self.include_pattern(pattern, anchor=0):
log.warn(("warning: no files found matching '%s' " + log.warn(("warning: no files found matching '%s' " +
"anywhere in distribution"), pattern) "anywhere in distribution"), pattern)
elif action == 'global-exclude': elif action == 'global-exclude':
self.debug_print("global-exclude " + string.join(patterns)) self.debug_print("global-exclude " + ' '.join(patterns))
for pattern in patterns: for pattern in patterns:
if not self.exclude_pattern(pattern, anchor=0): if not self.exclude_pattern(pattern, anchor=0):
log.warn(("warning: no previously-included files matching " log.warn(("warning: no previously-included files matching "
...@@ -163,7 +163,7 @@ class FileList: ...@@ -163,7 +163,7 @@ class FileList:
elif action == 'recursive-include': elif action == 'recursive-include':
self.debug_print("recursive-include %s %s" % self.debug_print("recursive-include %s %s" %
(dir, string.join(patterns))) (dir, ' '.join(patterns)))
for pattern in patterns: for pattern in patterns:
if not self.include_pattern(pattern, prefix=dir): if not self.include_pattern(pattern, prefix=dir):
log.warn(("warning: no files found matching '%s' " + log.warn(("warning: no files found matching '%s' " +
...@@ -172,7 +172,7 @@ class FileList: ...@@ -172,7 +172,7 @@ class FileList:
elif action == 'recursive-exclude': elif action == 'recursive-exclude':
self.debug_print("recursive-exclude %s %s" % self.debug_print("recursive-exclude %s %s" %
(dir, string.join(patterns))) (dir, ' '.join(patterns)))
for pattern in patterns: for pattern in patterns:
if not self.exclude_pattern(pattern, prefix=dir): if not self.exclude_pattern(pattern, prefix=dir):
log.warn(("warning: no previously-included files matching " log.warn(("warning: no previously-included files matching "
......
...@@ -12,7 +12,7 @@ for the Microsoft Visual Studio. ...@@ -12,7 +12,7 @@ for the Microsoft Visual Studio.
__revision__ = "$Id$" __revision__ = "$Id$"
import sys, os, string import sys, os
from distutils.errors import \ from distutils.errors import \
DistutilsExecError, DistutilsPlatformError, \ DistutilsExecError, DistutilsPlatformError, \
CompileError, LibError, LinkError CompileError, LibError, LinkError
...@@ -148,7 +148,7 @@ you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""") ...@@ -148,7 +148,7 @@ you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""")
def sub(self, s): def sub(self, s):
for k, v in self.macros.items(): for k, v in self.macros.items():
s = string.replace(s, k, v) s = s.replace(k, v)
return s return s
def get_build_version(): def get_build_version():
...@@ -159,7 +159,7 @@ def get_build_version(): ...@@ -159,7 +159,7 @@ def get_build_version():
""" """
prefix = "MSC v." prefix = "MSC v."
i = string.find(sys.version, prefix) i = sys.version.find(prefix)
if i == -1: if i == -1:
return 6 return 6
i = i + len(prefix) i = i + len(prefix)
...@@ -181,10 +181,10 @@ def get_build_architecture(): ...@@ -181,10 +181,10 @@ def get_build_architecture():
""" """
prefix = " bit (" prefix = " bit ("
i = string.find(sys.version, prefix) i = sys.version.find(prefix)
if i == -1: if i == -1:
return "Intel" return "Intel"
j = string.find(sys.version, ")", i) j = sys.version.find(")", i)
return sys.version[i+len(prefix):j] return sys.version[i+len(prefix):j]
...@@ -266,11 +266,11 @@ class MSVCCompiler (CCompiler) : ...@@ -266,11 +266,11 @@ class MSVCCompiler (CCompiler) :
# extend the MSVC path with the current path # extend the MSVC path with the current path
try: try:
for p in string.split(os.environ['path'], ';'): for p in os.environ['path'].split(';'):
self.__paths.append(p) self.__paths.append(p)
except KeyError: except KeyError:
pass pass
os.environ['path'] = string.join(self.__paths, ';') os.environ['path'] = ';'.join(self.__paths)
self.preprocess_options = None self.preprocess_options = None
if self.__arch == "Intel": if self.__arch == "Intel":
...@@ -579,7 +579,7 @@ class MSVCCompiler (CCompiler) : ...@@ -579,7 +579,7 @@ class MSVCCompiler (CCompiler) :
return fn return fn
# didn't find it; try existing path # didn't find it; try existing path
for p in string.split(os.environ['Path'],';'): for p in os.environ['Path'].split(';'):
fn = os.path.join(os.path.abspath(p),exe) fn = os.path.join(os.path.abspath(p),exe)
if os.path.isfile(fn): if os.path.isfile(fn):
return fn return fn
...@@ -608,9 +608,9 @@ class MSVCCompiler (CCompiler) : ...@@ -608,9 +608,9 @@ class MSVCCompiler (CCompiler) :
d = read_values(base, key) d = read_values(base, key)
if d: if d:
if self.__version >= 7: if self.__version >= 7:
return string.split(self.__macros.sub(d[path]), ";") return self.__macros.sub(d[path]).split(";")
else: else:
return string.split(d[path], ";") return d[path].split(";")
# MSVC 6 seems to create the registry entries we need only when # MSVC 6 seems to create the registry entries we need only when
# the GUI is run. # the GUI is run.
if self.__version == 6: if self.__version == 6:
...@@ -635,4 +635,4 @@ class MSVCCompiler (CCompiler) : ...@@ -635,4 +635,4 @@ class MSVCCompiler (CCompiler) :
else: else:
p = self.get_msvc_paths(name) p = self.get_msvc_paths(name)
if p: if p:
os.environ[name] = string.join(p, ';') os.environ[name] = ';'.join(p)
...@@ -8,7 +8,7 @@ Windows.""" ...@@ -8,7 +8,7 @@ Windows."""
__revision__ = "$Id$" __revision__ = "$Id$"
import sys, os, string import sys, os
from types import * from types import *
from distutils.errors import \ from distutils.errors import \
DistutilsExecError, DistutilsPlatformError, \ DistutilsExecError, DistutilsPlatformError, \
...@@ -213,11 +213,11 @@ class MWerksCompiler (CCompiler) : ...@@ -213,11 +213,11 @@ class MWerksCompiler (CCompiler) :
curdir = os.getcwd() curdir = os.getcwd()
filename = os.path.join(curdir, filename) filename = os.path.join(curdir, filename)
# Finally remove .. components # Finally remove .. components
components = string.split(filename, ':') components = filename.split(':')
for i in range(1, len(components)): for i in range(1, len(components)):
if components[i] == '..': if components[i] == '..':
components[i] = '' components[i] = ''
return string.join(components, ':') return ':'.join(components)
def library_dir_option (self, dir): def library_dir_option (self, dir):
"""Return the compiler option to add 'dir' to the list of """Return the compiler option to add 'dir' to the list of
......
...@@ -10,7 +10,7 @@ executable name. ...@@ -10,7 +10,7 @@ executable name.
__revision__ = "$Id$" __revision__ = "$Id$"
import sys, os, string import sys, os
from distutils.errors import * from distutils.errors import *
from distutils import log from distutils import log
...@@ -59,7 +59,7 @@ def _nt_quote_args (args): ...@@ -59,7 +59,7 @@ def _nt_quote_args (args):
# quoting?) # quoting?)
for i in range(len(args)): for i in range(len(args)):
if string.find(args[i], ' ') != -1: if args[i].find(' ') != -1:
args[i] = '"%s"' % args[i] args[i] = '"%s"' % args[i]
return args return args
...@@ -73,7 +73,7 @@ def _spawn_nt (cmd, ...@@ -73,7 +73,7 @@ def _spawn_nt (cmd,
if search_path: if search_path:
# either we find one or it stays the same # either we find one or it stays the same
executable = find_executable(executable) or executable executable = find_executable(executable) or executable
log.info(string.join([executable] + cmd[1:], ' ')) log.info(' '.join([executable] + cmd[1:]))
if not dry_run: if not dry_run:
# spawn for NT requires a full path to the .exe # spawn for NT requires a full path to the .exe
try: try:
...@@ -98,7 +98,7 @@ def _spawn_os2 (cmd, ...@@ -98,7 +98,7 @@ def _spawn_os2 (cmd,
if search_path: if search_path:
# either we find one or it stays the same # either we find one or it stays the same
executable = find_executable(executable) or executable executable = find_executable(executable) or executable
log.info(string.join([executable] + cmd[1:], ' ')) log.info(' '.join([executable] + cmd[1:]))
if not dry_run: if not dry_run:
# spawnv for OS/2 EMX requires a full path to the .exe # spawnv for OS/2 EMX requires a full path to the .exe
try: try:
...@@ -119,7 +119,7 @@ def _spawn_posix (cmd, ...@@ -119,7 +119,7 @@ def _spawn_posix (cmd,
verbose=0, verbose=0,
dry_run=0): dry_run=0):
log.info(string.join(cmd, ' ')) log.info(' '.join(cmd))
if dry_run: if dry_run:
return return
exec_fn = search_path and os.execvp or os.execv exec_fn = search_path and os.execvp or os.execv
...@@ -184,7 +184,7 @@ def find_executable(executable, path=None): ...@@ -184,7 +184,7 @@ def find_executable(executable, path=None):
""" """
if path is None: if path is None:
path = os.environ['PATH'] path = os.environ['PATH']
paths = string.split(path, os.pathsep) paths = path.split(os.pathsep)
(base, ext) = os.path.splitext(executable) (base, ext) = os.path.splitext(executable)
if (sys.platform == 'win32' or os.name == 'os2') and (ext != '.exe'): if (sys.platform == 'win32' or os.name == 'os2') and (ext != '.exe'):
executable = executable + '.exe' executable = executable + '.exe'
......
...@@ -13,7 +13,6 @@ __revision__ = "$Id$" ...@@ -13,7 +13,6 @@ __revision__ = "$Id$"
import os import os
import re import re
import string
import sys import sys
from .errors import DistutilsPlatformError from .errors import DistutilsPlatformError
...@@ -261,7 +260,7 @@ def parse_makefile(fn, g=None): ...@@ -261,7 +260,7 @@ def parse_makefile(fn, g=None):
m = _variable_rx.match(line) m = _variable_rx.match(line)
if m: if m:
n, v = m.group(1, 2) n, v = m.group(1, 2)
v = string.strip(v) v = v.strip()
if "$" in v: if "$" in v:
notdone[n] = v notdone[n] = v
else: else:
...@@ -295,7 +294,7 @@ def parse_makefile(fn, g=None): ...@@ -295,7 +294,7 @@ def parse_makefile(fn, g=None):
else: else:
try: value = int(value) try: value = int(value)
except ValueError: except ValueError:
done[name] = string.strip(value) done[name] = value.strip()
else: else:
done[name] = value done[name] = value
del notdone[name] del notdone[name]
...@@ -399,7 +398,7 @@ def _init_posix(): ...@@ -399,7 +398,7 @@ def _init_posix():
# relative to the srcdir, which after installation no longer makes # relative to the srcdir, which after installation no longer makes
# sense. # sense.
python_lib = get_python_lib(standard_lib=1) python_lib = get_python_lib(standard_lib=1)
linkerscript_path = string.split(g['LDSHARED'])[0] linkerscript_path = g['LDSHARED'].split()[0]
linkerscript_name = os.path.basename(linkerscript_path) linkerscript_name = os.path.basename(linkerscript_path)
linkerscript = os.path.join(python_lib, 'config', linkerscript = os.path.join(python_lib, 'config',
linkerscript_name) linkerscript_name)
......
...@@ -7,7 +7,7 @@ lines, and joining lines with backslashes.""" ...@@ -7,7 +7,7 @@ lines, and joining lines with backslashes."""
__revision__ = "$Id$" __revision__ = "$Id$"
from types import * from types import *
import sys, os, string import sys, os
class TextFile: class TextFile:
...@@ -142,7 +142,7 @@ class TextFile: ...@@ -142,7 +142,7 @@ class TextFile:
else: else:
outmsg.append("line %d: " % line) outmsg.append("line %d: " % line)
outmsg.append(str(msg)) outmsg.append(str(msg))
return string.join(outmsg, "") return "".join(outmsg)
def error (self, msg, line=None): def error (self, msg, line=None):
...@@ -196,7 +196,7 @@ class TextFile: ...@@ -196,7 +196,7 @@ class TextFile:
# unescape it (and any other escaped "#"'s that might be # unescape it (and any other escaped "#"'s that might be
# lurking in there) and otherwise leave the line alone. # lurking in there) and otherwise leave the line alone.
pos = string.find (line, "#") pos = line.find ("#")
if pos == -1: # no "#" -- no comments if pos == -1: # no "#" -- no comments
pass pass
...@@ -219,11 +219,11 @@ class TextFile: ...@@ -219,11 +219,11 @@ class TextFile:
# # comment that should be ignored # # comment that should be ignored
# there # there
# result in "hello there". # result in "hello there".
if string.strip(line) == "": if line.strip () == "":
continue continue
else: # it's an escaped "#" else: # it's an escaped "#"
line = string.replace (line, "\\#", "#") line = line.replace("\\#", "#")
# did previous line end with a backslash? then accumulate # did previous line end with a backslash? then accumulate
...@@ -235,7 +235,7 @@ class TextFile: ...@@ -235,7 +235,7 @@ class TextFile:
return buildup_line return buildup_line
if self.collapse_join: if self.collapse_join:
line = string.lstrip (line) line = line.lstrip ()
line = buildup_line + line line = buildup_line + line
# careful: pay attention to line number when incrementing it # careful: pay attention to line number when incrementing it
...@@ -259,11 +259,11 @@ class TextFile: ...@@ -259,11 +259,11 @@ class TextFile:
# strip whitespace however the client wants (leading and # strip whitespace however the client wants (leading and
# trailing, or one or the other, or neither) # trailing, or one or the other, or neither)
if self.lstrip_ws and self.rstrip_ws: if self.lstrip_ws and self.rstrip_ws:
line = string.strip (line) line = line.strip ()
elif self.lstrip_ws: elif self.lstrip_ws:
line = string.lstrip (line) line = line.lstrip ()
elif self.rstrip_ws: elif self.rstrip_ws:
line = string.rstrip (line) line = line.rstrip ()
# blank line (whether we rstrip'ed or not)? skip to next line # blank line (whether we rstrip'ed or not)? skip to next line
# if appropriate # if appropriate
...@@ -313,7 +313,7 @@ line 3 \\ ...@@ -313,7 +313,7 @@ line 3 \\
continues on next line continues on next line
""" """
# result 1: no fancy options # result 1: no fancy options
result1 = map (lambda x: x + "\n", string.split (test_data, "\n")[0:-1]) result1 = map (lambda x: x + "\n", test_data.split ("\n")[0:-1])
# result 2: just strip comments # result 2: just strip comments
result2 = ["\n", result2 = ["\n",
...@@ -340,7 +340,7 @@ line 3 \\ ...@@ -340,7 +340,7 @@ line 3 \\
def test_input (count, description, file, expected_result): def test_input (count, description, file, expected_result):
result = file.readlines () result = file.readlines ()
# result = string.join (result, '') # result = ''.join (result)
if result == expected_result: if result == expected_result:
print("ok %d (%s)" % (count, description)) print("ok %d (%s)" % (count, description))
else: else:
......
...@@ -42,10 +42,9 @@ def get_platform (): ...@@ -42,10 +42,9 @@ def get_platform ():
# Convert the OS name to lowercase, remove '/' characters # Convert the OS name to lowercase, remove '/' characters
# (to accommodate BSD/OS), and translate spaces (for "Power Macintosh") # (to accommodate BSD/OS), and translate spaces (for "Power Macintosh")
osname = string.lower(osname) osname = osname.lower().replace('/', '')
osname = string.replace(osname, '/', '') machine = machine.replace(' ', '_')
machine = string.replace(machine, ' ', '_') machine = machine.replace('/', '-')
machine = string.replace(machine, '/', '-')
if osname[:5] == "linux": if osname[:5] == "linux":
# At least on Linux/Intel, 'machine' is the processor -- # At least on Linux/Intel, 'machine' is the processor --
...@@ -139,7 +138,7 @@ def convert_path (pathname): ...@@ -139,7 +138,7 @@ def convert_path (pathname):
if pathname[-1] == '/': if pathname[-1] == '/':
raise ValueError, "path '%s' cannot end with '/'" % pathname raise ValueError, "path '%s' cannot end with '/'" % pathname
paths = string.split(pathname, '/') paths = pathname.split('/')
while '.' in paths: while '.' in paths:
paths.remove('.') paths.remove('.')
if not paths: if not paths:
...@@ -178,7 +177,7 @@ def change_root (new_root, pathname): ...@@ -178,7 +177,7 @@ def change_root (new_root, pathname):
return os.path.join(new_root, pathname) return os.path.join(new_root, pathname)
else: else:
# Chop off volume name from start of path # Chop off volume name from start of path
elements = string.split(pathname, ":", 1) elements = pathname.split(":", 1)
pathname = ":" + elements[1] pathname = ":" + elements[1]
return os.path.join(new_root, pathname) return os.path.join(new_root, pathname)
...@@ -281,7 +280,7 @@ def split_quoted (s): ...@@ -281,7 +280,7 @@ def split_quoted (s):
# bit of a brain-bender to get it working right, though... # bit of a brain-bender to get it working right, though...
if _wordchars_re is None: _init_regex() if _wordchars_re is None: _init_regex()
s = string.strip(s) s = s.strip()
words = [] words = []
pos = 0 pos = 0
...@@ -294,7 +293,7 @@ def split_quoted (s): ...@@ -294,7 +293,7 @@ def split_quoted (s):
if s[end] in string.whitespace: # unescaped, unquoted whitespace: now if s[end] in string.whitespace: # unescaped, unquoted whitespace: now
words.append(s[:end]) # we definitely have a word delimiter words.append(s[:end]) # we definitely have a word delimiter
s = string.lstrip(s[end:]) s = s[end:].lstrip()
pos = 0 pos = 0
elif s[end] == '\\': # preserve whatever is being escaped; elif s[end] == '\\': # preserve whatever is being escaped;
...@@ -354,7 +353,7 @@ def strtobool (val): ...@@ -354,7 +353,7 @@ def strtobool (val):
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else. 'val' is anything else.
""" """
val = string.lower(val) val = val.lower()
if val in ('y', 'yes', 't', 'true', 'on', '1'): if val in ('y', 'yes', 't', 'true', 'on', '1'):
return 1 return 1
elif val in ('n', 'no', 'f', 'false', 'off', '0'): elif val in ('n', 'no', 'f', 'false', 'off', '0'):
...@@ -445,7 +444,7 @@ files = [ ...@@ -445,7 +444,7 @@ files = [
#if prefix: #if prefix:
# prefix = os.path.abspath(prefix) # prefix = os.path.abspath(prefix)
script.write(string.join(map(repr, py_files), ",\n") + "]\n") script.write(",\n".join(map(repr, py_files)) + "]\n")
script.write(""" script.write("""
byte_compile(files, optimize=%r, force=%r, byte_compile(files, optimize=%r, force=%r,
prefix=%r, base_dir=%r, prefix=%r, base_dir=%r,
...@@ -507,7 +506,6 @@ def rfc822_escape (header): ...@@ -507,7 +506,6 @@ def rfc822_escape (header):
"""Return a version of the string escaped for inclusion in an """Return a version of the string escaped for inclusion in an
RFC-822 header, by ensuring there are 8 spaces space after each newline. RFC-822 header, by ensuring there are 8 spaces space after each newline.
""" """
lines = string.split(header, '\n') lines = [x.strip() for x in header.split('\n')]
lines = map(string.strip, lines) sep = '\n' + 8*' '
header = string.join(lines, '\n' + 8*' ') return sep.join(lines)
return header
...@@ -26,8 +26,7 @@ Every version number class implements the following interface: ...@@ -26,8 +26,7 @@ Every version number class implements the following interface:
of the same class, thus must follow the same rules) of the same class, thus must follow the same rules)
""" """
import string, re import re
from types import StringType
class Version: class Version:
"""Abstract base class for version numbering classes. Just provides """Abstract base class for version numbering classes. Just provides
...@@ -147,12 +146,12 @@ class StrictVersion (Version): ...@@ -147,12 +146,12 @@ class StrictVersion (Version):
match.group(1, 2, 4, 5, 6) match.group(1, 2, 4, 5, 6)
if patch: if patch:
self.version = tuple(map(string.atoi, [major, minor, patch])) self.version = tuple(map(int, [major, minor, patch]))
else: else:
self.version = tuple(map(string.atoi, [major, minor]) + [0]) self.version = tuple(map(int, [major, minor]) + [0])
if prerelease: if prerelease:
self.prerelease = (prerelease[0], string.atoi(prerelease_num)) self.prerelease = (prerelease[0], int(prerelease_num))
else: else:
self.prerelease = None self.prerelease = None
...@@ -160,9 +159,9 @@ class StrictVersion (Version): ...@@ -160,9 +159,9 @@ class StrictVersion (Version):
def __str__ (self): def __str__ (self):
if self.version[2] == 0: if self.version[2] == 0:
vstring = string.join(map(str, self.version[0:2]), '.') vstring = '.'.join(map(str, self.version[0:2]))
else: else:
vstring = string.join(map(str, self.version), '.') vstring = '.'.join(map(str, self.version))
if self.prerelease: if self.prerelease:
vstring = vstring + self.prerelease[0] + str(self.prerelease[1]) vstring = vstring + self.prerelease[0] + str(self.prerelease[1])
...@@ -171,7 +170,7 @@ class StrictVersion (Version): ...@@ -171,7 +170,7 @@ class StrictVersion (Version):
def __cmp__ (self, other): def __cmp__ (self, other):
if isinstance(other, StringType): if isinstance(other, str):
other = StrictVersion(other) other = StrictVersion(other)
compare = cmp(self.version, other.version) compare = cmp(self.version, other.version)
...@@ -327,7 +326,7 @@ class LooseVersion (Version): ...@@ -327,7 +326,7 @@ class LooseVersion (Version):
def __cmp__ (self, other): def __cmp__ (self, other):
if isinstance(other, StringType): if isinstance(other, str):
other = LooseVersion(other) other = LooseVersion(other)
return cmp(self.version, other.version) return cmp(self.version, other.version)
......
...@@ -348,8 +348,7 @@ class StackViewer(ScrolledList): ...@@ -348,8 +348,7 @@ class StackViewer(ScrolledList):
funcname = code.co_name funcname = code.co_name
import linecache import linecache
sourceline = linecache.getline(filename, lineno) sourceline = linecache.getline(filename, lineno)
import string sourceline = sourceline.strip()
sourceline = string.strip(sourceline)
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:
......
...@@ -31,7 +31,6 @@ Each function will be called at most once for each event. ...@@ -31,7 +31,6 @@ Each function will be called at most once for each event.
import sys import sys
import os import os
import string
import re import re
import Tkinter import Tkinter
...@@ -244,7 +243,7 @@ def _parse_sequence(sequence): ...@@ -244,7 +243,7 @@ def _parse_sequence(sequence):
""" """
if not sequence or sequence[0] != '<' or sequence[-1] != '>': if not sequence or sequence[0] != '<' or sequence[-1] != '>':
return None return None
words = string.split(sequence[1:-1], '-') words = '-'.split(sequence[1:-1])
modifiers = 0 modifiers = 0
while words and words[0] in _modifier_names: while words and words[0] in _modifier_names:
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
""" """
from Tkinter import * from Tkinter import *
import string, os import os
import textView import textView
import idlever import idlever
...@@ -70,7 +70,7 @@ class AboutDialog(Toplevel): ...@@ -70,7 +70,7 @@ class AboutDialog(Toplevel):
tkVer[len(tkVer)-1] = str('%.3g' % (float('.'+tkVer[len(tkVer)-1])))[2:] tkVer[len(tkVer)-1] = str('%.3g' % (float('.'+tkVer[len(tkVer)-1])))[2:]
if tkVer[len(tkVer)-1] == '': if tkVer[len(tkVer)-1] == '':
tkVer[len(tkVer)-1] = '0' tkVer[len(tkVer)-1] = '0'
tkVer = string.join(tkVer,'.') tkVer = '.'.join(tkVer)
labelTkVer = Label(frameBg, text='Tk version: '+ labelTkVer = Label(frameBg, text='Tk version: '+
tkVer, fg=self.fg, bg=self.bg) tkVer, fg=self.fg, bg=self.bg)
labelTkVer.grid(row=9, column=1, sticky=W, padx=2, pady=0) labelTkVer.grid(row=9, column=1, sticky=W, padx=2, pady=0)
......
...@@ -11,7 +11,7 @@ Refer to comments in EditorWindow autoindent code for details. ...@@ -11,7 +11,7 @@ Refer to comments in EditorWindow autoindent code for details.
""" """
from Tkinter import * from Tkinter import *
import tkMessageBox, tkColorChooser, tkFont import tkMessageBox, tkColorChooser, tkFont
import string, copy import copy
from configHandler import idleConf from configHandler import idleConf
from dynOptionMenuWidget import DynOptionMenu from dynOptionMenuWidget import DynOptionMenu
...@@ -650,7 +650,7 @@ class ConfigDialog(Toplevel): ...@@ -650,7 +650,7 @@ class ConfigDialog(Toplevel):
newKeys={} newKeys={}
for event in prevKeys.keys(): #add key set to changed items for event in prevKeys.keys(): #add key set to changed items
eventName=event[2:-2] #trim off the angle brackets eventName=event[2:-2] #trim off the angle brackets
binding=string.join(prevKeys[event]) binding=' '.join(prevKeys[event])
newKeys[eventName]=binding newKeys[eventName]=binding
#handle any unsaved changes to prev key set #handle any unsaved changes to prev key set
if prevKeySetName in self.changedItems['keys'].keys(): if prevKeySetName in self.changedItems['keys'].keys():
...@@ -677,7 +677,7 @@ class ConfigDialog(Toplevel): ...@@ -677,7 +677,7 @@ class ConfigDialog(Toplevel):
bindNames.sort() bindNames.sort()
self.listBindings.delete(0,END) self.listBindings.delete(0,END)
for bindName in bindNames: for bindName in bindNames:
key=string.join(keySet[bindName]) #make key(s) into a string key=' '.join(keySet[bindName]) #make key(s) into a string
bindName=bindName[2:-2] #trim off the angle brackets bindName=bindName[2:-2] #trim off the angle brackets
if keySetName in self.changedItems['keys'].keys(): if keySetName in self.changedItems['keys'].keys():
#handle any unsaved changes to this key set #handle any unsaved changes to this key set
...@@ -914,7 +914,7 @@ class ConfigDialog(Toplevel): ...@@ -914,7 +914,7 @@ class ConfigDialog(Toplevel):
self.changedItems['main']['HelpFiles'] = {} self.changedItems['main']['HelpFiles'] = {}
for num in range(1,len(self.userHelpList)+1): for num in range(1,len(self.userHelpList)+1):
self.AddChangedItem('main','HelpFiles',str(num), self.AddChangedItem('main','HelpFiles',str(num),
string.join(self.userHelpList[num-1][:2],';')) ';'.join(self.userHelpList[num-1][:2]))
def LoadFontCfg(self): def LoadFontCfg(self):
##base editor font selection list ##base editor font selection list
......
...@@ -19,7 +19,6 @@ configuration problem notification and resolution. ...@@ -19,7 +19,6 @@ configuration problem notification and resolution.
""" """
import os import os
import sys import sys
import string
import macosxSupport import macosxSupport
from ConfigParser import ConfigParser, NoOptionError, NoSectionError from ConfigParser import ConfigParser, NoOptionError, NoSectionError
...@@ -632,7 +631,7 @@ class IdleConf: ...@@ -632,7 +631,7 @@ class IdleConf:
menuItem='' #make these empty menuItem='' #make these empty
helpPath='' #so value won't be added to list helpPath='' #so value won't be added to list
else: #config entry contains ';' as expected else: #config entry contains ';' as expected
value=string.split(value,';') value=value.split(';')
menuItem=value[0].strip() menuItem=value[0].strip()
helpPath=value[1].strip() helpPath=value[1].strip()
if menuItem and helpPath: #neither are empty strings if menuItem and helpPath: #neither are empty strings
......
...@@ -163,7 +163,7 @@ class GetKeysDialog(Toplevel): ...@@ -163,7 +163,7 @@ class GetKeysDialog(Toplevel):
if finalKey: if finalKey:
finalKey = self.TranslateKey(finalKey, modifiers) finalKey = self.TranslateKey(finalKey, modifiers)
keyList.append(finalKey) keyList.append(finalKey)
self.keyString.set('<' + string.join(keyList,'-') + '>') self.keyString.set('<' + '-'.join(keyList) + '>')
def GetModifiers(self): def GetModifiers(self):
modList = [variable.get() for variable in self.modifier_vars] modList = [variable.get() for variable in self.modifier_vars]
......
...@@ -29,7 +29,7 @@ Here are some of the useful functions provided by this module: ...@@ -29,7 +29,7 @@ Here are some of the useful functions provided by this module:
__author__ = 'Ka-Ping Yee <ping@lfw.org>' __author__ = 'Ka-Ping Yee <ping@lfw.org>'
__date__ = '1 Jan 2001' __date__ = '1 Jan 2001'
import sys, os, types, string, re, dis, imp, tokenize, linecache import sys, os, types, re, dis, imp, tokenize, linecache
from operator import attrgetter from operator import attrgetter
# ----------------------------------------------------------- type-checking # ----------------------------------------------------------- type-checking
...@@ -301,8 +301,8 @@ def getmro(cls): ...@@ -301,8 +301,8 @@ def getmro(cls):
# -------------------------------------------------- source code extraction # -------------------------------------------------- source code extraction
def indentsize(line): def indentsize(line):
"""Return the indent size, in spaces, at the start of a line of text.""" """Return the indent size, in spaces, at the start of a line of text."""
expline = string.expandtabs(line) expline = line.expandtabs()
return len(expline) - len(string.lstrip(expline)) return len(expline) - len(expline.lstrip())
def getdoc(object): def getdoc(object):
"""Get the documentation string for an object. """Get the documentation string for an object.
...@@ -317,14 +317,14 @@ def getdoc(object): ...@@ -317,14 +317,14 @@ def getdoc(object):
if not isinstance(doc, types.StringTypes): if not isinstance(doc, types.StringTypes):
return None return None
try: try:
lines = string.split(string.expandtabs(doc), '\n') lines = doc.expandtabs().split('\n')
except UnicodeError: except UnicodeError:
return None return None
else: else:
# Find minimum indentation of any non-blank lines after first line. # Find minimum indentation of any non-blank lines after first line.
margin = sys.maxint margin = sys.maxint
for line in lines[1:]: for line in lines[1:]:
content = len(string.lstrip(line)) content = len(line.lstrip())
if content: if content:
indent = len(line) - content indent = len(line) - content
margin = min(margin, indent) margin = min(margin, indent)
...@@ -338,7 +338,7 @@ def getdoc(object): ...@@ -338,7 +338,7 @@ def getdoc(object):
lines.pop() lines.pop()
while lines and not lines[0]: while lines and not lines[0]:
lines.pop(0) lines.pop(0)
return string.join(lines, '\n') return '\n'.join(lines)
def getfile(object): def getfile(object):
"""Work out which source or compiled file an object was defined in.""" """Work out which source or compiled file an object was defined in."""
...@@ -382,10 +382,10 @@ def getmodulename(path): ...@@ -382,10 +382,10 @@ def getmodulename(path):
def getsourcefile(object): def getsourcefile(object):
"""Return the Python source file an object was defined in, if it exists.""" """Return the Python source file an object was defined in, if it exists."""
filename = getfile(object) filename = getfile(object)
if string.lower(filename[-4:]) in ('.pyc', '.pyo'): if filename[-4:].lower() in ('.pyc', '.pyo'):
filename = filename[:-4] + '.py' filename = filename[:-4] + '.py'
for suffix, mode, kind in imp.get_suffixes(): for suffix, mode, kind in imp.get_suffixes():
if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix: if 'b' in mode and filename[-len(suffix):].lower() == suffix:
# Looks like a binary file. We want to only return a text file. # Looks like a binary file. We want to only return a text file.
return None return None
if os.path.exists(filename): if os.path.exists(filename):
...@@ -527,36 +527,36 @@ def getcomments(object): ...@@ -527,36 +527,36 @@ def getcomments(object):
# Look for a comment block at the top of the file. # Look for a comment block at the top of the file.
start = 0 start = 0
if lines and lines[0][:2] == '#!': start = 1 if lines and lines[0][:2] == '#!': start = 1
while start < len(lines) and string.strip(lines[start]) in ('', '#'): while start < len(lines) and lines[start].strip() in ('', '#'):
start = start + 1 start = start + 1
if start < len(lines) and lines[start][:1] == '#': if start < len(lines) and lines[start][:1] == '#':
comments = [] comments = []
end = start end = start
while end < len(lines) and lines[end][:1] == '#': while end < len(lines) and lines[end][:1] == '#':
comments.append(string.expandtabs(lines[end])) comments.append(lines[end].expandtabs())
end = end + 1 end = end + 1
return string.join(comments, '') return ''.join(comments)
# Look for a preceding block of comments at the same indentation. # Look for a preceding block of comments at the same indentation.
elif lnum > 0: elif lnum > 0:
indent = indentsize(lines[lnum]) indent = indentsize(lines[lnum])
end = lnum - 1 end = lnum - 1
if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \ if end >= 0 and lines[end].lstrip()[:1] == '#' and \
indentsize(lines[end]) == indent: indentsize(lines[end]) == indent:
comments = [string.lstrip(string.expandtabs(lines[end]))] comments = [lines[end].expandtabs().lstrip()]
if end > 0: if end > 0:
end = end - 1 end = end - 1
comment = string.lstrip(string.expandtabs(lines[end])) comment = lines[end].expandtabs().lstrip()
while comment[:1] == '#' and indentsize(lines[end]) == indent: while comment[:1] == '#' and indentsize(lines[end]) == indent:
comments[:0] = [comment] comments[:0] = [comment]
end = end - 1 end = end - 1
if end < 0: break if end < 0: break
comment = string.lstrip(string.expandtabs(lines[end])) comment = lines[end].expandtabs().lstrip()
while comments and string.strip(comments[0]) == '#': while comments and comments[0].strip() == '#':
comments[:1] = [] comments[:1] = []
while comments and string.strip(comments[-1]) == '#': while comments and comments[-1].strip() == '#':
comments[-1:] = [] comments[-1:] = []
return string.join(comments, '') return ''.join(comments)
class EndOfBlock(Exception): pass class EndOfBlock(Exception): pass
...@@ -628,7 +628,7 @@ def getsource(object): ...@@ -628,7 +628,7 @@ def getsource(object):
or code object. The source code is returned as a single string. An or code object. The source code is returned as a single string. An
IOError is raised if the source code cannot be retrieved.""" IOError is raised if the source code cannot be retrieved."""
lines, lnum = getsourcelines(object) lines, lnum = getsourcelines(object)
return string.join(lines, '') return ''.join(lines)
# --------------------------------------------------- class tree extraction # --------------------------------------------------- class tree extraction
def walktree(classes, children, parent): def walktree(classes, children, parent):
...@@ -801,7 +801,7 @@ def joinseq(seq): ...@@ -801,7 +801,7 @@ def joinseq(seq):
if len(seq) == 1: if len(seq) == 1:
return '(' + seq[0] + ',)' return '(' + seq[0] + ',)'
else: else:
return '(' + string.join(seq, ', ') + ')' return '(' + ', '.join(seq) + ')'
def strseq(object, convert, join=joinseq): def strseq(object, convert, join=joinseq):
"""Recursively walk a sequence, stringifying each element.""" """Recursively walk a sequence, stringifying each element."""
...@@ -866,7 +866,7 @@ def formatargspec(args, varargs=None, varkw=None, defaults=None, ...@@ -866,7 +866,7 @@ def formatargspec(args, varargs=None, varkw=None, defaults=None,
specs.append(spec) specs.append(spec)
if varkw is not None: if varkw is not None:
specs.append(formatvarkw(formatargandannotation(varkw))) specs.append(formatvarkw(formatargandannotation(varkw)))
result = '(' + string.join(specs, ', ') + ')' result = '(' + ', '.join(specs) + ')'
if 'return' in annotations: if 'return' in annotations:
result += formatreturns(formatannotation(annotations['return'])) result += formatreturns(formatannotation(annotations['return']))
return result return result
...@@ -893,7 +893,7 @@ def formatargvalues(args, varargs, varkw, locals, ...@@ -893,7 +893,7 @@ def formatargvalues(args, varargs, varkw, locals,
specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
if varkw: if varkw:
specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
return '(' + string.join(specs, ', ') + ')' return '(' + ', '.join(specs) + ')'
# -------------------------------------------------- stack frame extraction # -------------------------------------------------- stack frame extraction
def getframeinfo(frame, context=1): def getframeinfo(frame, context=1):
......
...@@ -26,7 +26,7 @@ Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved. ...@@ -26,7 +26,7 @@ Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved.
To use, simply 'import logging' and log away! To use, simply 'import logging' and log away!
""" """
import sys, os, types, time, string, cStringIO, traceback import sys, os, types, time, cStringIO, traceback
try: try:
import codecs import codecs
...@@ -54,7 +54,7 @@ __date__ = "16 February 2007" ...@@ -54,7 +54,7 @@ __date__ = "16 February 2007"
# #
if hasattr(sys, 'frozen'): #support for py2exe if hasattr(sys, 'frozen'): #support for py2exe
_srcfile = "logging%s__init__%s" % (os.sep, __file__[-4:]) _srcfile = "logging%s__init__%s" % (os.sep, __file__[-4:])
elif string.lower(__file__[-4:]) in ['.pyc', '.pyo']: elif __file__[-4:].lower() in ['.pyc', '.pyo']:
_srcfile = __file__[:-4] + '.py' _srcfile = __file__[:-4] + '.py'
else: else:
_srcfile = __file__ _srcfile = __file__
...@@ -416,7 +416,7 @@ class Formatter: ...@@ -416,7 +416,7 @@ class Formatter:
formatException() and appended to the message. formatException() and appended to the message.
""" """
record.message = record.getMessage() record.message = record.getMessage()
if string.find(self._fmt,"%(asctime)") >= 0: if self._fmt.find("%(asctime)") >= 0:
record.asctime = self.formatTime(record, self.datefmt) record.asctime = self.formatTime(record, self.datefmt)
s = self._fmt % record.__dict__ s = self._fmt % record.__dict__
if record.exc_info: if record.exc_info:
...@@ -510,7 +510,7 @@ class Filter: ...@@ -510,7 +510,7 @@ class Filter:
return 1 return 1
elif self.name == record.name: elif self.name == record.name:
return 1 return 1
elif string.find(record.name, self.name, 0, self.nlen) != 0: elif record.name.find(self.name, 0, self.nlen) != 0:
return 0 return 0
return (record.name[self.nlen] == ".") return (record.name[self.nlen] == ".")
...@@ -896,7 +896,7 @@ class Manager: ...@@ -896,7 +896,7 @@ class Manager:
from the specified logger to the root of the logger hierarchy. from the specified logger to the root of the logger hierarchy.
""" """
name = alogger.name name = alogger.name
i = string.rfind(name, ".") i = name.rfind(".")
rv = None rv = None
while (i > 0) and not rv: while (i > 0) and not rv:
substr = name[:i] substr = name[:i]
...@@ -909,7 +909,7 @@ class Manager: ...@@ -909,7 +909,7 @@ class Manager:
else: else:
assert isinstance(obj, PlaceHolder) assert isinstance(obj, PlaceHolder)
obj.append(alogger) obj.append(alogger)
i = string.rfind(name, ".", 0, i - 1) i = name.rfind(".", 0, i - 1)
if not rv: if not rv:
rv = self.root rv = self.root
alogger.parent = rv alogger.parent = rv
......
...@@ -27,7 +27,7 @@ Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved. ...@@ -27,7 +27,7 @@ Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved.
To use, simply 'import logging' and log away! To use, simply 'import logging' and log away!
""" """
import sys, logging, logging.handlers, string, socket, struct, os, traceback, types import sys, logging, logging.handlers, socket, struct, os, traceback, types
try: try:
import thread import thread
...@@ -89,7 +89,7 @@ def fileConfig(fname, defaults=None): ...@@ -89,7 +89,7 @@ def fileConfig(fname, defaults=None):
def _resolve(name): def _resolve(name):
"""Resolve a dotted name to a global object.""" """Resolve a dotted name to a global object."""
name = string.split(name, '.') name = name.split('.')
used = name.pop(0) used = name.pop(0)
found = __import__(used) found = __import__(used)
for n in name: for n in name:
...@@ -107,10 +107,10 @@ def _create_formatters(cp): ...@@ -107,10 +107,10 @@ def _create_formatters(cp):
flist = cp.get("formatters", "keys") flist = cp.get("formatters", "keys")
if not len(flist): if not len(flist):
return {} return {}
flist = string.split(flist, ",") flist = flist.split(",")
formatters = {} formatters = {}
for form in flist: for form in flist:
sectname = "formatter_%s" % string.strip(form) sectname = "formatter_%s" % form.strip()
opts = cp.options(sectname) opts = cp.options(sectname)
if "format" in opts: if "format" in opts:
fs = cp.get(sectname, "format", 1) fs = cp.get(sectname, "format", 1)
...@@ -135,11 +135,11 @@ def _install_handlers(cp, formatters): ...@@ -135,11 +135,11 @@ def _install_handlers(cp, formatters):
hlist = cp.get("handlers", "keys") hlist = cp.get("handlers", "keys")
if not len(hlist): if not len(hlist):
return {} return {}
hlist = string.split(hlist, ",") hlist = hlist.split(",")
handlers = {} handlers = {}
fixups = [] #for inter-handler references fixups = [] #for inter-handler references
for hand in hlist: for hand in hlist:
sectname = "handler_%s" % string.strip(hand) sectname = "handler_%s" % hand.strip()
klass = cp.get(sectname, "class") klass = cp.get(sectname, "class")
opts = cp.options(sectname) opts = cp.options(sectname)
if "formatter" in opts: if "formatter" in opts:
...@@ -175,8 +175,8 @@ def _install_loggers(cp, handlers): ...@@ -175,8 +175,8 @@ def _install_loggers(cp, handlers):
# configure the root first # configure the root first
llist = cp.get("loggers", "keys") llist = cp.get("loggers", "keys")
llist = string.split(llist, ",") llist = llist.split(",")
llist = map(lambda x: string.strip(x), llist) llist = map(lambda x: x.strip(), llist)
llist.remove("root") llist.remove("root")
sectname = "logger_root" sectname = "logger_root"
root = logging.root root = logging.root
...@@ -189,9 +189,9 @@ def _install_loggers(cp, handlers): ...@@ -189,9 +189,9 @@ def _install_loggers(cp, handlers):
root.removeHandler(h) root.removeHandler(h)
hlist = cp.get(sectname, "handlers") hlist = cp.get(sectname, "handlers")
if len(hlist): if len(hlist):
hlist = string.split(hlist, ",") hlist = hlist.split(",")
for hand in hlist: for hand in hlist:
log.addHandler(handlers[string.strip(hand)]) log.addHandler(handlers[hand.strip()])
#and now the others... #and now the others...
#we don't want to lose the existing loggers, #we don't want to lose the existing loggers,
...@@ -224,9 +224,9 @@ def _install_loggers(cp, handlers): ...@@ -224,9 +224,9 @@ def _install_loggers(cp, handlers):
logger.disabled = 0 logger.disabled = 0
hlist = cp.get(sectname, "handlers") hlist = cp.get(sectname, "handlers")
if len(hlist): if len(hlist):
hlist = string.split(hlist, ",") hlist = hlist.split(",")
for hand in hlist: for hand in hlist:
logger.addHandler(handlers[string.strip(hand)]) logger.addHandler(handlers[hand.strip()])
#Disable any old loggers. There's no point deleting #Disable any old loggers. There's no point deleting
#them as other threads may continue to hold references #them as other threads may continue to hold references
......
...@@ -27,7 +27,7 @@ Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved. ...@@ -27,7 +27,7 @@ Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved.
To use, simply 'import logging' and log away! To use, simply 'import logging' and log away!
""" """
import sys, logging, socket, types, os, string, struct, time, glob import sys, logging, socket, types, os, struct, time, glob
try: try:
import cPickle as pickle import cPickle as pickle
except ImportError: except ImportError:
...@@ -162,7 +162,7 @@ class TimedRotatingFileHandler(BaseRotatingHandler): ...@@ -162,7 +162,7 @@ class TimedRotatingFileHandler(BaseRotatingHandler):
""" """
def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None): def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None):
BaseRotatingHandler.__init__(self, filename, 'a', encoding) BaseRotatingHandler.__init__(self, filename, 'a', encoding)
self.when = string.upper(when) self.when = when.upper()
self.backupCount = backupCount self.backupCount = backupCount
# Calculate the real rollover interval, which is just the number of # Calculate the real rollover interval, which is just the number of
# seconds between rollovers. Also set the filename suffix used when # seconds between rollovers. Also set the filename suffix used when
...@@ -792,7 +792,7 @@ class SMTPHandler(logging.Handler): ...@@ -792,7 +792,7 @@ class SMTPHandler(logging.Handler):
msg = self.format(record) msg = self.format(record)
msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
self.fromaddr, self.fromaddr,
string.join(self.toaddrs, ","), ",".join(self.toaddrs),
self.getSubject(record), self.getSubject(record),
formatdate(), msg) formatdate(), msg)
smtp.sendmail(self.fromaddr, self.toaddrs, msg) smtp.sendmail(self.fromaddr, self.toaddrs, msg)
...@@ -913,7 +913,7 @@ class HTTPHandler(logging.Handler): ...@@ -913,7 +913,7 @@ class HTTPHandler(logging.Handler):
("GET" or "POST") ("GET" or "POST")
""" """
logging.Handler.__init__(self) logging.Handler.__init__(self)
method = string.upper(method) method = method.upper()
if method not in ["GET", "POST"]: if method not in ["GET", "POST"]:
raise ValueError, "method must be GET or POST" raise ValueError, "method must be GET or POST"
self.host = host self.host = host
...@@ -941,7 +941,7 @@ class HTTPHandler(logging.Handler): ...@@ -941,7 +941,7 @@ class HTTPHandler(logging.Handler):
url = self.url url = self.url
data = urllib.urlencode(self.mapLogRecord(record)) data = urllib.urlencode(self.mapLogRecord(record))
if self.method == "GET": if self.method == "GET":
if (string.find(url, '?') >= 0): if (url.find('?') >= 0):
sep = '&' sep = '&'
else: else:
sep = '?' sep = '?'
...@@ -949,7 +949,7 @@ class HTTPHandler(logging.Handler): ...@@ -949,7 +949,7 @@ class HTTPHandler(logging.Handler):
h.putrequest(self.method, url) h.putrequest(self.method, url)
# support multiple hosts on one IP address... # support multiple hosts on one IP address...
# need to strip optional :port from host, if present # need to strip optional :port from host, if present
i = string.find(host, ":") i = host.find(":")
if i >= 0: if i >= 0:
host = host[:i] host = host[:i]
h.putheader("Host", host) h.putheader("Host", host)
......
...@@ -14,14 +14,14 @@ ...@@ -14,14 +14,14 @@
# You can then use c.write() to write out the changed values to the # You can then use c.write() to write out the changed values to the
# .cdplayerrc file. # .cdplayerrc file.
import string, posix, os import posix, os
_cddbrc = '.cddb' _cddbrc = '.cddb'
_DB_ID_NTRACKS = 5 _DB_ID_NTRACKS = 5
_dbid_map = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ@_=+abcdefghijklmnopqrstuvwxyz' _dbid_map = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ@_=+abcdefghijklmnopqrstuvwxyz'
def _dbid(v): def _dbid(v):
if v >= len(_dbid_map): if v >= len(_dbid_map):
return string.zfill(v, 2) return v.zfill(2)
else: else:
return _dbid_map[v] return _dbid_map[v]
...@@ -164,11 +164,10 @@ class Cddb: ...@@ -164,11 +164,10 @@ class Cddb:
for i in range(nidtracks): for i in range(nidtracks):
start, length = tracklist[i] start, length = tracklist[i]
self.id = self.id + _dbid(length[0]) + _dbid(length[1]) self.id = self.id + _dbid(length[0]) + _dbid(length[1])
self.toc = string.zfill(ntracks, 2) self.toc = ntracks.zfill(2)
for track in tracklist: for track in tracklist:
start, length = track start, length = track
self.toc = self.toc + string.zfill(length[0], 2) + \ self.toc = self.toc + length[0].zfill(2) + length[1].zfill(2)
string.zfill(length[1], 2)
def write(self): def write(self):
import posixpath import posixpath
......
...@@ -18,7 +18,6 @@ cdplayerrc = '.cdplayerrc' ...@@ -18,7 +18,6 @@ cdplayerrc = '.cdplayerrc'
class Cdplayer: class Cdplayer:
def __init__(self, tracklist): def __init__(self, tracklist):
import string
self.artist = '' self.artist = ''
self.title = '' self.title = ''
if type(tracklist) == type(''): if type(tracklist) == type(''):
...@@ -29,11 +28,11 @@ class Cdplayer: ...@@ -29,11 +28,11 @@ class Cdplayer:
int(tracklist[i+2:i+4])))) int(tracklist[i+2:i+4]))))
tracklist = t tracklist = t
self.track = [None] + [''] * len(tracklist) self.track = [None] + [''] * len(tracklist)
self.id = 'd' + string.zfill(len(tracklist), 2) self.id = 'd' + repr(len(tracklist)).zfill(2)
for track in tracklist: for track in tracklist:
start, length = track start, length = track
self.id = self.id + string.zfill(length[0], 2) + \ self.id = self.id + repr(length[0]).zfill(2) + \
string.zfill(length[1], 2) repr(length[1]).zfill(2)
try: try:
import posix import posix
f = open(posix.environ['HOME'] + '/' + cdplayerrc, 'r') f = open(posix.environ['HOME'] + '/' + cdplayerrc, 'r')
......
...@@ -30,7 +30,6 @@ from Carbon import Menu ...@@ -30,7 +30,6 @@ from Carbon import Menu
from Carbon import AE from Carbon import AE
import Nav import Nav
import MacOS import MacOS
import string
from Carbon.ControlAccessor import * # Also import Controls constants from Carbon.ControlAccessor import * # Also import Controls constants
import Carbon.File import Carbon.File
import macresource import macresource
...@@ -54,12 +53,12 @@ def _interact(): ...@@ -54,12 +53,12 @@ def _interact():
def cr2lf(text): def cr2lf(text):
if '\r' in text: if '\r' in text:
text = string.join(string.split(text, '\r'), '\n') text = '\n'.join(text.split('\r'))
return text return text
def lf2cr(text): def lf2cr(text):
if '\n' in text: if '\n' in text:
text = string.join(string.split(text, '\n'), '\r') text = '\r'.join(text.split('\n'))
if len(text) > 253: if len(text) > 253:
text = text[:253] + '\311' text = text[:253] + '\311'
return text return text
...@@ -543,7 +542,7 @@ def GetArgv(optionlist=None, commandlist=None, addoldfile=1, addnewfile=1, addfo ...@@ -543,7 +542,7 @@ def GetArgv(optionlist=None, commandlist=None, addoldfile=1, addnewfile=1, addfo
d.SelectDialogItemText(ARGV_CMDLINE_DATA, 0x7fff, 0x7fff) d.SelectDialogItemText(ARGV_CMDLINE_DATA, 0x7fff, 0x7fff)
h = d.GetDialogItemAsControl(ARGV_CMDLINE_DATA) h = d.GetDialogItemAsControl(ARGV_CMDLINE_DATA)
oldstr = GetDialogItemText(h) oldstr = GetDialogItemText(h)
tmplist = string.split(oldstr) tmplist = oldstr.split()
newlist = [] newlist = []
while tmplist: while tmplist:
item = tmplist[0] item = tmplist[0]
......
...@@ -13,9 +13,7 @@ coerce(x, wanted_sample) coerces a python object to another python object ...@@ -13,9 +13,7 @@ coerce(x, wanted_sample) coerces a python object to another python object
# #
import struct import struct
import string
import types import types
from string import strip
from types import * from types import *
from Carbon import AE from Carbon import AE
from Carbon.AppleEvents import * from Carbon.AppleEvents import *
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
from Carbon.AppleEvents import * from Carbon.AppleEvents import *
import struct import struct
from types import * from types import *
import string
# #
# convoluted, since there are cyclic dependencies between this file and # convoluted, since there are cyclic dependencies between this file and
...@@ -41,7 +40,7 @@ class Enum: ...@@ -41,7 +40,7 @@ class Enum:
return "Enum(%r)" % (self.enum,) return "Enum(%r)" % (self.enum,)
def __str__(self): def __str__(self):
return string.strip(self.enum) return self.enum.strip()
def __aepack__(self): def __aepack__(self):
return pack(self.enum, typeEnumeration) return pack(self.enum, typeEnumeration)
...@@ -108,7 +107,7 @@ class Type: ...@@ -108,7 +107,7 @@ class Type:
return "Type(%r)" % (self.type,) return "Type(%r)" % (self.type,)
def __str__(self): def __str__(self):
return string.strip(self.type) return self.type.strip()
def __aepack__(self): def __aepack__(self):
return pack(self.type, typeType) return pack(self.type, typeType)
...@@ -131,7 +130,7 @@ class Keyword: ...@@ -131,7 +130,7 @@ class Keyword:
return "Keyword(%r)" % self.keyword return "Keyword(%r)" % self.keyword
def __str__(self): def __str__(self):
return string.strip(self.keyword) return self.keyword.strip()
def __aepack__(self): def __aepack__(self):
return pack(self.keyword, typeKeyword) return pack(self.keyword, typeKeyword)
...@@ -170,7 +169,7 @@ class Comparison: ...@@ -170,7 +169,7 @@ class Comparison:
return "Comparison(%r, %r, %r)" % (self.obj1, self.relo, self.obj2) return "Comparison(%r, %r, %r)" % (self.obj1, self.relo, self.obj2)
def __str__(self): def __str__(self):
return "%s %s %s" % (nice(self.obj1), string.strip(self.relo), nice(self.obj2)) return "%s %s %s" % (nice(self.obj1), self.relo.strip(), nice(self.obj2))
def __aepack__(self): def __aepack__(self):
return pack({'obj1': self.obj1, return pack({'obj1': self.obj1,
...@@ -198,7 +197,7 @@ class Ordinal: ...@@ -198,7 +197,7 @@ class Ordinal:
return "Ordinal(%r)" % (self.abso,) return "Ordinal(%r)" % (self.abso,)
def __str__(self): def __str__(self):
return "%s" % (string.strip(self.abso)) return "%s" % (self.abso.strip())
def __aepack__(self): def __aepack__(self):
return pack(self.abso, 'abso') return pack(self.abso, 'abso')
...@@ -225,10 +224,10 @@ class Logical: ...@@ -225,10 +224,10 @@ class Logical:
def __str__(self): def __str__(self):
if type(self.term) == ListType and len(self.term) == 2: if type(self.term) == ListType and len(self.term) == 2:
return "%s %s %s" % (nice(self.term[0]), return "%s %s %s" % (nice(self.term[0]),
string.strip(self.logc), self.logc.strip(),
nice(self.term[1])) nice(self.term[1]))
else: else:
return "%s(%s)" % (string.strip(self.logc), nice(self.term)) return "%s(%s)" % (self.logc.strip(), nice(self.term))
def __aepack__(self): def __aepack__(self):
return pack({'logc': mkenum(self.logc), 'term': self.term}, 'logi') return pack({'logc': mkenum(self.logc), 'term': self.term}, 'logi')
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
import sys import sys
import os import os
import string
import imp import imp
import marshal import marshal
from Carbon import Res from Carbon import Res
...@@ -86,7 +85,7 @@ def process(template, filename, destname, copy_codefragment=0, ...@@ -86,7 +85,7 @@ def process(template, filename, destname, copy_codefragment=0,
# Set the destination file name. Note that basename # Set the destination file name. Note that basename
# does contain the whole filepath, only a .py is stripped. # does contain the whole filepath, only a .py is stripped.
if string.lower(filename[-3:]) == ".py": if filename[-3:].lower() == ".py":
basename = filename[:-3] basename = filename[:-3]
if MacOS.runtimemodel != 'macho' and not destname: if MacOS.runtimemodel != 'macho' and not destname:
destname = basename destname = basename
...@@ -347,7 +346,7 @@ def copyres(input, output, skiptypes, skipowner, progress=None): ...@@ -347,7 +346,7 @@ def copyres(input, output, skiptypes, skipowner, progress=None):
for ires in range(1, 1+nresources): for ires in range(1, 1+nresources):
res = Res.Get1IndResource(type, ires) res = Res.Get1IndResource(type, ires)
id, type, name = res.GetResInfo() id, type, name = res.GetResInfo()
lcname = string.lower(name) lcname = name.lower()
if lcname == OWNERNAME and id == 0: if lcname == OWNERNAME and id == 0:
if skipowner: if skipowner:
......
...@@ -698,7 +698,7 @@ class SuiteCompiler: ...@@ -698,7 +698,7 @@ class SuiteCompiler:
"""Generate class boilerplate""" """Generate class boilerplate"""
classname = '%s_Events'%self.modname classname = '%s_Events'%self.modname
if self.basemodule: if self.basemodule:
modshortname = string.split(self.basemodule.__name__, '.')[-1] modshortname = self.basemodule.__name__.split('.')[-1]
baseclassname = '%s_Events'%modshortname baseclassname = '%s_Events'%modshortname
self.fp.write("class %s(%s):\n\n"%(classname, baseclassname)) self.fp.write("class %s(%s):\n\n"%(classname, baseclassname))
else: else:
...@@ -1169,7 +1169,7 @@ def compiledataflags(flags): ...@@ -1169,7 +1169,7 @@ def compiledataflags(flags):
bits.append(dataflagdict[i]) bits.append(dataflagdict[i])
else: else:
bits.append(repr(i)) bits.append(repr(i))
return '[%s]' % string.join(bits) return '[%s]' % ' '.join(bits)
def ascii(str): def ascii(str):
"""Return a string with all non-ascii characters hex-encoded""" """Return a string with all non-ascii characters hex-encoded"""
......
"""IC wrapper module, based on Internet Config 1.3""" """IC wrapper module, based on Internet Config 1.3"""
import icglue import icglue
import string
import sys import sys
import os import os
from Carbon import Res from Carbon import Res
...@@ -135,7 +134,7 @@ _decoder_table = { ...@@ -135,7 +134,7 @@ _decoder_table = {
def _decode(data, key): def _decode(data, key):
if '\245' in key: if '\245' in key:
key2 = key[:string.index(key, '\245')+1] key2 = key[:key.index('\245')+1]
else: else:
key2 = key key2 = key
if key2 in _decoder_table: if key2 in _decoder_table:
...@@ -148,7 +147,7 @@ def _code(data, key): ...@@ -148,7 +147,7 @@ def _code(data, key):
if type(data) == _ICOpaqueDataType: if type(data) == _ICOpaqueDataType:
return data.data return data.data
if '\245' in key: if '\245' in key:
key2 = key[:string.index(key, '\245')+1] key2 = key[:key.index('\245')+1]
else: else:
key2 = key key2 = key
if key2 in _decoder_table: if key2 in _decoder_table:
......
...@@ -59,13 +59,13 @@ def _split(p): ...@@ -59,13 +59,13 @@ def _split(p):
""" """
dash= _allowMOSFSNames and p[:1]=='-' dash= _allowMOSFSNames and p[:1]=='-'
if dash: if dash:
q= string.find(p, '-', 1)+1 q= p.find('-', 1)+1
else: else:
if p[:1]==':': if p[:1]==':':
q= 0 q= 0
else: else:
q= string.find(p, ':')+1 # q= index of start of non-FS portion of path q= p.find(':')+1 # q= index of start of non-FS portion of path
s= string.find(p, '#') s= p.find('#')
if s==-1 or s>q: if s==-1 or s>q:
s= q # find end of main FS name, not including special field s= q # find end of main FS name, not including special field
else: else:
...@@ -75,7 +75,7 @@ def _split(p): ...@@ -75,7 +75,7 @@ def _split(p):
break # disallow invalid non-special-field characters in FS name break # disallow invalid non-special-field characters in FS name
r= q r= q
if p[q:q+1]==':': if p[q:q+1]==':':
r= string.find(p, '.', q+1)+1 r= p.find('.', q+1)+1
if r==0: if r==0:
r= len(p) # find end of drive name (if any) following FS name (if any) r= len(p) # find end of drive name (if any) following FS name (if any)
return (p[:q], p[q:r], p[r:]) return (p[:q], p[q:r], p[r:])
...@@ -87,7 +87,7 @@ def normcase(p): ...@@ -87,7 +87,7 @@ def normcase(p):
OS filesystems are case-insensitive. However, not all filesystems have to be, OS filesystems are case-insensitive. However, not all filesystems have to be,
and there's no simple way to find out what type an FS is argh. and there's no simple way to find out what type an FS is argh.
""" """
return string.lower(p) return p.lower()
def isabs(p): def isabs(p):
...@@ -126,7 +126,7 @@ def split(p): ...@@ -126,7 +126,7 @@ def split(p):
name must still be dealt with separately since special field may contain '.'. name must still be dealt with separately since special field may contain '.'.
""" """
(fs, drive, path)= _split(p) (fs, drive, path)= _split(p)
q= string.rfind(path, '.') q= path.rfind('.')
if q!=-1: if q!=-1:
return (fs+drive+path[:q], path[q+1:]) return (fs+drive+path[:q], path[q+1:])
return ('', p) return ('', p)
...@@ -139,7 +139,7 @@ def splitext(p): ...@@ -139,7 +139,7 @@ def splitext(p):
""" """
(tail, head)= split(p) (tail, head)= split(p)
if '/' in head: if '/' in head:
q= len(head)-string.rfind(head, '/') q= len(head)-head.rfind('/')
return (p[:-q], p[-q:]) return (p[:-q], p[-q:])
return (p, '') return (p, '')
...@@ -291,7 +291,7 @@ def expanduser(p): ...@@ -291,7 +291,7 @@ def expanduser(p):
fsname= fs[1:-1] fsname= fs[1:-1]
else: else:
fsname= fs[:-1] fsname= fs[:-1]
fsname= string.split(fsname, '#', 1)[0] # remove special field from fs fsname= fsname.split('#', 1)[0] # remove special field from fs
x= swi.swi('OS_FSControl', 'ib2s.i;.....i', 54, b, fsname, l) x= swi.swi('OS_FSControl', 'ib2s.i;.....i', 54, b, fsname, l)
if x<l: if x<l:
urd= b.tostring(0, l-x-1) urd= b.tostring(0, l-x-1)
......
...@@ -21,7 +21,7 @@ def url2pathname(url): ...@@ -21,7 +21,7 @@ def url2pathname(url):
url = url[2:] url = url[2:]
elif url[:2] == '//': elif url[:2] == '//':
raise RuntimeError, 'Cannot convert non-local URL to pathname' raise RuntimeError, 'Cannot convert non-local URL to pathname'
components = string.split(url, '/') components = url.split('/')
if not components[0]: if not components[0]:
if '$' in components: if '$' in components:
del components[0] del components[0]
......
...@@ -112,7 +112,7 @@ __copyright__ = """ ...@@ -112,7 +112,7 @@ __copyright__ = """
__version__ = '1.0.6' __version__ = '1.0.6'
import sys,string,os,re import sys, os, re
### Platform specific APIs ### Platform specific APIs
...@@ -189,15 +189,15 @@ def _dist_try_harder(distname,version,id): ...@@ -189,15 +189,15 @@ def _dist_try_harder(distname,version,id):
info = open('/var/adm/inst-log/info').readlines() info = open('/var/adm/inst-log/info').readlines()
distname = 'SuSE' distname = 'SuSE'
for line in info: for line in info:
tv = string.split(line) tv = line.split()
if len(tv) == 2: if len(tv) == 2:
tag,value = tv tag,value = tv
else: else:
continue continue
if tag == 'MIN_DIST_VERSION': if tag == 'MIN_DIST_VERSION':
version = string.strip(value) version = value.strip()
elif tag == 'DIST_IDENT': elif tag == 'DIST_IDENT':
values = string.split(value,'-') values = value.split('-')
id = values[2] id = values[2]
return distname,version,id return distname,version,id
...@@ -205,7 +205,7 @@ def _dist_try_harder(distname,version,id): ...@@ -205,7 +205,7 @@ def _dist_try_harder(distname,version,id):
# Caldera OpenLinux has some infos in that file (thanks to Colin Kong) # Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
info = open('/etc/.installed').readlines() info = open('/etc/.installed').readlines()
for line in info: for line in info:
pkg = string.split(line,'-') pkg = line.split('-')
if len(pkg) >= 2 and pkg[0] == 'OpenLinux': if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
# XXX does Caldera support non Intel platforms ? If yes, # XXX does Caldera support non Intel platforms ? If yes,
# where can we find the needed id ? # where can we find the needed id ?
...@@ -258,7 +258,7 @@ def _parse_release_file(firstline): ...@@ -258,7 +258,7 @@ def _parse_release_file(firstline):
return tuple(m.groups()) return tuple(m.groups())
# Unkown format... take the first two words # Unkown format... take the first two words
l = string.split(string.strip(firstline)) l = firstline.strip().split()
if l: if l:
version = l[0] version = l[0]
if len(l) > 1: if len(l) > 1:
...@@ -451,7 +451,7 @@ def _norm_version(version, build=''): ...@@ -451,7 +451,7 @@ def _norm_version(version, build=''):
""" Normalize the version and build strings and return a single """ Normalize the version and build strings and return a single
version string using the format major.minor.build (or patchlevel). version string using the format major.minor.build (or patchlevel).
""" """
l = string.split(version,'.') l = version.split('.')
if build: if build:
l.append(build) l.append(build)
try: try:
...@@ -460,7 +460,7 @@ def _norm_version(version, build=''): ...@@ -460,7 +460,7 @@ def _norm_version(version, build=''):
strings = l strings = l
else: else:
strings = map(str,ints) strings = map(str,ints)
version = string.join(strings[:3],'.') version = '.'.join(strings[:3])
return version return version
_ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) ' _ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
...@@ -505,7 +505,7 @@ def _syscmd_ver(system='', release='', version='', ...@@ -505,7 +505,7 @@ def _syscmd_ver(system='', release='', version='',
return system,release,version return system,release,version
# Parse the output # Parse the output
info = string.strip(info) info = info.strip()
m = _ver_output.match(info) m = _ver_output.match(info)
if m is not None: if m is not None:
system,release,version = m.groups() system,release,version = m.groups()
...@@ -766,7 +766,7 @@ def system_alias(system,release,version): ...@@ -766,7 +766,7 @@ def system_alias(system,release,version):
# These releases use the old name SunOS # These releases use the old name SunOS
return system,release,version return system,release,version
# Modify release (marketing release = SunOS release - 3) # Modify release (marketing release = SunOS release - 3)
l = string.split(release,'.') l = release.split('.')
if l: if l:
try: try:
major = int(l[0]) major = int(l[0])
...@@ -775,7 +775,7 @@ def system_alias(system,release,version): ...@@ -775,7 +775,7 @@ def system_alias(system,release,version):
else: else:
major = major - 3 major = major - 3
l[0] = str(major) l[0] = str(major)
release = string.join(l,'.') release = '.'.join(l)
if release < '6': if release < '6':
system = 'Solaris' system = 'Solaris'
else: else:
...@@ -806,28 +806,24 @@ def _platform(*args): ...@@ -806,28 +806,24 @@ def _platform(*args):
compatible format e.g. "system-version-machine". compatible format e.g. "system-version-machine".
""" """
# Format the platform string # Format the platform string
platform = string.join( platform = '-'.join(x.strip() for x in filter(len, args))
map(string.strip,
filter(len, args)),
'-')
# Cleanup some possible filename obstacles... # Cleanup some possible filename obstacles...
replace = string.replace platform = platform.replace(' ','_')
platform = replace(platform,' ','_') platform = platform.replace('/','-')
platform = replace(platform,'/','-') platform = platform.replace('\\','-')
platform = replace(platform,'\\','-') platform = platform.replace(':','-')
platform = replace(platform,':','-') platform = platform.replace(';','-')
platform = replace(platform,';','-') platform = platform.replace('"','-')
platform = replace(platform,'"','-') platform = platform.replace('(','-')
platform = replace(platform,'(','-') platform = platform.replace(')','-')
platform = replace(platform,')','-')
# No need to report 'unknown' information... # No need to report 'unknown' information...
platform = replace(platform,'unknown','') platform = platform.replace('unknown','')
# Fold '--'s and remove trailing '-' # Fold '--'s and remove trailing '-'
while 1: while 1:
cleaned = replace(platform,'--','-') cleaned = platform.replace('--','-')
if cleaned == platform: if cleaned == platform:
break break
platform = cleaned platform = cleaned
...@@ -889,7 +885,7 @@ def _syscmd_uname(option,default=''): ...@@ -889,7 +885,7 @@ def _syscmd_uname(option,default=''):
f = os.popen('uname %s 2> /dev/null' % option) f = os.popen('uname %s 2> /dev/null' % option)
except (AttributeError,os.error): except (AttributeError,os.error):
return default return default
output = string.strip(f.read()) output = f.read().strip()
rc = f.close() rc = f.close()
if not output or rc: if not output or rc:
return default return default
...@@ -911,7 +907,7 @@ def _syscmd_file(target,default=''): ...@@ -911,7 +907,7 @@ def _syscmd_file(target,default=''):
f = os.popen('file %s 2> /dev/null' % target) f = os.popen('file %s 2> /dev/null' % target)
except (AttributeError,os.error): except (AttributeError,os.error):
return default return default
output = string.strip(f.read()) output = f.read().strip()
rc = f.close() rc = f.close()
if not output or rc: if not output or rc:
return default return default
...@@ -1082,7 +1078,7 @@ def uname(): ...@@ -1082,7 +1078,7 @@ def uname():
elif system[:4] == 'java': elif system[:4] == 'java':
release,vendor,vminfo,osinfo = java_ver() release,vendor,vminfo,osinfo = java_ver()
system = 'Java' system = 'Java'
version = string.join(vminfo,', ') version = ', '.join(vminfo)
if not version: if not version:
version = vendor version = vendor
...@@ -1285,10 +1281,10 @@ def _sys_version(sys_version=None): ...@@ -1285,10 +1281,10 @@ def _sys_version(sys_version=None):
builddate = builddate + ' ' + buildtime builddate = builddate + ' ' + buildtime
# Add the patchlevel version if missing # Add the patchlevel version if missing
l = string.split(version, '.') l = version.split('.')
if len(l) == 2: if len(l) == 2:
l.append('0') l.append('0')
version = string.join(l, '.') version = '.'.join(l)
# Build and cache the result # Build and cache the result
result = (name, version, branch, revision, buildno, builddate, compiler) result = (name, version, branch, revision, buildno, builddate, compiler)
...@@ -1345,7 +1341,7 @@ def python_version_tuple(): ...@@ -1345,7 +1341,7 @@ def python_version_tuple():
""" """
if hasattr(sys, 'version_info'): if hasattr(sys, 'version_info'):
return sys.version_info[:3] return sys.version_info[:3]
return tuple(string.split(_sys_version()[1], '.')) return tuple(_sys_version()[1].split('.'))
def python_branch(): def python_branch():
......
...@@ -54,7 +54,6 @@ Richard Chamberlain, for the first implementation of textdoc. ...@@ -54,7 +54,6 @@ Richard Chamberlain, for the first implementation of textdoc.
import sys, imp, os, re, types, inspect, __builtin__, pkgutil import sys, imp, os, re, types, inspect, __builtin__, pkgutil
from repr import Repr from repr import Repr
from string import expandtabs, find, join, lower, split, strip, rfind, rstrip
try: try:
from collections import deque from collections import deque
except ImportError: except ImportError:
...@@ -80,16 +79,16 @@ def pathdirs(): ...@@ -80,16 +79,16 @@ def pathdirs():
def getdoc(object): def getdoc(object):
"""Get the doc string or comments for an object.""" """Get the doc string or comments for an object."""
result = inspect.getdoc(object) or inspect.getcomments(object) result = inspect.getdoc(object) or inspect.getcomments(object)
return result and re.sub('^ *\n', '', rstrip(result)) or '' return result and re.sub('^ *\n', '', result.rstrip()) or ''
def splitdoc(doc): def splitdoc(doc):
"""Split a doc string into a synopsis line (if any) and the rest.""" """Split a doc string into a synopsis line (if any) and the rest."""
lines = split(strip(doc), '\n') lines = doc.strip().split('\n')
if len(lines) == 1: if len(lines) == 1:
return lines[0], '' return lines[0], ''
elif len(lines) >= 2 and not rstrip(lines[1]): elif len(lines) >= 2 and not lines[1].rstrip():
return lines[0], join(lines[2:], '\n') return lines[0], '\n'.join(lines[2:])
return '', join(lines, '\n') return '', '\n'.join(lines)
def classname(object, modname): def classname(object, modname):
"""Get a class name and qualify it with a module name if necessary.""" """Get a class name and qualify it with a module name if necessary."""
...@@ -107,7 +106,7 @@ def isdata(object): ...@@ -107,7 +106,7 @@ def isdata(object):
def replace(text, *pairs): def replace(text, *pairs):
"""Do a series of global replacements on a string.""" """Do a series of global replacements on a string."""
while pairs: while pairs:
text = join(split(text, pairs[0]), pairs[1]) text = pairs[1].join(text.split(pairs[0]))
pairs = pairs[2:] pairs = pairs[2:]
return text return text
...@@ -190,18 +189,18 @@ def ispackage(path): ...@@ -190,18 +189,18 @@ def ispackage(path):
def source_synopsis(file): def source_synopsis(file):
line = file.readline() line = file.readline()
while line[:1] == '#' or not strip(line): while line[:1] == '#' or not line.strip():
line = file.readline() line = file.readline()
if not line: break if not line: break
line = strip(line) line = line.strip()
if line[:4] == 'r"""': line = line[1:] if line[:4] == 'r"""': line = line[1:]
if line[:3] == '"""': if line[:3] == '"""':
line = line[3:] line = line[3:]
if line[-1:] == '\\': line = line[:-1] if line[-1:] == '\\': line = line[:-1]
while not strip(line): while not line.strip():
line = file.readline() line = file.readline()
if not line: break if not line: break
result = strip(split(line, '"""')[0]) result = line.split('"""')[0].strip()
else: result = None else: result = None
return result return result
...@@ -297,13 +296,13 @@ def safeimport(path, forceload=0, cache={}): ...@@ -297,13 +296,13 @@ def safeimport(path, forceload=0, cache={}):
# A SyntaxError occurred before we could execute the module. # A SyntaxError occurred before we could execute the module.
raise ErrorDuringImport(value.filename, info) raise ErrorDuringImport(value.filename, info)
elif exc is ImportError and \ elif exc is ImportError and \
split(lower(str(value)))[:2] == ['no', 'module']: str(value).lower().split()[:2] == ['no', 'module']:
# The module was not found. # The module was not found.
return None return None
else: else:
# Some other error occurred during the importing process. # Some other error occurred during the importing process.
raise ErrorDuringImport(path, sys.exc_info()) raise ErrorDuringImport(path, sys.exc_info())
for part in split(path, '.')[1:]: for part in path.split('.')[1:]:
try: module = getattr(module, part) try: module = getattr(module, part)
except AttributeError: return None except AttributeError: return None
return module return module
...@@ -382,7 +381,7 @@ class HTMLRepr(Repr): ...@@ -382,7 +381,7 @@ class HTMLRepr(Repr):
def repr1(self, x, level): def repr1(self, x, level):
if hasattr(type(x), '__name__'): if hasattr(type(x), '__name__'):
methodname = 'repr_' + join(split(type(x).__name__), '_') methodname = 'repr_' + '_'.join(type(x).__name__.split())
if hasattr(self, methodname): if hasattr(self, methodname):
return getattr(self, methodname)(x, level) return getattr(self, methodname)(x, level)
return self.escape(cram(stripid(repr(x)), self.maxother)) return self.escape(cram(stripid(repr(x)), self.maxother))
...@@ -466,7 +465,7 @@ class HTMLDoc(Doc): ...@@ -466,7 +465,7 @@ class HTMLDoc(Doc):
def preformat(self, text): def preformat(self, text):
"""Format literal preformatted text.""" """Format literal preformatted text."""
text = self.escape(expandtabs(text)) text = self.escape(text.expandtabs())
return replace(text, '\n\n', '\n \n', '\n\n', '\n \n', return replace(text, '\n\n', '\n \n', '\n\n', '\n \n',
' ', '&nbsp;', '\n', '<br>\n') ' ', '&nbsp;', '\n', '<br>\n')
...@@ -551,7 +550,7 @@ class HTMLDoc(Doc): ...@@ -551,7 +550,7 @@ class HTMLDoc(Doc):
results.append(self.namelink(name, classes)) results.append(self.namelink(name, classes))
here = end here = end
results.append(escape(text[here:])) results.append(escape(text[here:]))
return join(results, '') return ''.join(results)
# ---------------------------------------------- type-specific routines # ---------------------------------------------- type-specific routines
...@@ -567,7 +566,7 @@ class HTMLDoc(Doc): ...@@ -567,7 +566,7 @@ class HTMLDoc(Doc):
parents = [] parents = []
for base in bases: for base in bases:
parents.append(self.classlink(base, modname)) parents.append(self.classlink(base, modname))
result = result + '(' + join(parents, ', ') + ')' result = result + '(' + ', '.join(parents) + ')'
result = result + '\n</font></dt>' result = result + '\n</font></dt>'
elif type(entry) is type([]): elif type(entry) is type([]):
result = result + '<dd>\n%s</dd>\n' % self.formattree( result = result + '<dd>\n%s</dd>\n' % self.formattree(
...@@ -581,13 +580,13 @@ class HTMLDoc(Doc): ...@@ -581,13 +580,13 @@ class HTMLDoc(Doc):
all = object.__all__ all = object.__all__
except AttributeError: except AttributeError:
all = None all = None
parts = split(name, '.') parts = name.split('.')
links = [] links = []
for i in range(len(parts)-1): for i in range(len(parts)-1):
links.append( links.append(
'<a href="%s.html"><font color="#ffffff">%s</font></a>' % '<a href="%s.html"><font color="#ffffff">%s</font></a>' %
(join(parts[:i+1], '.'), parts[i])) ('.'.join(parts[:i+1]), parts[i]))
linkedname = join(links + parts[-1:], '.') linkedname = '.'.join(links + parts[-1:])
head = '<big><big><strong>%s</strong></big></big>' % linkedname head = '<big><big><strong>%s</strong></big></big>' % linkedname
try: try:
path = inspect.getabsfile(object) path = inspect.getabsfile(object)
...@@ -602,12 +601,12 @@ class HTMLDoc(Doc): ...@@ -602,12 +601,12 @@ class HTMLDoc(Doc):
if hasattr(object, '__version__'): if hasattr(object, '__version__'):
version = str(object.__version__) version = str(object.__version__)
if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
version = strip(version[11:-1]) version = version[11:-1].strip()
info.append('version %s' % self.escape(version)) info.append('version %s' % self.escape(version))
if hasattr(object, '__date__'): if hasattr(object, '__date__'):
info.append(self.escape(str(object.__date__))) info.append(self.escape(str(object.__date__)))
if info: if info:
head = head + ' (%s)' % join(info, ', ') head = head + ' (%s)' % ', '.join(info)
docloc = self.getdocloc(object) docloc = self.getdocloc(object)
if docloc is not None: if docloc is not None:
docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals() docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals()
...@@ -674,19 +673,19 @@ class HTMLDoc(Doc): ...@@ -674,19 +673,19 @@ class HTMLDoc(Doc):
for key, value in classes: for key, value in classes:
contents.append(self.document(value, key, name, fdict, cdict)) contents.append(self.document(value, key, name, fdict, cdict))
result = result + self.bigsection( result = result + self.bigsection(
'Classes', '#ffffff', '#ee77aa', join(contents)) 'Classes', '#ffffff', '#ee77aa', ' '.join(contents))
if funcs: if funcs:
contents = [] contents = []
for key, value in funcs: for key, value in funcs:
contents.append(self.document(value, key, name, fdict, cdict)) contents.append(self.document(value, key, name, fdict, cdict))
result = result + self.bigsection( result = result + self.bigsection(
'Functions', '#ffffff', '#eeaa77', join(contents)) 'Functions', '#ffffff', '#eeaa77', ' '.join(contents))
if data: if data:
contents = [] contents = []
for key, value in data: for key, value in data:
contents.append(self.document(value, key)) contents.append(self.document(value, key))
result = result + self.bigsection( result = result + self.bigsection(
'Data', '#ffffff', '#55aa55', join(contents, '<br>\n')) 'Data', '#ffffff', '#55aa55', '<br>\n'.join(contents))
if hasattr(object, '__author__'): if hasattr(object, '__author__'):
contents = self.markup(str(object.__author__), self.preformat) contents = self.markup(str(object.__author__), self.preformat)
result = result + self.bigsection( result = result + self.bigsection(
...@@ -831,7 +830,7 @@ class HTMLDoc(Doc): ...@@ -831,7 +830,7 @@ class HTMLDoc(Doc):
parents = [] parents = []
for base in bases: for base in bases:
parents.append(self.classlink(base, object.__module__)) parents.append(self.classlink(base, object.__module__))
title = title + '(%s)' % join(parents, ', ') title = title + '(%s)' % ', '.join(parents)
doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict) doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict)
doc = doc and '<tt>%s<br>&nbsp;</tt>' % doc doc = doc and '<tt>%s<br>&nbsp;</tt>' % doc
...@@ -951,7 +950,7 @@ class TextRepr(Repr): ...@@ -951,7 +950,7 @@ class TextRepr(Repr):
def repr1(self, x, level): def repr1(self, x, level):
if hasattr(type(x), '__name__'): if hasattr(type(x), '__name__'):
methodname = 'repr_' + join(split(type(x).__name__), '_') methodname = 'repr_' + '_'.join(type(x).__name__.split())
if hasattr(self, methodname): if hasattr(self, methodname):
return getattr(self, methodname)(x, level) return getattr(self, methodname)(x, level)
return cram(stripid(repr(x)), self.maxother) return cram(stripid(repr(x)), self.maxother)
...@@ -983,19 +982,20 @@ class TextDoc(Doc): ...@@ -983,19 +982,20 @@ class TextDoc(Doc):
def bold(self, text): def bold(self, text):
"""Format a string in bold by overstriking.""" """Format a string in bold by overstriking."""
return join(map(lambda ch: ch + '\b' + ch, text), '') return ''.join(map(lambda ch: ch + '\b' + ch, text))
def indent(self, text, prefix=' '): def indent(self, text, prefix=' '):
"""Indent text by prepending a given prefix to each line.""" """Indent text by prepending a given prefix to each line."""
if not text: return '' if not text: return ''
lines = split(text, '\n') lines = text.split('\n')
lines = map(lambda line, prefix=prefix: prefix + line, lines) lines = map(lambda line, prefix=prefix: prefix + line, lines)
if lines: lines[-1] = rstrip(lines[-1]) if lines: lines[-1] = lines[-1].rstrip()
return join(lines, '\n') return '\n'.join(lines)
def section(self, title, contents): def section(self, title, contents):
"""Format a section with a given heading.""" """Format a section with a given heading."""
return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n' clean_contents = self.indent(contents).rstrip()
return self.bold(title) + '\n' + clean_contents + '\n\n'
# ---------------------------------------------- type-specific routines # ---------------------------------------------- type-specific routines
...@@ -1008,7 +1008,7 @@ class TextDoc(Doc): ...@@ -1008,7 +1008,7 @@ class TextDoc(Doc):
result = result + prefix + classname(c, modname) result = result + prefix + classname(c, modname)
if bases and bases != (parent,): if bases and bases != (parent,):
parents = map(lambda c, m=modname: classname(c, m), bases) parents = map(lambda c, m=modname: classname(c, m), bases)
result = result + '(%s)' % join(parents, ', ') result = result + '(%s)' % ', '.join(parents)
result = result + '\n' result = result + '\n'
elif type(entry) is type([]): elif type(entry) is type([]):
result = result + self.formattree( result = result + self.formattree(
...@@ -1068,7 +1068,7 @@ class TextDoc(Doc): ...@@ -1068,7 +1068,7 @@ class TextDoc(Doc):
modpkgs.sort() modpkgs.sort()
result = result + self.section( result = result + self.section(
'PACKAGE CONTENTS', join(modpkgs, '\n')) 'PACKAGE CONTENTS', '\n'.join(modpkgs))
if classes: if classes:
classlist = map(lambda (key, value): value, classes) classlist = map(lambda (key, value): value, classes)
...@@ -1076,24 +1076,24 @@ class TextDoc(Doc): ...@@ -1076,24 +1076,24 @@ class TextDoc(Doc):
inspect.getclasstree(classlist, 1), name)] inspect.getclasstree(classlist, 1), name)]
for key, value in classes: for key, value in classes:
contents.append(self.document(value, key, name)) contents.append(self.document(value, key, name))
result = result + self.section('CLASSES', join(contents, '\n')) result = result + self.section('CLASSES', '\n'.join(contents))
if funcs: if funcs:
contents = [] contents = []
for key, value in funcs: for key, value in funcs:
contents.append(self.document(value, key, name)) contents.append(self.document(value, key, name))
result = result + self.section('FUNCTIONS', join(contents, '\n')) result = result + self.section('FUNCTIONS', '\n'.join(contents))
if data: if data:
contents = [] contents = []
for key, value in data: for key, value in data:
contents.append(self.docother(value, key, name, maxlen=70)) contents.append(self.docother(value, key, name, maxlen=70))
result = result + self.section('DATA', join(contents, '\n')) result = result + self.section('DATA', '\n'.join(contents))
if hasattr(object, '__version__'): if hasattr(object, '__version__'):
version = str(object.__version__) version = str(object.__version__)
if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
version = strip(version[11:-1]) version = version[11:-1].strip()
result = result + self.section('VERSION', version) result = result + self.section('VERSION', version)
if hasattr(object, '__date__'): if hasattr(object, '__date__'):
result = result + self.section('DATE', str(object.__date__)) result = result + self.section('DATE', str(object.__date__))
...@@ -1118,7 +1118,7 @@ class TextDoc(Doc): ...@@ -1118,7 +1118,7 @@ class TextDoc(Doc):
title = self.bold(name) + ' = class ' + realname title = self.bold(name) + ' = class ' + realname
if bases: if bases:
parents = map(makename, bases) parents = map(makename, bases)
title = title + '(%s)' % join(parents, ', ') title = title + '(%s)' % ', '.join(parents)
doc = getdoc(object) doc = getdoc(object)
contents = doc and [doc + '\n'] or [] contents = doc and [doc + '\n'] or []
...@@ -1214,7 +1214,7 @@ class TextDoc(Doc): ...@@ -1214,7 +1214,7 @@ class TextDoc(Doc):
contents = '\n'.join(contents) contents = '\n'.join(contents)
if not contents: if not contents:
return title + '\n' return title + '\n'
return title + '\n' + self.indent(rstrip(contents), ' | ') + '\n' return title + '\n' + self.indent(contents.rstrip(), ' | ') + '\n'
def formatvalue(self, object): def formatvalue(self, object):
"""Format an argument default value as text.""" """Format an argument default value as text."""
...@@ -1267,7 +1267,7 @@ class TextDoc(Doc): ...@@ -1267,7 +1267,7 @@ class TextDoc(Doc):
return decl + '\n' return decl + '\n'
else: else:
doc = getdoc(object) or '' doc = getdoc(object) or ''
return decl + '\n' + (doc and rstrip(self.indent(doc)) + '\n') return decl + '\n' + (doc and self.indent(doc).rstrip() + '\n')
def _docdescriptor(self, name, value, mod): def _docdescriptor(self, name, value, mod):
results = [] results = []
...@@ -1368,7 +1368,7 @@ def tempfilepager(text, cmd): ...@@ -1368,7 +1368,7 @@ def tempfilepager(text, cmd):
def ttypager(text): def ttypager(text):
"""Page through text on a text terminal.""" """Page through text on a text terminal."""
lines = split(plain(text), '\n') lines = plain(text).split('\n')
try: try:
import tty import tty
fd = sys.stdin.fileno() fd = sys.stdin.fileno()
...@@ -1381,7 +1381,7 @@ def ttypager(text): ...@@ -1381,7 +1381,7 @@ def ttypager(text):
try: try:
r = inc = os.environ.get('LINES', 25) - 1 r = inc = os.environ.get('LINES', 25) - 1
sys.stdout.write(join(lines[:inc], '\n') + '\n') sys.stdout.write('\n'.join(lines[:inc]) + '\n')
while lines[r:]: while lines[r:]:
sys.stdout.write('-- more --') sys.stdout.write('-- more --')
sys.stdout.flush() sys.stdout.flush()
...@@ -1397,7 +1397,7 @@ def ttypager(text): ...@@ -1397,7 +1397,7 @@ def ttypager(text):
if c in ('b', 'B', '\x1b'): if c in ('b', 'B', '\x1b'):
r = r - inc - inc r = r - inc - inc
if r < 0: r = 0 if r < 0: r = 0
sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n') sys.stdout.write('\n' + '\n'.join(lines[r:r+inc]) + '\n')
r = r + inc r = r + inc
finally: finally:
...@@ -1437,10 +1437,10 @@ def describe(thing): ...@@ -1437,10 +1437,10 @@ def describe(thing):
def locate(path, forceload=0): def locate(path, forceload=0):
"""Locate an object by name or dotted path, importing as necessary.""" """Locate an object by name or dotted path, importing as necessary."""
parts = [part for part in split(path, '.') if part] parts = [part for part in path.split('.') if part]
module, n = None, 0 module, n = None, 0
while n < len(parts): while n < len(parts):
nextmodule = safeimport(join(parts[:n+1], '.'), forceload) nextmodule = safeimport('.'.join(parts[:n+1]), forceload)
if nextmodule: module, n = nextmodule, n + 1 if nextmodule: module, n = nextmodule, n + 1
else: break else: break
if module: if module:
...@@ -1637,8 +1637,8 @@ class Helper: ...@@ -1637,8 +1637,8 @@ class Helper:
for dir in [os.environ.get('PYTHONDOCS'), for dir in [os.environ.get('PYTHONDOCS'),
homedir and os.path.join(homedir, 'doc'), homedir and os.path.join(homedir, 'doc'),
os.path.join(execdir, 'doc'), os.path.join(execdir, 'doc'),
'/usr/doc/python-docs-' + split(sys.version)[0], '/usr/doc/python-docs-' + sys.version.split()[0],
'/usr/doc/python-' + split(sys.version)[0], '/usr/doc/python-' + sys.version.split()[0],
'/usr/doc/python-docs-' + sys.version[:3], '/usr/doc/python-docs-' + sys.version[:3],
'/usr/doc/python-' + sys.version[:3], '/usr/doc/python-' + sys.version[:3],
os.path.join(sys.prefix, 'Resources/English.lproj/Documentation')]: os.path.join(sys.prefix, 'Resources/English.lproj/Documentation')]:
...@@ -1672,8 +1672,8 @@ has the same effect as typing a particular string at the help> prompt. ...@@ -1672,8 +1672,8 @@ has the same effect as typing a particular string at the help> prompt.
if not request: break if not request: break
except (KeyboardInterrupt, EOFError): except (KeyboardInterrupt, EOFError):
break break
request = strip(replace(request, '"', '', "'", '')) request = replace(request, '"', '', "'", '').strip()
if lower(request) in ('q', 'quit'): break if request.lower() in ('q', 'quit'): break
self.help(request) self.help(request)
def getline(self, prompt): def getline(self, prompt):
...@@ -1692,7 +1692,7 @@ has the same effect as typing a particular string at the help> prompt. ...@@ -1692,7 +1692,7 @@ has the same effect as typing a particular string at the help> prompt.
elif request == 'topics': self.listtopics() elif request == 'topics': self.listtopics()
elif request == 'modules': self.listmodules() elif request == 'modules': self.listmodules()
elif request[:8] == 'modules ': elif request[:8] == 'modules ':
self.listmodules(split(request)[1]) self.listmodules(request.split()[1])
elif request in self.keywords: self.showtopic(request) elif request in self.keywords: self.showtopic(request)
elif request in self.topics: self.showtopic(request) elif request in self.topics: self.showtopic(request)
elif request: doc(request, 'Help on %s:') elif request: doc(request, 'Help on %s:')
...@@ -1786,11 +1786,11 @@ running "hh -decompile . PythonNN.chm" in the C:\PythonNN\Doc> directory. ...@@ -1786,11 +1786,11 @@ running "hh -decompile . PythonNN.chm" in the C:\PythonNN\Doc> directory.
parser.start_td = parser.start_th = lambda a, b=buffer: b.write('\t') parser.start_td = parser.start_th = lambda a, b=buffer: b.write('\t')
parser.feed(document) parser.feed(document)
buffer = replace(buffer.getvalue(), '\xa0', ' ', '\n', '\n ') buffer = replace(buffer.getvalue(), '\xa0', ' ', '\n', '\n ')
pager(' ' + strip(buffer) + '\n') pager(' ' + buffer.strip() + '\n')
if xrefs: if xrefs:
buffer = StringIO.StringIO() buffer = StringIO.StringIO()
formatter.DumbWriter(buffer).send_flowing_data( formatter.DumbWriter(buffer).send_flowing_data(
'Related help topics: ' + join(split(xrefs), ', ') + '\n') 'Related help topics: ' + ', '.join(xrefs.split()) + '\n')
self.output.write('\n%s\n' % buffer.getvalue()) self.output.write('\n%s\n' % buffer.getvalue())
def listmodules(self, key=''): def listmodules(self, key=''):
...@@ -1809,7 +1809,7 @@ Please wait a moment while I gather a list of all available modules... ...@@ -1809,7 +1809,7 @@ Please wait a moment while I gather a list of all available modules...
def callback(path, modname, desc, modules=modules): def callback(path, modname, desc, modules=modules):
if modname and modname[-9:] == '.__init__': if modname and modname[-9:] == '.__init__':
modname = modname[:-9] + ' (package)' modname = modname[:-9] + ' (package)'
if find(modname, '.') < 0: if modname.find('.') < 0:
modules[modname] = 1 modules[modname] = 1
ModuleScanner().run(callback) ModuleScanner().run(callback)
self.list(modules.keys()) self.list(modules.keys())
...@@ -1848,7 +1848,7 @@ class ModuleScanner: ...@@ -1848,7 +1848,7 @@ class ModuleScanner:
"""An interruptible scanner that searches module synopses.""" """An interruptible scanner that searches module synopses."""
def run(self, callback, key=None, completer=None): def run(self, callback, key=None, completer=None):
if key: key = lower(key) if key: key = key.lower()
self.quit = False self.quit = False
seen = {} seen = {}
...@@ -1858,8 +1858,10 @@ class ModuleScanner: ...@@ -1858,8 +1858,10 @@ class ModuleScanner:
if key is None: if key is None:
callback(None, modname, '') callback(None, modname, '')
else: else:
desc = split(__import__(modname).__doc__ or '', '\n')[0] name = __import__(modname).__doc__ or ''
if find(lower(modname + ' - ' + desc), key) >= 0: desc = name.split('\n')[0]
name = modname + ' - ' + desc
if name.lower().find(key) >= 0:
callback(None, modname, desc) callback(None, modname, desc)
for importer, modname, ispkg in pkgutil.walk_packages(): for importer, modname, ispkg in pkgutil.walk_packages():
...@@ -1882,7 +1884,8 @@ class ModuleScanner: ...@@ -1882,7 +1884,8 @@ class ModuleScanner:
module = loader.load_module(modname) module = loader.load_module(modname)
desc = (module.__doc__ or '').splitlines()[0] desc = (module.__doc__ or '').splitlines()[0]
path = getattr(module,'__file__',None) path = getattr(module,'__file__',None)
if find(lower(modname + ' - ' + desc), key) >= 0: name = modname + ' - ' + desc
if name.lower().find(key) >= 0:
callback(path, modname, desc) callback(path, modname, desc)
if completer: if completer:
...@@ -1953,7 +1956,7 @@ def serve(port, callback=None, completer=None): ...@@ -1953,7 +1956,7 @@ def serve(port, callback=None, completer=None):
seen = {} seen = {}
for dir in sys.path: for dir in sys.path:
indices.append(html.index(dir, seen)) indices.append(html.index(dir, seen))
contents = heading + join(indices) + '''<p align=right> contents = heading + ' '.join(indices) + '''<p align=right>
<font color="#909090" face="helvetica, arial"><strong> <font color="#909090" face="helvetica, arial"><strong>
pydoc</strong> by Ka-Ping Yee &lt;ping@lfw.org&gt;</font>''' pydoc</strong> by Ka-Ping Yee &lt;ping@lfw.org&gt;</font>'''
self.send_document('Index of Modules', contents) self.send_document('Index of Modules', contents)
...@@ -2135,7 +2138,7 @@ def gui(): ...@@ -2135,7 +2138,7 @@ def gui():
def goto(self, event=None): def goto(self, event=None):
selection = self.result_lst.curselection() selection = self.result_lst.curselection()
if selection: if selection:
modname = split(self.result_lst.get(selection[0]))[0] modname = self.result_lst.get(selection[0]).split()[0]
self.open(url=self.server.url + modname + '.html') self.open(url=self.server.url + modname + '.html')
def collapse(self): def collapse(self):
...@@ -2180,7 +2183,7 @@ def gui(): ...@@ -2180,7 +2183,7 @@ def gui():
# -------------------------------------------------- command-line interface # -------------------------------------------------- command-line interface
def ispath(x): def ispath(x):
return isinstance(x, str) and find(x, os.sep) >= 0 return isinstance(x, str) and x.find(os.sep) >= 0
def cli(): def cli():
"""Command-line interface (looks at sys.argv to decide what to do).""" """Command-line interface (looks at sys.argv to decide what to do)."""
......
"""A collection of string operations (most are no longer used). """A collection of string constants.
Warning: most of the code you see here isn't normally used nowadays.
Beginning with Python 1.6, many of these functions are implemented as
methods on the standard string object. They used to be implemented by
a built-in module called strop, but strop is now obsolete itself.
Public module variables: Public module variables:
...@@ -202,327 +197,12 @@ class Template(metaclass=_TemplateMetaclass): ...@@ -202,327 +197,12 @@ class Template(metaclass=_TemplateMetaclass):
return self.pattern.sub(convert, self.template) return self.pattern.sub(convert, self.template)
####################################################################
# NOTE: Everything below here is deprecated. Use string methods instead.
# This stuff will go away in Python 3.0.
# Backward compatible names for exceptions
index_error = ValueError
atoi_error = ValueError
atof_error = ValueError
atol_error = ValueError
# convert UPPER CASE letters to lower case
def lower(s):
"""lower(s) -> string
Return a copy of the string s converted to lowercase.
"""
return s.lower()
# Convert lower case letters to UPPER CASE
def upper(s):
"""upper(s) -> string
Return a copy of the string s converted to uppercase.
"""
return s.upper()
# Swap lower case letters and UPPER CASE
def swapcase(s):
"""swapcase(s) -> string
Return a copy of the string s with upper case characters
converted to lowercase and vice versa.
"""
return s.swapcase()
# Strip leading and trailing tabs and spaces
def strip(s, chars=None):
"""strip(s [,chars]) -> string
Return a copy of the string s with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping.
"""
return s.strip(chars)
# Strip leading tabs and spaces
def lstrip(s, chars=None):
"""lstrip(s [,chars]) -> string
Return a copy of the string s with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return s.lstrip(chars)
# Strip trailing tabs and spaces
def rstrip(s, chars=None):
"""rstrip(s [,chars]) -> string
Return a copy of the string s with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return s.rstrip(chars)
# Split a string into a list of space/tab-separated words
def split(s, sep=None, maxsplit=-1):
"""split(s [,sep [,maxsplit]]) -> list of strings
Return a list of the words in the string s, using sep as the
delimiter string. If maxsplit is given, splits at no more than
maxsplit places (resulting in at most maxsplit+1 words). If sep
is not specified or is None, any whitespace string is a separator.
(split and splitfields are synonymous)
"""
return s.split(sep, maxsplit)
splitfields = split
# Split a string into a list of space/tab-separated words
def rsplit(s, sep=None, maxsplit=-1):
"""rsplit(s [,sep [,maxsplit]]) -> list of strings
Return a list of the words in the string s, using sep as the
delimiter string, starting at the end of the string and working
to the front. If maxsplit is given, at most maxsplit splits are
done. If sep is not specified or is None, any whitespace string
is a separator.
"""
return s.rsplit(sep, maxsplit)
# Join fields with optional separator
def join(words, sep = ' '):
"""join(list [,sep]) -> string
Return a string composed of the words in list, with
intervening occurrences of sep. The default separator is a
single space.
(joinfields and join are synonymous)
"""
return sep.join(words)
joinfields = join
# Find substring, raise exception if not found
def index(s, *args):
"""index(s, sub [,start [,end]]) -> int
Like find but raises ValueError when the substring is not found.
"""
return s.index(*args)
# Find last substring, raise exception if not found
def rindex(s, *args):
"""rindex(s, sub [,start [,end]]) -> int
Like rfind but raises ValueError when the substring is not found.
"""
return s.rindex(*args)
# Count non-overlapping occurrences of substring
def count(s, *args):
"""count(s, sub[, start[,end]]) -> int
Return the number of occurrences of substring sub in string
s[start:end]. Optional arguments start and end are
interpreted as in slice notation.
"""
return s.count(*args)
# Find substring, return -1 if not found
def find(s, *args):
"""find(s, sub [,start [,end]]) -> in
Return the lowest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return s.find(*args)
# Find last substring, return -1 if not found
def rfind(s, *args):
"""rfind(s, sub [,start [,end]]) -> int
Return the highest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return s.rfind(*args)
# for a bit of speed
_float = float
_int = int
_long = int
# Convert string to float
def atof(s):
"""atof(s) -> float
Return the floating point number represented by the string s.
"""
return _float(s)
# Convert string to integer
def atoi(s , base=10):
"""atoi(s [,base]) -> int
Return the integer represented by the string s in the given
base, which defaults to 10. The string s must consist of one
or more digits, possibly preceded by a sign. If base is 0, it
is chosen from the leading characters of s, 0 for octal, 0x or
0X for hexadecimal. If base is 16, a preceding 0x or 0X is
accepted.
"""
return _int(s, base)
# Convert string to long integer
def atol(s, base=10):
"""atol(s [,base]) -> long
Return the long integer represented by the string s in the
given base, which defaults to 10. The string s must consist
of one or more digits, possibly preceded by a sign. If base
is 0, it is chosen from the leading characters of s, 0 for
octal, 0x or 0X for hexadecimal. If base is 16, a preceding
0x or 0X is accepted. A trailing L or l is not accepted,
unless base is 0.
"""
return _long(s, base)
# Left-justify a string
def ljust(s, width, *args):
"""ljust(s, width[, fillchar]) -> string
Return a left-justified version of s, in a field of the
specified width, padded with spaces as needed. The string is
never truncated. If specified the fillchar is used instead of spaces.
"""
return s.ljust(width, *args)
# Right-justify a string
def rjust(s, width, *args):
"""rjust(s, width[, fillchar]) -> string
Return a right-justified version of s, in a field of the
specified width, padded with spaces as needed. The string is
never truncated. If specified the fillchar is used instead of spaces.
"""
return s.rjust(width, *args)
# Center a string
def center(s, width, *args):
"""center(s, width[, fillchar]) -> string
Return a center version of s, in a field of the specified
width. padded with spaces as needed. The string is never
truncated. If specified the fillchar is used instead of spaces.
"""
return s.center(width, *args)
# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
# Decadent feature: the argument may be a string or a number
# (Use of this is deprecated; it should be a string as with ljust c.s.)
def zfill(x, width):
"""zfill(x, width) -> string
Pad a numeric string x with zeros on the left, to fill a field
of the specified width. The string x is never truncated.
"""
if not isinstance(x, basestring):
x = repr(x)
return x.zfill(width)
# Expand tabs in a string.
# Doesn't take non-printing chars into account, but does understand \n.
def expandtabs(s, tabsize=8):
"""expandtabs(s [,tabsize]) -> string
Return a copy of the string s with all tab characters replaced
by the appropriate number of spaces, depending on the current
column, and the tabsize (default 8).
"""
return s.expandtabs(tabsize)
# Character translation through look-up table.
def translate(s, table, deletions=""):
"""translate(s,table [,deletions]) -> string
Return a copy of the string s, where all characters occurring
in the optional argument deletions are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256. The
deletions argument is not allowed for Unicode strings.
"""
if deletions:
return s.translate(table, deletions)
else:
# Add s[:0] so that if s is Unicode and table is an 8-bit string,
# table is converted to Unicode. This means that table *cannot*
# be a dictionary -- for that feature, use u.translate() directly.
return s.translate(table + s[:0])
# Capitalize a string, e.g. "aBc dEf" -> "Abc def".
def capitalize(s):
"""capitalize(s) -> string
Return a copy of the string s with only its first character
capitalized.
"""
return s.capitalize()
# Substring replacement (global)
def replace(s, old, new, maxsplit=-1):
"""replace (str, old, new[, maxsplit]) -> string
Return a copy of string str with all occurrences of substring
old replaced by new. If the optional argument maxsplit is
given, only the first maxsplit occurrences are replaced.
"""
return s.replace(old, new, maxsplit)
# Try importing optional built-in module "strop" -- if it exists, # Try importing optional built-in module "strop" -- if it exists,
# it redefines some string operations that are 100-1000 times faster. # it redefines some string operations that are 100-1000 times faster.
# It also defines values for whitespace, lowercase and uppercase # It also defines values for whitespace, lowercase and uppercase
# that match <ctype.h>'s definitions. # that match <ctype.h>'s definitions.
try: try:
from strop import maketrans, lowercase, uppercase, whitespace from strop import maketrans
letters = lowercase + uppercase
except ImportError: except ImportError:
pass # Use the original versions pass # Use the original versions
"""This is a test""" """This is a test"""
from __future__ import nested_scopes; import string from __future__ import nested_scopes; import site
def f(x): def f(x):
def g(y): def g(y):
......
...@@ -25,7 +25,7 @@ Copyright (C) 2001-2002 Vinay Sajip. All Rights Reserved. ...@@ -25,7 +25,7 @@ Copyright (C) 2001-2002 Vinay Sajip. All Rights Reserved.
""" """
import select import select
import os, sys, string, struct, types, pickle, cStringIO import os, sys, struct, types, pickle, cStringIO
import socket, tempfile, threading, time import socket, tempfile, threading, time
import logging, logging.handlers, logging.config import logging, logging.handlers, logging.config
from test.test_support import run_with_locale from test.test_support import run_with_locale
...@@ -455,11 +455,10 @@ datefmt= ...@@ -455,11 +455,10 @@ datefmt=
""" """
# config2 has a subtle configuration error that should be reported # config2 has a subtle configuration error that should be reported
config2 = string.replace(config1, "sys.stdout", "sys.stbout") config2 = config1.replace("sys.stdout", "sys.stbout")
# config3 has a less subtle configuration error # config3 has a less subtle configuration error
config3 = string.replace( config3 = config1.replace("formatter=form1", "formatter=misspelled_name")
config1, "formatter=form1", "formatter=misspelled_name")
def test4(): def test4():
for i in range(4): for i in range(4):
......
...@@ -187,25 +187,25 @@ class ScopeTests(unittest.TestCase): ...@@ -187,25 +187,25 @@ class ScopeTests(unittest.TestCase):
check_syntax_error(self, """\ check_syntax_error(self, """\
def unoptimized_clash1(strip): def unoptimized_clash1(strip):
def f(s): def f(s):
from string import * from sys import *
return strip(s) # ambiguity: free or local return getrefcount(s) # ambiguity: free or local
return f return f
""") """)
check_syntax_error(self, """\ check_syntax_error(self, """\
def unoptimized_clash2(): def unoptimized_clash2():
from string import * from sys import *
def f(s): def f(s):
return strip(s) # ambiguity: global or local return getrefcount(s) # ambiguity: global or local
return f return f
""") """)
check_syntax_error(self, """\ check_syntax_error(self, """\
def unoptimized_clash2(): def unoptimized_clash2():
from string import * from sys import *
def g(): def g():
def f(s): def f(s):
return strip(s) # ambiguity: global or local return getrefcount(s) # ambiguity: global or local
return f return f
""") """)
...@@ -219,24 +219,24 @@ def f(x): ...@@ -219,24 +219,24 @@ def f(x):
check_syntax_error(self, """\ check_syntax_error(self, """\
def f(): def f():
def g(): def g():
from string import * from sys import *
return strip # global or local? return getrefcount # global or local?
""") """)
# and verify a few cases that should work # and verify a few cases that should work
exec(""" exec("""
def noproblem1(): def noproblem1():
from string import * from sys import *
f = lambda x:x f = lambda x:x
def noproblem2(): def noproblem2():
from string import * from sys import *
def f(x): def f(x):
return x + 1 return x + 1
def noproblem3(): def noproblem3():
from string import * from sys import *
def f(x): def f(x):
global y global y
y = x y = x
......
import unittest, string import unittest, string
from test import test_support, string_tests from test import test_support
from UserList import UserList
class StringTest(
string_tests.CommonTest,
string_tests.MixinStrStringUserStringTest
):
type2test = str
def checkequal(self, result, object, methodname, *args):
realresult = getattr(string, methodname)(object, *args)
self.assertEqual(
result,
realresult
)
def checkraises(self, exc, object, methodname, *args):
self.assertRaises(
exc,
getattr(string, methodname),
object,
*args
)
def checkcall(self, object, methodname, *args):
getattr(string, methodname)(object, *args)
def test_join(self):
# These are the same checks as in string_test.ObjectTest.test_join
# but the argument order ist different
self.checkequal('a b c d', ['a', 'b', 'c', 'd'], 'join', ' ')
self.checkequal('abcd', ('a', 'b', 'c', 'd'), 'join', '')
self.checkequal('w x y z', string_tests.Sequence(), 'join', ' ')
self.checkequal('abc', ('abc',), 'join', 'a')
self.checkequal('z', UserList(['z']), 'join', 'a')
if test_support.have_unicode:
self.checkequal(unicode('a.b.c'), ['a', 'b', 'c'], 'join', unicode('.'))
self.checkequal(unicode('a.b.c'), [unicode('a'), 'b', 'c'], 'join', '.')
self.checkequal(unicode('a.b.c'), ['a', unicode('b'), 'c'], 'join', '.')
self.checkequal(unicode('a.b.c'), ['a', 'b', unicode('c')], 'join', '.')
self.checkraises(TypeError, ['a', unicode('b'), 3], 'join', '.')
for i in [5, 25, 125]:
self.checkequal(
((('a' * i) + '-') * i)[:-1],
['a' * i] * i, 'join', '-')
self.checkequal(
((('a' * i) + '-') * i)[:-1],
('a' * i,) * i, 'join', '-')
self.checkraises(TypeError, string_tests.BadSeq1(), 'join', ' ')
self.checkequal('a b c', string_tests.BadSeq2(), 'join', ' ')
try:
def f():
yield 4 + ""
self.fixtype(' ').join(f())
except TypeError as e:
if '+' not in str(e):
self.fail('join() ate exception message')
else:
self.fail('exception not raised')
class ModuleTest(unittest.TestCase): class ModuleTest(unittest.TestCase):
...@@ -77,37 +15,14 @@ class ModuleTest(unittest.TestCase): ...@@ -77,37 +15,14 @@ class ModuleTest(unittest.TestCase):
string.punctuation string.punctuation
string.printable string.printable
def test_atoi(self):
self.assertEqual(string.atoi(" 1 "), 1)
self.assertRaises(ValueError, string.atoi, " 1x")
self.assertRaises(ValueError, string.atoi, " x1 ")
def test_atol(self):
self.assertEqual(string.atol(" 1 "), 1)
self.assertRaises(ValueError, string.atol, " 1x ")
self.assertRaises(ValueError, string.atol, " x1 ")
def test_atof(self):
self.assertAlmostEqual(string.atof(" 1 "), 1.0)
self.assertRaises(ValueError, string.atof, " 1x ")
self.assertRaises(ValueError, string.atof, " x1 ")
def test_maketrans(self): def test_maketrans(self):
transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377' transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377'
self.assertEqual(string.maketrans('abc', 'xyz'), transtable) self.assertEqual(string.maketrans('abc', 'xyz'), transtable)
self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzq') self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzq')
def test_capwords(self):
self.assertEqual(string.capwords('abc def ghi'), 'Abc Def Ghi')
self.assertEqual(string.capwords('abc\tdef\nghi'), 'Abc Def Ghi')
self.assertEqual(string.capwords('abc\t def \nghi'), 'Abc Def Ghi')
self.assertEqual(string.capwords('ABC DEF GHI'), 'Abc Def Ghi')
self.assertEqual(string.capwords('ABC-DEF-GHI', '-'), 'Abc-Def-Ghi')
self.assertEqual(string.capwords('ABC-def DEF-ghi GHI'), 'Abc-def Def-ghi Ghi')
def test_main(): def test_main():
test_support.run_unittest(StringTest, ModuleTest) test_support.run_unittest(ModuleTest)
if __name__ == "__main__": if __name__ == "__main__":
test_main() test_main()
...@@ -9,126 +9,16 @@ from test import test_support ...@@ -9,126 +9,16 @@ from test import test_support
class StropFunctionTestCase(unittest.TestCase): class StropFunctionTestCase(unittest.TestCase):
def test_atoi(self):
self.assert_(strop.atoi(" 1 ") == 1)
self.assertRaises(ValueError, strop.atoi, " 1x")
self.assertRaises(ValueError, strop.atoi, " x1 ")
def test_atol(self):
self.assert_(strop.atol(" 1 ") == 1)
self.assertRaises(ValueError, strop.atol, " 1x")
self.assertRaises(ValueError, strop.atol, " x1 ")
def test_atof(self):
self.assert_(strop.atof(" 1 ") == 1.0)
self.assertRaises(ValueError, strop.atof, " 1x")
self.assertRaises(ValueError, strop.atof, " x1 ")
def test_capitalize(self):
self.assert_(strop.capitalize(" hello ") == " hello ")
self.assert_(strop.capitalize("hello ") == "Hello ")
def test_find(self):
self.assert_(strop.find("abcdefghiabc", "abc") == 0)
self.assert_(strop.find("abcdefghiabc", "abc", 1) == 9)
self.assert_(strop.find("abcdefghiabc", "def", 4) == -1)
def test_rfind(self):
self.assert_(strop.rfind("abcdefghiabc", "abc") == 9)
def test_lower(self):
self.assert_(strop.lower("HeLLo") == "hello")
def test_upper(self):
self.assert_(strop.upper("HeLLo") == "HELLO")
def test_swapcase(self):
self.assert_(strop.swapcase("HeLLo cOmpUteRs") == "hEllO CoMPuTErS")
def test_strip(self):
self.assert_(strop.strip(" \t\n hello \t\n ") == "hello")
def test_lstrip(self):
self.assert_(strop.lstrip(" \t\n hello \t\n ") == "hello \t\n ")
def test_rstrip(self):
self.assert_(strop.rstrip(" \t\n hello \t\n ") == " \t\n hello")
def test_replace(self):
replace = strop.replace
self.assert_(replace("one!two!three!", '!', '@', 1)
== "one@two!three!")
self.assert_(replace("one!two!three!", '!', '@', 2)
== "one@two@three!")
self.assert_(replace("one!two!three!", '!', '@', 3)
== "one@two@three@")
self.assert_(replace("one!two!three!", '!', '@', 4)
== "one@two@three@")
# CAUTION: a replace count of 0 means infinity only to strop,
# not to the string .replace() method or to the
# string.replace() function.
self.assert_(replace("one!two!three!", '!', '@', 0)
== "one@two@three@")
self.assert_(replace("one!two!three!", '!', '@')
== "one@two@three@")
self.assert_(replace("one!two!three!", 'x', '@')
== "one!two!three!")
self.assert_(replace("one!two!three!", 'x', '@', 2)
== "one!two!three!")
def test_split(self):
split = strop.split
self.assert_(split("this is the split function")
== ['this', 'is', 'the', 'split', 'function'])
self.assert_(split("a|b|c|d", '|') == ['a', 'b', 'c', 'd'])
self.assert_(split("a|b|c|d", '|', 2) == ['a', 'b', 'c|d'])
self.assert_(split("a b c d", None, 1) == ['a', 'b c d'])
self.assert_(split("a b c d", None, 2) == ['a', 'b', 'c d'])
self.assert_(split("a b c d", None, 3) == ['a', 'b', 'c', 'd'])
self.assert_(split("a b c d", None, 4) == ['a', 'b', 'c', 'd'])
self.assert_(split("a b c d", None, 0) == ['a', 'b', 'c', 'd'])
self.assert_(split("a b c d", None, 2) == ['a', 'b', 'c d'])
def test_join(self):
self.assert_(strop.join(['a', 'b', 'c', 'd']) == 'a b c d')
self.assert_(strop.join(('a', 'b', 'c', 'd'), '') == 'abcd')
self.assert_(strop.join(Sequence()) == 'w x y z')
# try a few long ones
self.assert_(strop.join(['x' * 100] * 100, ':')
== (('x' * 100) + ":") * 99 + "x" * 100)
self.assert_(strop.join(('x' * 100,) * 100, ':')
== (('x' * 100) + ":") * 99 + "x" * 100)
def test_maketrans(self): def test_maketrans(self):
self.assert_(strop.maketrans("abc", "xyz") == transtable) self.assert_(strop.maketrans("abc", "xyz") == transtable)
self.assertRaises(ValueError, strop.maketrans, "abc", "xyzq") self.assertRaises(ValueError, strop.maketrans, "abc", "xyzq")
def test_translate(self):
self.assert_(strop.translate("xyzabcdef", transtable, "def")
== "xyzxyz")
def test_data_attributes(self):
strop.lowercase
strop.uppercase
strop.whitespace
transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377' transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377'
# join() now works with any sequence type.
class Sequence:
def __init__(self): self.seq = 'wxyz'
def __len__(self): return len(self.seq)
def __getitem__(self, i): return self.seq[i]
def test_main(): def test_main():
test_support.run_unittest(StropFunctionTestCase) test_support.run_unittest(StropFunctionTestCase)
if __name__ == "__main__": if __name__ == "__main__":
test_main() test_main()
...@@ -55,7 +55,6 @@ import sched ...@@ -55,7 +55,6 @@ import sched
import smtplib import smtplib
import sndhdr import sndhdr
import statvfs import statvfs
import stringold
import sunau import sunau
import sunaudio import sunaudio
import symbol import symbol
......
...@@ -6,7 +6,7 @@ Written by Marc-Andre Lemburg (mal@lemburg.com). ...@@ -6,7 +6,7 @@ Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""#" """#"
import unittest, sys, string, codecs, new import unittest, sys, codecs, new
from test import test_support, string_tests from test import test_support, string_tests
# Error handling (bad decoder return) # Error handling (bad decoder return)
......
...@@ -22,7 +22,6 @@ used to query various info about the object, if available. ...@@ -22,7 +22,6 @@ used to query various info about the object, if available.
(mimetools.Message objects are queried with the getheader() method.) (mimetools.Message objects are queried with the getheader() method.)
""" """
import string
import socket import socket
import os import os
import time import time
...@@ -1465,6 +1464,7 @@ def reporthook(blocknum, blocksize, totalsize): ...@@ -1465,6 +1464,7 @@ def reporthook(blocknum, blocksize, totalsize):
# Test program # Test program
def test(args=[]): def test(args=[]):
import string
if not args: if not args:
args = [ args = [
'/etc/passwd', '/etc/passwd',
......
...@@ -109,7 +109,7 @@ __all__ = [ ...@@ -109,7 +109,7 @@ __all__ = [
# structure, and convert it from and to XML. # structure, and convert it from and to XML.
## ##
import string, sys, re import sys, re
from . import ElementPath from . import ElementPath
...@@ -762,7 +762,7 @@ def _encode_entity(text, pattern=_escape): ...@@ -762,7 +762,7 @@ def _encode_entity(text, pattern=_escape):
if text is None: if text is None:
text = "&#%d;" % ord(char) text = "&#%d;" % ord(char)
append(text) append(text)
return string.join(out, "") return "".join(out)
try: try:
return _encode(pattern.sub(escape_entities, text), "ascii") return _encode(pattern.sub(escape_entities, text), "ascii")
except TypeError: except TypeError:
...@@ -772,7 +772,7 @@ def _encode_entity(text, pattern=_escape): ...@@ -772,7 +772,7 @@ def _encode_entity(text, pattern=_escape):
# the following functions assume an ascii-compatible encoding # the following functions assume an ascii-compatible encoding
# (or "utf-16") # (or "utf-16")
def _escape_cdata(text, encoding=None, replace=string.replace): def _escape_cdata(text, encoding=None):
# escape character data # escape character data
try: try:
if encoding: if encoding:
...@@ -780,14 +780,14 @@ def _escape_cdata(text, encoding=None, replace=string.replace): ...@@ -780,14 +780,14 @@ def _escape_cdata(text, encoding=None, replace=string.replace):
text = _encode(text, encoding) text = _encode(text, encoding)
except UnicodeError: except UnicodeError:
return _encode_entity(text) return _encode_entity(text)
text = replace(text, "&", "&amp;") text = text.replace("&", "&amp;")
text = replace(text, "<", "&lt;") text = text.replace("<", "&lt;")
text = replace(text, ">", "&gt;") text = text.replace(">", "&gt;")
return text return text
except (TypeError, AttributeError): except (TypeError, AttributeError):
_raise_serialization_error(text) _raise_serialization_error(text)
def _escape_attrib(text, encoding=None, replace=string.replace): def _escape_attrib(text, encoding=None):
# escape attribute value # escape attribute value
try: try:
if encoding: if encoding:
...@@ -795,11 +795,11 @@ def _escape_attrib(text, encoding=None, replace=string.replace): ...@@ -795,11 +795,11 @@ def _escape_attrib(text, encoding=None, replace=string.replace):
text = _encode(text, encoding) text = _encode(text, encoding)
except UnicodeError: except UnicodeError:
return _encode_entity(text) return _encode_entity(text)
text = replace(text, "&", "&amp;") text = text.replace("&", "&amp;")
text = replace(text, "'", "&apos;") # FIXME: overkill text = text.replace("'", "&apos;") # FIXME: overkill
text = replace(text, "\"", "&quot;") text = text.replace("\"", "&quot;")
text = replace(text, "<", "&lt;") text = text.replace("<", "&lt;")
text = replace(text, ">", "&gt;") text = text.replace(">", "&gt;")
return text return text
except (TypeError, AttributeError): except (TypeError, AttributeError):
_raise_serialization_error(text) _raise_serialization_error(text)
...@@ -809,7 +809,7 @@ def fixtag(tag, namespaces): ...@@ -809,7 +809,7 @@ def fixtag(tag, namespaces):
# tag and namespace declaration, if any # tag and namespace declaration, if any
if isinstance(tag, QName): if isinstance(tag, QName):
tag = tag.text tag = tag.text
namespace_uri, tag = string.split(tag[1:], "}", 1) namespace_uri, tag = tag[1:].split("}", 1)
prefix = namespaces.get(namespace_uri) prefix = namespaces.get(namespace_uri)
if prefix is None: if prefix is None:
prefix = _namespace_map.get(namespace_uri) prefix = _namespace_map.get(namespace_uri)
...@@ -982,7 +982,7 @@ def tostring(element, encoding=None): ...@@ -982,7 +982,7 @@ def tostring(element, encoding=None):
file = dummy() file = dummy()
file.write = data.append file.write = data.append
ElementTree(element).write(file, encoding) ElementTree(element).write(file, encoding)
return string.join(data, "") return "".join(data)
## ##
# Generic element structure builder. This builder converts a sequence # Generic element structure builder. This builder converts a sequence
...@@ -1021,7 +1021,7 @@ class TreeBuilder: ...@@ -1021,7 +1021,7 @@ class TreeBuilder:
def _flush(self): def _flush(self):
if self._data: if self._data:
if self._last is not None: if self._last is not None:
text = string.join(self._data, "") text = "".join(self._data)
if self._tail: if self._tail:
assert self._last.tail is None, "internal error (tail)" assert self._last.tail is None, "internal error (tail)"
self._last.tail = text self._last.tail = text
...@@ -1182,7 +1182,7 @@ class XMLTreeBuilder: ...@@ -1182,7 +1182,7 @@ class XMLTreeBuilder:
if prefix == ">": if prefix == ">":
self._doctype = None self._doctype = None
return return
text = string.strip(text) text = text.strip()
if not text: if not text:
return return
self._doctype.append(text) self._doctype.append(text)
......
...@@ -169,6 +169,14 @@ Extension Modules ...@@ -169,6 +169,14 @@ Extension Modules
Library Library
------- -------
- Remove functions in string module that are also string methods.
- Remove obsolete modules: xmllib, stringold.
- Remove support for long obsolete platforms: plat-aix3, plat-irix5.
- Remove xmlrpclib.SlowParser. It was based on xmllib.
- Patch #1680961: atexit has been reimplemented in C. - Patch #1680961: atexit has been reimplemented in C.
- Removed all traces of the sets module. - Removed all traces of the sets module.
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
#define PY_SSIZE_T_CLEAN #define PY_SSIZE_T_CLEAN
#include "Python.h" #include "Python.h"
#include <ctype.h>
PyDoc_STRVAR(strop_module__doc__, PyDoc_STRVAR(strop_module__doc__,
"Common string manipulations, optimized for speed.\n" "Common string manipulations, optimized for speed.\n"
...@@ -10,871 +9,6 @@ PyDoc_STRVAR(strop_module__doc__, ...@@ -10,871 +9,6 @@ PyDoc_STRVAR(strop_module__doc__,
"Always use \"import string\" rather than referencing\n" "Always use \"import string\" rather than referencing\n"
"this module directly."); "this module directly.");
/* XXX This file assumes that the <ctype.h> is*() functions
XXX are defined for all 8-bit characters! */
#define WARN if (PyErr_Warn(PyExc_DeprecationWarning, \
"strop functions are obsolete; use string methods")) \
return NULL
/* The lstrip(), rstrip() and strip() functions are implemented
in do_strip(), which uses an additional parameter to indicate what
type of strip should occur. */
#define LEFTSTRIP 0
#define RIGHTSTRIP 1
#define BOTHSTRIP 2
static PyObject *
split_whitespace(char *s, Py_ssize_t len, Py_ssize_t maxsplit)
{
Py_ssize_t i = 0, j;
int err;
Py_ssize_t countsplit = 0;
PyObject* item;
PyObject *list = PyList_New(0);
if (list == NULL)
return NULL;
while (i < len) {
while (i < len && isspace(Py_CHARMASK(s[i]))) {
i = i+1;
}
j = i;
while (i < len && !isspace(Py_CHARMASK(s[i]))) {
i = i+1;
}
if (j < i) {
item = PyString_FromStringAndSize(s+j, i-j);
if (item == NULL)
goto finally;
err = PyList_Append(list, item);
Py_DECREF(item);
if (err < 0)
goto finally;
countsplit++;
while (i < len && isspace(Py_CHARMASK(s[i]))) {
i = i+1;
}
if (maxsplit && (countsplit >= maxsplit) && i < len) {
item = PyString_FromStringAndSize(
s+i, len - i);
if (item == NULL)
goto finally;
err = PyList_Append(list, item);
Py_DECREF(item);
if (err < 0)
goto finally;
i = len;
}
}
}
return list;
finally:
Py_DECREF(list);
return NULL;
}
PyDoc_STRVAR(splitfields__doc__,
"split(s [,sep [,maxsplit]]) -> list of strings\n"
"splitfields(s [,sep [,maxsplit]]) -> list of strings\n"
"\n"
"Return a list of the words in the string s, using sep as the\n"
"delimiter string. If maxsplit is nonzero, splits into at most\n"
"maxsplit words. If sep is not specified, any whitespace string\n"
"is a separator. Maxsplit defaults to 0.\n"
"\n"
"(split and splitfields are synonymous)");
static PyObject *
strop_splitfields(PyObject *self, PyObject *args)
{
Py_ssize_t len, n, i, j, err;
Py_ssize_t splitcount, maxsplit;
char *s, *sub;
PyObject *list, *item;
WARN;
sub = NULL;
n = 0;
splitcount = 0;
maxsplit = 0;
if (!PyArg_ParseTuple(args, "t#|z#n:split", &s, &len, &sub, &n, &maxsplit))
return NULL;
if (sub == NULL)
return split_whitespace(s, len, maxsplit);
if (n == 0) {
PyErr_SetString(PyExc_ValueError, "empty separator");
return NULL;
}
list = PyList_New(0);
if (list == NULL)
return NULL;
i = j = 0;
while (i+n <= len) {
if (s[i] == sub[0] && (n == 1 || memcmp(s+i, sub, n) == 0)) {
item = PyString_FromStringAndSize(s+j, i-j);
if (item == NULL)
goto fail;
err = PyList_Append(list, item);
Py_DECREF(item);
if (err < 0)
goto fail;
i = j = i + n;
splitcount++;
if (maxsplit && (splitcount >= maxsplit))
break;
}
else
i++;
}
item = PyString_FromStringAndSize(s+j, len-j);
if (item == NULL)
goto fail;
err = PyList_Append(list, item);
Py_DECREF(item);
if (err < 0)
goto fail;
return list;
fail:
Py_DECREF(list);
return NULL;
}
PyDoc_STRVAR(joinfields__doc__,
"join(list [,sep]) -> string\n"
"joinfields(list [,sep]) -> string\n"
"\n"
"Return a string composed of the words in list, with\n"
"intervening occurrences of sep. Sep defaults to a single\n"
"space.\n"
"\n"
"(join and joinfields are synonymous)");
static PyObject *
strop_joinfields(PyObject *self, PyObject *args)
{
PyObject *seq;
char *sep = NULL;
Py_ssize_t seqlen, seplen = 0;
Py_ssize_t i, reslen = 0, slen = 0, sz = 100;
PyObject *res = NULL;
char* p = NULL;
ssizeargfunc getitemfunc;
WARN;
if (!PyArg_ParseTuple(args, "O|t#:join", &seq, &sep, &seplen))
return NULL;
if (sep == NULL) {
sep = " ";
seplen = 1;
}
seqlen = PySequence_Size(seq);
if (seqlen < 0 && PyErr_Occurred())
return NULL;
if (seqlen == 1) {
/* Optimization if there's only one item */
PyObject *item = PySequence_GetItem(seq, 0);
if (item && !PyString_Check(item)) {
PyErr_SetString(PyExc_TypeError,
"first argument must be sequence of strings");
Py_DECREF(item);
return NULL;
}
return item;
}
if (!(res = PyString_FromStringAndSize((char*)NULL, sz)))
return NULL;
p = PyString_AsString(res);
/* optimize for lists, since it's the most common case. all others
* (tuples and arbitrary sequences) just use the sequence abstract
* interface.
*/
if (PyList_Check(seq)) {
for (i = 0; i < seqlen; i++) {
PyObject *item = PyList_GET_ITEM(seq, i);
if (!PyString_Check(item)) {
PyErr_SetString(PyExc_TypeError,
"first argument must be sequence of strings");
Py_DECREF(res);
return NULL;
}
slen = PyString_GET_SIZE(item);
while (reslen + slen + seplen >= sz) {
if (_PyString_Resize(&res, sz * 2) < 0)
return NULL;
sz *= 2;
p = PyString_AsString(res) + reslen;
}
if (i > 0) {
memcpy(p, sep, seplen);
p += seplen;
reslen += seplen;
}
memcpy(p, PyString_AS_STRING(item), slen);
p += slen;
reslen += slen;
}
_PyString_Resize(&res, reslen);
return res;
}
if (seq->ob_type->tp_as_sequence == NULL ||
(getitemfunc = seq->ob_type->tp_as_sequence->sq_item) == NULL)
{
PyErr_SetString(PyExc_TypeError,
"first argument must be a sequence");
return NULL;
}
/* This is now type safe */
for (i = 0; i < seqlen; i++) {
PyObject *item = getitemfunc(seq, i);
if (!item || !PyString_Check(item)) {
PyErr_SetString(PyExc_TypeError,
"first argument must be sequence of strings");
Py_DECREF(res);
Py_XDECREF(item);
return NULL;
}
slen = PyString_GET_SIZE(item);
while (reslen + slen + seplen >= sz) {
if (_PyString_Resize(&res, sz * 2) < 0) {
Py_DECREF(item);
return NULL;
}
sz *= 2;
p = PyString_AsString(res) + reslen;
}
if (i > 0) {
memcpy(p, sep, seplen);
p += seplen;
reslen += seplen;
}
memcpy(p, PyString_AS_STRING(item), slen);
p += slen;
reslen += slen;
Py_DECREF(item);
}
_PyString_Resize(&res, reslen);
return res;
}
PyDoc_STRVAR(find__doc__,
"find(s, sub [,start [,end]]) -> in\n"
"\n"
"Return the lowest index in s where substring sub is found,\n"
"such that sub is contained within s[start,end]. Optional\n"
"arguments start and end are interpreted as in slice notation.\n"
"\n"
"Return -1 on failure.");
static PyObject *
strop_find(PyObject *self, PyObject *args)
{
char *s, *sub;
Py_ssize_t len, n, i = 0, last = PY_SSIZE_T_MAX;
WARN;
if (!PyArg_ParseTuple(args, "t#t#|nn:find", &s, &len, &sub, &n, &i, &last))
return NULL;
if (last > len)
last = len;
if (last < 0)
last += len;
if (last < 0)
last = 0;
if (i < 0)
i += len;
if (i < 0)
i = 0;
if (n == 0 && i <= last)
return PyInt_FromLong((long)i);
last -= n;
for (; i <= last; ++i)
if (s[i] == sub[0] &&
(n == 1 || memcmp(&s[i+1], &sub[1], n-1) == 0))
return PyInt_FromLong((long)i);
return PyInt_FromLong(-1L);
}
PyDoc_STRVAR(rfind__doc__,
"rfind(s, sub [,start [,end]]) -> int\n"
"\n"
"Return the highest index in s where substring sub is found,\n"
"such that sub is contained within s[start,end]. Optional\n"
"arguments start and end are interpreted as in slice notation.\n"
"\n"
"Return -1 on failure.");
static PyObject *
strop_rfind(PyObject *self, PyObject *args)
{
char *s, *sub;
Py_ssize_t len, n, j;
Py_ssize_t i = 0, last = PY_SSIZE_T_MAX;
WARN;
if (!PyArg_ParseTuple(args, "t#t#|nn:rfind", &s, &len, &sub, &n, &i, &last))
return NULL;
if (last > len)
last = len;
if (last < 0)
last += len;
if (last < 0)
last = 0;
if (i < 0)
i += len;
if (i < 0)
i = 0;
if (n == 0 && i <= last)
return PyInt_FromLong((long)last);
for (j = last-n; j >= i; --j)
if (s[j] == sub[0] &&
(n == 1 || memcmp(&s[j+1], &sub[1], n-1) == 0))
return PyInt_FromLong((long)j);
return PyInt_FromLong(-1L);
}
static PyObject *
do_strip(PyObject *args, int striptype)
{
char *s;
Py_ssize_t len, i, j;
if (PyString_AsStringAndSize(args, &s, &len))
return NULL;
i = 0;
if (striptype != RIGHTSTRIP) {
while (i < len && isspace(Py_CHARMASK(s[i]))) {
i++;
}
}
j = len;
if (striptype != LEFTSTRIP) {
do {
j--;
} while (j >= i && isspace(Py_CHARMASK(s[j])));
j++;
}
if (i == 0 && j == len) {
Py_INCREF(args);
return args;
}
else
return PyString_FromStringAndSize(s+i, j-i);
}
PyDoc_STRVAR(strip__doc__,
"strip(s) -> string\n"
"\n"
"Return a copy of the string s with leading and trailing\n"
"whitespace removed.");
static PyObject *
strop_strip(PyObject *self, PyObject *args)
{
WARN;
return do_strip(args, BOTHSTRIP);
}
PyDoc_STRVAR(lstrip__doc__,
"lstrip(s) -> string\n"
"\n"
"Return a copy of the string s with leading whitespace removed.");
static PyObject *
strop_lstrip(PyObject *self, PyObject *args)
{
WARN;
return do_strip(args, LEFTSTRIP);
}
PyDoc_STRVAR(rstrip__doc__,
"rstrip(s) -> string\n"
"\n"
"Return a copy of the string s with trailing whitespace removed.");
static PyObject *
strop_rstrip(PyObject *self, PyObject *args)
{
WARN;
return do_strip(args, RIGHTSTRIP);
}
PyDoc_STRVAR(lower__doc__,
"lower(s) -> string\n"
"\n"
"Return a copy of the string s converted to lowercase.");
static PyObject *
strop_lower(PyObject *self, PyObject *args)
{
char *s, *s_new;
Py_ssize_t i, n;
PyObject *newstr;
int changed;
WARN;
if (PyString_AsStringAndSize(args, &s, &n))
return NULL;
newstr = PyString_FromStringAndSize(NULL, n);
if (newstr == NULL)
return NULL;
s_new = PyString_AsString(newstr);
changed = 0;
for (i = 0; i < n; i++) {
int c = Py_CHARMASK(*s++);
if (isupper(c)) {
changed = 1;
*s_new = tolower(c);
} else
*s_new = c;
s_new++;
}
if (!changed) {
Py_DECREF(newstr);
Py_INCREF(args);
return args;
}
return newstr;
}
PyDoc_STRVAR(upper__doc__,
"upper(s) -> string\n"
"\n"
"Return a copy of the string s converted to uppercase.");
static PyObject *
strop_upper(PyObject *self, PyObject *args)
{
char *s, *s_new;
Py_ssize_t i, n;
PyObject *newstr;
int changed;
WARN;
if (PyString_AsStringAndSize(args, &s, &n))
return NULL;
newstr = PyString_FromStringAndSize(NULL, n);
if (newstr == NULL)
return NULL;
s_new = PyString_AsString(newstr);
changed = 0;
for (i = 0; i < n; i++) {
int c = Py_CHARMASK(*s++);
if (islower(c)) {
changed = 1;
*s_new = toupper(c);
} else
*s_new = c;
s_new++;
}
if (!changed) {
Py_DECREF(newstr);
Py_INCREF(args);
return args;
}
return newstr;
}
PyDoc_STRVAR(capitalize__doc__,
"capitalize(s) -> string\n"
"\n"
"Return a copy of the string s with only its first character\n"
"capitalized.");
static PyObject *
strop_capitalize(PyObject *self, PyObject *args)
{
char *s, *s_new;
Py_ssize_t i, n;
PyObject *newstr;
int changed;
WARN;
if (PyString_AsStringAndSize(args, &s, &n))
return NULL;
newstr = PyString_FromStringAndSize(NULL, n);
if (newstr == NULL)
return NULL;
s_new = PyString_AsString(newstr);
changed = 0;
if (0 < n) {
int c = Py_CHARMASK(*s++);
if (islower(c)) {
changed = 1;
*s_new = toupper(c);
} else
*s_new = c;
s_new++;
}
for (i = 1; i < n; i++) {
int c = Py_CHARMASK(*s++);
if (isupper(c)) {
changed = 1;
*s_new = tolower(c);
} else
*s_new = c;
s_new++;
}
if (!changed) {
Py_DECREF(newstr);
Py_INCREF(args);
return args;
}
return newstr;
}
PyDoc_STRVAR(expandtabs__doc__,
"expandtabs(string, [tabsize]) -> string\n"
"\n"
"Expand tabs in a string, i.e. replace them by one or more spaces,\n"
"depending on the current column and the given tab size (default 8).\n"
"The column number is reset to zero after each newline occurring in the\n"
"string. This doesn't understand other non-printing characters.");
static PyObject *
strop_expandtabs(PyObject *self, PyObject *args)
{
/* Original by Fredrik Lundh */
char* e;
char* p;
char* q;
Py_ssize_t i, j;
PyObject* out;
char* string;
Py_ssize_t stringlen;
int tabsize = 8;
WARN;
/* Get arguments */
if (!PyArg_ParseTuple(args, "s#|i:expandtabs", &string, &stringlen, &tabsize))
return NULL;
if (tabsize < 1) {
PyErr_SetString(PyExc_ValueError,
"tabsize must be at least 1");
return NULL;
}
/* First pass: determine size of output string */
i = j = 0; /* j: current column; i: total of previous lines */
e = string + stringlen;
for (p = string; p < e; p++) {
if (*p == '\t')
j += tabsize - (j%tabsize);
else {
j++;
if (*p == '\n') {
i += j;
j = 0;
}
}
}
/* Second pass: create output string and fill it */
out = PyString_FromStringAndSize(NULL, i+j);
if (out == NULL)
return NULL;
i = 0;
q = PyString_AS_STRING(out);
for (p = string; p < e; p++) {
if (*p == '\t') {
j = tabsize - (i%tabsize);
i += j;
while (j-- > 0)
*q++ = ' ';
} else {
*q++ = *p;
i++;
if (*p == '\n')
i = 0;
}
}
return out;
}
PyDoc_STRVAR(count__doc__,
"count(s, sub[, start[, end]]) -> int\n"
"\n"
"Return the number of occurrences of substring sub in string\n"
"s[start:end]. Optional arguments start and end are\n"
"interpreted as in slice notation.");
static PyObject *
strop_count(PyObject *self, PyObject *args)
{
char *s, *sub;
Py_ssize_t len, n;
Py_ssize_t i = 0, last = PY_SSIZE_T_MAX;
Py_ssize_t m, r;
WARN;
if (!PyArg_ParseTuple(args, "t#t#|nn:count", &s, &len, &sub, &n, &i, &last))
return NULL;
if (last > len)
last = len;
if (last < 0)
last += len;
if (last < 0)
last = 0;
if (i < 0)
i += len;
if (i < 0)
i = 0;
m = last + 1 - n;
if (n == 0)
return PyInt_FromLong((long) (m-i));
r = 0;
while (i < m) {
if (!memcmp(s+i, sub, n)) {
r++;
i += n;
} else {
i++;
}
}
return PyInt_FromLong((long) r);
}
PyDoc_STRVAR(swapcase__doc__,
"swapcase(s) -> string\n"
"\n"
"Return a copy of the string s with upper case characters\n"
"converted to lowercase and vice versa.");
static PyObject *
strop_swapcase(PyObject *self, PyObject *args)
{
char *s, *s_new;
Py_ssize_t i, n;
PyObject *newstr;
int changed;
WARN;
if (PyString_AsStringAndSize(args, &s, &n))
return NULL;
newstr = PyString_FromStringAndSize(NULL, n);
if (newstr == NULL)
return NULL;
s_new = PyString_AsString(newstr);
changed = 0;
for (i = 0; i < n; i++) {
int c = Py_CHARMASK(*s++);
if (islower(c)) {
changed = 1;
*s_new = toupper(c);
}
else if (isupper(c)) {
changed = 1;
*s_new = tolower(c);
}
else
*s_new = c;
s_new++;
}
if (!changed) {
Py_DECREF(newstr);
Py_INCREF(args);
return args;
}
return newstr;
}
PyDoc_STRVAR(atoi__doc__,
"atoi(s [,base]) -> int\n"
"\n"
"Return the integer represented by the string s in the given\n"
"base, which defaults to 10. The string s must consist of one\n"
"or more digits, possibly preceded by a sign. If base is 0, it\n"
"is chosen from the leading characters of s, 0 for octal, 0x or\n"
"0X for hexadecimal. If base is 16, a preceding 0x or 0X is\n"
"accepted.");
static PyObject *
strop_atoi(PyObject *self, PyObject *args)
{
char *s, *end;
int base = 10;
long x;
char buffer[256]; /* For errors */
WARN;
if (!PyArg_ParseTuple(args, "s|i:atoi", &s, &base))
return NULL;
if ((base != 0 && base < 2) || base > 36) {
PyErr_SetString(PyExc_ValueError, "invalid base for atoi()");
return NULL;
}
while (*s && isspace(Py_CHARMASK(*s)))
s++;
errno = 0;
if (base == 0 && s[0] == '0')
x = (long) PyOS_strtoul(s, &end, base);
else
x = PyOS_strtol(s, &end, base);
if (end == s || !isalnum(Py_CHARMASK(end[-1])))
goto bad;
while (*end && isspace(Py_CHARMASK(*end)))
end++;
if (*end != '\0') {
bad:
PyOS_snprintf(buffer, sizeof(buffer),
"invalid literal for atoi(): %.200s", s);
PyErr_SetString(PyExc_ValueError, buffer);
return NULL;
}
else if (errno != 0) {
PyOS_snprintf(buffer, sizeof(buffer),
"atoi() literal too large: %.200s", s);
PyErr_SetString(PyExc_ValueError, buffer);
return NULL;
}
return PyInt_FromLong(x);
}
PyDoc_STRVAR(atol__doc__,
"atol(s [,base]) -> long\n"
"\n"
"Return the long integer represented by the string s in the\n"
"given base, which defaults to 10. The string s must consist\n"
"of one or more digits, possibly preceded by a sign. If base\n"
"is 0, it is chosen from the leading characters of s, 0 for\n"
"octal, 0x or 0X for hexadecimal. If base is 16, a preceding\n"
"0x or 0X is accepted. A trailing L or l is not accepted,\n"
"unless base is 0.");
static PyObject *
strop_atol(PyObject *self, PyObject *args)
{
char *s, *end;
int base = 10;
PyObject *x;
char buffer[256]; /* For errors */
WARN;
if (!PyArg_ParseTuple(args, "s|i:atol", &s, &base))
return NULL;
if ((base != 0 && base < 2) || base > 36) {
PyErr_SetString(PyExc_ValueError, "invalid base for atol()");
return NULL;
}
while (*s && isspace(Py_CHARMASK(*s)))
s++;
if (s[0] == '\0') {
PyErr_SetString(PyExc_ValueError, "empty string for atol()");
return NULL;
}
x = PyLong_FromString(s, &end, base);
if (x == NULL)
return NULL;
if (base == 0 && (*end == 'l' || *end == 'L'))
end++;
while (*end && isspace(Py_CHARMASK(*end)))
end++;
if (*end != '\0') {
PyOS_snprintf(buffer, sizeof(buffer),
"invalid literal for atol(): %.200s", s);
PyErr_SetString(PyExc_ValueError, buffer);
Py_DECREF(x);
return NULL;
}
return x;
}
PyDoc_STRVAR(atof__doc__,
"atof(s) -> float\n"
"\n"
"Return the floating point number represented by the string s.");
static PyObject *
strop_atof(PyObject *self, PyObject *args)
{
char *s, *end;
double x;
char buffer[256]; /* For errors */
WARN;
if (!PyArg_ParseTuple(args, "s:atof", &s))
return NULL;
while (*s && isspace(Py_CHARMASK(*s)))
s++;
if (s[0] == '\0') {
PyErr_SetString(PyExc_ValueError, "empty string for atof()");
return NULL;
}
errno = 0;
PyFPE_START_PROTECT("strop_atof", return 0)
x = PyOS_ascii_strtod(s, &end);
PyFPE_END_PROTECT(x)
while (*end && isspace(Py_CHARMASK(*end)))
end++;
if (*end != '\0') {
PyOS_snprintf(buffer, sizeof(buffer),
"invalid literal for atof(): %.200s", s);
PyErr_SetString(PyExc_ValueError, buffer);
return NULL;
}
else if (errno != 0) {
PyOS_snprintf(buffer, sizeof(buffer),
"atof() literal too large: %.200s", s);
PyErr_SetString(PyExc_ValueError, buffer);
return NULL;
}
return PyFloat_FromDouble(x);
}
PyDoc_STRVAR(maketrans__doc__, PyDoc_STRVAR(maketrans__doc__,
"maketrans(frm, to) -> string\n" "maketrans(frm, to) -> string\n"
"\n" "\n"
...@@ -910,297 +44,11 @@ strop_maketrans(PyObject *self, PyObject *args) ...@@ -910,297 +44,11 @@ strop_maketrans(PyObject *self, PyObject *args)
return result; return result;
} }
PyDoc_STRVAR(translate__doc__,
"translate(s,table [,deletechars]) -> string\n"
"\n"
"Return a copy of the string s, where all characters occurring\n"
"in the optional argument deletechars are removed, and the\n"
"remaining characters have been mapped through the given\n"
"translation table, which must be a string of length 256.");
static PyObject *
strop_translate(PyObject *self, PyObject *args)
{
register char *input, *table, *output;
Py_ssize_t i;
int c, changed = 0;
PyObject *input_obj;
char *table1, *output_start, *del_table=NULL;
Py_ssize_t inlen, tablen, dellen = 0;
PyObject *result;
int trans_table[256];
WARN;
if (!PyArg_ParseTuple(args, "St#|t#:translate", &input_obj,
&table1, &tablen, &del_table, &dellen))
return NULL;
if (tablen != 256) {
PyErr_SetString(PyExc_ValueError,
"translation table must be 256 characters long");
return NULL;
}
table = table1;
inlen = PyString_GET_SIZE(input_obj);
result = PyString_FromStringAndSize((char *)NULL, inlen);
if (result == NULL)
return NULL;
output_start = output = PyString_AsString(result);
input = PyString_AsString(input_obj);
if (dellen == 0) {
/* If no deletions are required, use faster code */
for (i = inlen; --i >= 0; ) {
c = Py_CHARMASK(*input++);
if (Py_CHARMASK((*output++ = table[c])) != c)
changed = 1;
}
if (changed)
return result;
Py_DECREF(result);
Py_INCREF(input_obj);
return input_obj;
}
for (i = 0; i < 256; i++)
trans_table[i] = Py_CHARMASK(table[i]);
for (i = 0; i < dellen; i++)
trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
for (i = inlen; --i >= 0; ) {
c = Py_CHARMASK(*input++);
if (trans_table[c] != -1)
if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
continue;
changed = 1;
}
if (!changed) {
Py_DECREF(result);
Py_INCREF(input_obj);
return input_obj;
}
/* Fix the size of the resulting string */
if (inlen > 0)
_PyString_Resize(&result, output - output_start);
return result;
}
/* What follows is used for implementing replace(). Perry Stoll. */
/*
mymemfind
strstr replacement for arbitrary blocks of memory.
Locates the first occurrence in the memory pointed to by MEM of the
contents of memory pointed to by PAT. Returns the index into MEM if
found, or -1 if not found. If len of PAT is greater than length of
MEM, the function returns -1.
*/
static Py_ssize_t
mymemfind(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
{
register Py_ssize_t ii;
/* pattern can not occur in the last pat_len-1 chars */
len -= pat_len;
for (ii = 0; ii <= len; ii++) {
if (mem[ii] == pat[0] &&
(pat_len == 1 ||
memcmp(&mem[ii+1], &pat[1], pat_len-1) == 0)) {
return ii;
}
}
return -1;
}
/*
mymemcnt
Return the number of distinct times PAT is found in MEM.
meaning mem=1111 and pat==11 returns 2.
mem=11111 and pat==11 also return 2.
*/
static Py_ssize_t
mymemcnt(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
{
register Py_ssize_t offset = 0;
Py_ssize_t nfound = 0;
while (len >= 0) {
offset = mymemfind(mem, len, pat, pat_len);
if (offset == -1)
break;
mem += offset + pat_len;
len -= offset + pat_len;
nfound++;
}
return nfound;
}
/*
mymemreplace
Return a string in which all occurrences of PAT in memory STR are
replaced with SUB.
If length of PAT is less than length of STR or there are no occurrences
of PAT in STR, then the original string is returned. Otherwise, a new
string is allocated here and returned.
on return, out_len is:
the length of output string, or
-1 if the input string is returned, or
unchanged if an error occurs (no memory).
return value is:
the new string allocated locally, or
NULL if an error occurred.
*/
static char *
mymemreplace(const char *str, Py_ssize_t len, /* input string */
const char *pat, Py_ssize_t pat_len, /* pattern string to find */
const char *sub, Py_ssize_t sub_len, /* substitution string */
Py_ssize_t count, /* number of replacements */
Py_ssize_t *out_len)
{
char *out_s;
char *new_s;
Py_ssize_t nfound, offset, new_len;
if (len == 0 || pat_len > len)
goto return_same;
/* find length of output string */
nfound = mymemcnt(str, len, pat, pat_len);
if (count < 0)
count = PY_SSIZE_T_MAX;
else if (nfound > count)
nfound = count;
if (nfound == 0)
goto return_same;
new_len = len + nfound*(sub_len - pat_len);
if (new_len == 0) {
/* Have to allocate something for the caller to free(). */
out_s = (char *)PyMem_MALLOC(1);
if (out_s == NULL)
return NULL;
out_s[0] = '\0';
}
else {
assert(new_len > 0);
new_s = (char *)PyMem_MALLOC(new_len);
if (new_s == NULL)
return NULL;
out_s = new_s;
for (; count > 0 && len > 0; --count) {
/* find index of next instance of pattern */
offset = mymemfind(str, len, pat, pat_len);
if (offset == -1)
break;
/* copy non matching part of input string */
memcpy(new_s, str, offset);
str += offset + pat_len;
len -= offset + pat_len;
/* copy substitute into the output string */
new_s += offset;
memcpy(new_s, sub, sub_len);
new_s += sub_len;
}
/* copy any remaining values into output string */
if (len > 0)
memcpy(new_s, str, len);
}
*out_len = new_len;
return out_s;
return_same:
*out_len = -1;
return (char *)str; /* cast away const */
}
PyDoc_STRVAR(replace__doc__,
"replace (str, old, new[, maxsplit]) -> string\n"
"\n"
"Return a copy of string str with all occurrences of substring\n"
"old replaced by new. If the optional argument maxsplit is\n"
"given, only the first maxsplit occurrences are replaced.");
static PyObject *
strop_replace(PyObject *self, PyObject *args)
{
char *str, *pat,*sub,*new_s;
Py_ssize_t len,pat_len,sub_len,out_len;
Py_ssize_t count = -1;
PyObject *newstr;
WARN;
if (!PyArg_ParseTuple(args, "t#t#t#|n:replace",
&str, &len, &pat, &pat_len, &sub, &sub_len,
&count))
return NULL;
if (pat_len <= 0) {
PyErr_SetString(PyExc_ValueError, "empty pattern string");
return NULL;
}
/* CAUTION: strop treats a replace count of 0 as infinity, unlke
* current (2.1) string.py and string methods. Preserve this for
* ... well, hard to say for what <wink>.
*/
if (count == 0)
count = -1;
new_s = mymemreplace(str,len,pat,pat_len,sub,sub_len,count,&out_len);
if (new_s == NULL) {
PyErr_NoMemory();
return NULL;
}
if (out_len == -1) {
/* we're returning another reference to the input string */
newstr = PyTuple_GetItem(args, 0);
Py_XINCREF(newstr);
}
else {
newstr = PyString_FromStringAndSize(new_s, out_len);
PyMem_FREE(new_s);
}
return newstr;
}
/* List of functions defined in the module */ /* List of functions defined in the module */
static PyMethodDef static PyMethodDef
strop_methods[] = { strop_methods[] = {
{"atof", strop_atof, METH_VARARGS, atof__doc__},
{"atoi", strop_atoi, METH_VARARGS, atoi__doc__},
{"atol", strop_atol, METH_VARARGS, atol__doc__},
{"capitalize", strop_capitalize, METH_O, capitalize__doc__},
{"count", strop_count, METH_VARARGS, count__doc__},
{"expandtabs", strop_expandtabs, METH_VARARGS, expandtabs__doc__},
{"find", strop_find, METH_VARARGS, find__doc__},
{"join", strop_joinfields, METH_VARARGS, joinfields__doc__},
{"joinfields", strop_joinfields, METH_VARARGS, joinfields__doc__},
{"lstrip", strop_lstrip, METH_O, lstrip__doc__},
{"lower", strop_lower, METH_O, lower__doc__},
{"maketrans", strop_maketrans, METH_VARARGS, maketrans__doc__}, {"maketrans", strop_maketrans, METH_VARARGS, maketrans__doc__},
{"replace", strop_replace, METH_VARARGS, replace__doc__},
{"rfind", strop_rfind, METH_VARARGS, rfind__doc__},
{"rstrip", strop_rstrip, METH_O, rstrip__doc__},
{"split", strop_splitfields, METH_VARARGS, splitfields__doc__},
{"splitfields", strop_splitfields, METH_VARARGS, splitfields__doc__},
{"strip", strop_strip, METH_O, strip__doc__},
{"swapcase", strop_swapcase, METH_O, swapcase__doc__},
{"translate", strop_translate, METH_VARARGS, translate__doc__},
{"upper", strop_upper, METH_O, upper__doc__},
{NULL, NULL} /* sentinel */ {NULL, NULL} /* sentinel */
}; };
...@@ -1208,41 +56,9 @@ strop_methods[] = { ...@@ -1208,41 +56,9 @@ strop_methods[] = {
PyMODINIT_FUNC PyMODINIT_FUNC
initstrop(void) initstrop(void)
{ {
PyObject *m, *s; PyObject *m;
char buf[256];
int c, n;
m = Py_InitModule4("strop", strop_methods, strop_module__doc__, m = Py_InitModule4("strop", strop_methods, strop_module__doc__,
(PyObject*)NULL, PYTHON_API_VERSION); (PyObject*)NULL, PYTHON_API_VERSION);
if (m == NULL) if (m == NULL)
return; return;
/* Create 'whitespace' object */
n = 0;
for (c = 0; c < 256; c++) {
if (isspace(c))
buf[n++] = c;
}
s = PyString_FromStringAndSize(buf, n);
if (s)
PyModule_AddObject(m, "whitespace", s);
/* Create 'lowercase' object */
n = 0;
for (c = 0; c < 256; c++) {
if (islower(c))
buf[n++] = c;
}
s = PyString_FromStringAndSize(buf, n);
if (s)
PyModule_AddObject(m, "lowercase", s);
/* Create 'uppercase' object */
n = 0;
for (c = 0; c < 256; c++) {
if (isupper(c))
buf[n++] = c;
}
s = PyString_FromStringAndSize(buf, n);
if (s)
PyModule_AddObject(m, "uppercase", s);
} }
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