code
stringlengths
1
1.72M
language
stringclasses
1 value
#globals #session options - set by floater.py only session = None #game consts # max acceleration in x when player runs over terrain player_ax = 300.0 # max fastness in x when player runs over terrain player_vx = 300.0 # min fastness floater w/resp terrain floater_v = 0.75*player_vx # max wait time for floater floater_max_wait_time = 2.0 # transitory, later will be calc from patrol lenght floaters_per_patrol = 2 floater_colors3 = [ (2, 202, 26), #greenish (53, 147, 253), #bluish (249, 240, 91), #yellow (255, 29, 215), #magenta ]
Python
#! /usr/bin/env python # encoding: utf-8 # waf 1.6.10 VERSION='0.3.3' import sys APPNAME='p2t' top = '.' out = 'build' CPP_SOURCES = ['poly2tri/common/shapes.cc', 'poly2tri/sweep/cdt.cc', 'poly2tri/sweep/advancing_front.cc', 'poly2tri/sweep/sweep_context.cc', 'poly2tri/sweep/sweep.cc', 'testbed/main.cc'] from waflib.Tools.compiler_cxx import cxx_compiler cxx_compiler['win32'] = ['g++'] #Platform specific libs if sys.platform == 'win32': # MS Windows sys_libs = ['glfw', 'opengl32'] elif sys.platform == 'darwin': # Apple OSX sys_libs = ['glfw', 'OpenGL'] else: # GNU/Linux, BSD, etc sys_libs = ['glfw', 'GL'] def options(opt): print(' set_options') opt.load('compiler_cxx') def configure(conf): print(' calling the configuration') conf.load('compiler_cxx') conf.env.CXXFLAGS = ['-O3', '-ffast-math'] conf.env.DEFINES_P2T = ['P2T'] conf.env.LIB_P2T = sys_libs def build(bld): print(' building') bld.program(features = 'cxx cxxprogram', source=CPP_SOURCES, target = 'p2t', uselib = 'P2T')
Python
try: import unittest2 as unittest except ImportError: import unittest from functools import wraps from readercsv import ReaderCSV class TestCaseBuilder(type): def __new__(meta, classname, bases, methods): new_methods = {} for method_name, method in methods.items(): if callable(method) and hasattr(method, 'data'): for param_values in method.data: if isinstance(param_values, str): params_str = "'%s'" % (param_values) elif method.param_names == None : params_str = ', '.join(str(x) for x in param_values) else: params_str = ', '.join(['%s=%s' % (k, v) for (k, v) in zip(method.param_names, param_values)]) module_name = new_methods.get('__module__', '<module>') new_method = meta.new_method(method, param_values) new_method.__name__ = "%s(%s)" % (method.__name__, params_str) new_method.__doc__ = "%s.%s.%s(%s)" % (module_name, classname, method.__name__, params_str) + (new_method.__doc__ or "") new_methods[new_method.__name__] = new_method else: new_methods[method_name] = method return type.__new__(meta, classname, bases, new_methods) @classmethod def new_method(cls, method, param_values): @wraps(method) def new_method(self): if isinstance(param_values, str): return method(self, param_values) return method(self, *param_values) return new_method class Params(object): __metaclass__ = TestCaseBuilder @classmethod def set(cls, values): """ Decorator to parametrize a test method @Params.set([ (2323, 656), (87687, 545) ]) """ def decorator(func): @wraps(func) def newfunc(*arg, **kwargs): return func(*arg, **kwargs) newfunc.param_names = func.func_code.co_varnames[1:] newfunc.data = values return newfunc return decorator @classmethod def fromCSV(cls, data, types=None, hasHeaders=False, separator=','): """ Decorator to parametrize a test method @Params.fromCSV("c:\\data.csv", False, [str, int] ) """ if data.endswith('.csv'): f = open(data, 'r+') txt = f.read() #.rstrip('\r\n') f.close() else: txt = data.strip('\r\n\t ') reader = ReaderCSV(hasHeaders, separator, types) values = reader.parse(txt) headers = reader.headers def decorator(func): @wraps(func) def newfunc(*arg, **kwargs): return func(*arg, **kwargs) newfunc.param_names = func.func_code.co_varnames[1:] newfunc.data = values if len(newfunc.param_names) != len(newfunc.data[0]): raise Exception("Number of values(%s) doesn't match the number of arguments(%s)" % (len(newfunc.data[0]), len(newfunc.param_names))) return newfunc return decorator class TestCase(unittest.TestCase): __metaclass__ = TestCaseBuilder
Python
from decimal import Decimal from datetime import datetime class ReaderCSV: headers = None def __init__(self, hasHeaders, separator, types=None): self.headers = [] if hasHeaders else None self._isHeadersRow = hasHeaders self._separator = separator self._types = types self._typesmax = len(types) - 1 if types is not None else 0 self._characters = {} self._row_values = [] self._value_chars = [] self._quotechar = '' self._fieldIndex = -1 def parse(self, text): rows = [] self._characters = text + '\0' inquote = False max = len(self._characters) - 1 i = 0 while i < max: char1 = self._characters[i] char2 = self._characters[i + 1] if not inquote and (char1 == '\r' or char1 == '\n'): if char2 == '\r' or char2 == '\n': i += 1 self.push_value() if self._isHeadersRow: self.headers = self.pop_values() self._isHeadersRow = False else: rows.append(self.pop_values()) elif not inquote and char1 == self._separator: self.push_value() else: if char1 == '\"': # or char1 == '\'': if inquote and char1 == self._quotechar and char2 == self._quotechar: i += 1 elif inquote: inquote = False else: inquote = True self._quotechar = char1 self._value_chars.append(char1) i += 1 if inquote: raise Exception("Closing quote is missing") if len(self._value_chars) != 0: self.push_value() if len(self._row_values) != 0: rows.append(self.pop_values()) return rows def push_value(self): self._fieldIndex += 1 value_str = ''.join(self._value_chars).strip(' \t').strip(self._quotechar) if self._isHeadersRow or self._types is None: value = value_str else: if self._fieldIndex > self._typesmax: raise Exception("Number of values(%s) doesn't match the number of types(%s)" % (self._fieldIndex + 1, self._typesmax + 1)) value = self.convert(value_str, self._types[self._fieldIndex]) self._row_values.append(value) self._value_chars = [] def pop_values(self): row_values = self._row_values self._row_values = [] self._value_chars = [] self._fieldIndex = -1 return row_values def convert(self, value, totype): try: if totype is str: return value if totype is int: return int(value) if totype is long: return long(value) if totype is float: return float(value) if totype is Decimal: return Decimal(value) if totype is bool: return bool(value) #if totype is character: # return str(value)[0]; if totype is datetime: return datetime(value) except: raise Exception("Conversion failed to type %s . Value=<%s>" % (totype, value)) raise Exception("Conversion to type %s is not implemented" % totype)
Python
import time from PIL import Image, ImageChops class CmpPIL: def compare(self, fileA, fileB, fileDiff): a = Image.open(fileA) if a.mode == 'RGBA': a = a.convert('RGB') b = Image.open(fileB) if b.mode == 'RGBA': b = b.convert('RGB') d = ImageChops.difference(a, b) d.save(fileDiff) for count, pixel in Image.eval(d, lambda p: p > 10).getcolors(): if pixel == (0, 0, 0): return (d.size[0] * d.size[1]) - count return 0 if __name__ == '__main__': st = time.time() diffCount = CmpPIL().compare('c:\\imgA.png', 'c:\\imgB.png', 'c:\\diff.png') print 'diffCount={0} time={1}'.format(diffCount, time.time() - st)
Python
try: import unittest2 as unittest except ImportError: import unittest from functools import wraps class TestCaseBuilder(type): def __new__(meta, classname, bases, methods): new_methods = {} for method_name, method in methods.items(): if callable(method) and hasattr(method, 'data'): for param_values in method.data: if isinstance(param_values, str): params_str = "'%s'" % (param_values) elif method.param_names == None : params_str = ', '.join( str(x) for x in param_values) else: params_str = ', '.join(['%s=%s' % (k, v) for (k, v) in zip(method.param_names, param_values)]) module_name = new_methods.get('__module__', '<module>') new_method = meta.new_method(method, param_values) new_method.__name__ = "%s(%s)" % (method.__name__, params_str) new_method.__doc__ = "%s.%s.%s(%s)" % (module_name, classname, method.__name__, params_str) + (new_method.__doc__ or "") new_methods[new_method.__name__] = new_method else: new_methods[method_name] = method return type.__new__(meta, classname, bases, new_methods) @classmethod def new_method(cls, method, param_values): @wraps(method) def new_method(self): if isinstance(param_values, str): return method(self, param_values) return method(self, *param_values) return new_method class Params(object): __metaclass__ = TestCaseBuilder @classmethod def set(cls, names_or_values, values = None): """ Decorator to parametrize a test method @Params.set(("param", "expected"),[ (2323, 656), (87687, 545)]) """ def decorator(func): @wraps(func) def newfunc(*arg, **kwargs): return func(*arg, **kwargs) newfunc.param_names = names_or_values if values != None else None newfunc.data = names_or_values if values == None else values return newfunc return decorator class TestCase(unittest.TestCase): __metaclass__ = TestCaseBuilder
Python
""" test configuration(s) for running CPython's regression test suite on top of PyPy """ import py import sys import pypy from pypy.interpreter.gateway import ApplevelClass from pypy.interpreter.error import OperationError from pypy.interpreter.module import Module as PyPyModule from pypy.interpreter.main import run_string, run_file # the following adds command line options as a side effect! from pypy.conftest import gettestobjspace, option as pypy_option from test.regrtest import reportdiff from test import pystone from pypy.tool.pytest import appsupport from pypy.tool.pytest.confpath import pypydir, libpythondir, \ regrtestdir, modregrtestdir, testresultdir from pypy.tool.pytest.result import Result, ResultFromMime pypyexecpath = pypydir.join('bin', 'pypy-c') dist_rsync_roots = ['.', '../pypy', '../py'] # # Interfacing/Integrating with py.test's collection process # # XXX no nice way to implement a --listpassing py.test option?! #option = py.test.addoptions("compliance testing options", # py.test.Option('-L', '--listpassing', action="store", default=None, # type="string", dest="listpassing", # help="just display the list of expected-to-pass tests.") Option = py.test.config.Option option = py.test.config.addoptions("compliance testing options", Option('-C', '--compiled', action="store_true", default=False, dest="use_compiled", help="use a compiled version of pypy"), Option('--compiled-pypy', action="store", type="string", dest="pypy_executable", default=str(pypyexecpath), help="to use together with -C to specify the path to the " "compiled version of pypy, by default expected in pypy/bin/pypy-c"), Option('-E', '--extracttests', action="store_true", default=False, dest="extracttests", help="try to extract single tests and run them via py.test/PyPy"), Option('-T', '--timeout', action="store", type="string", default="100mp", dest="timeout", help="fail a test module after the given timeout. " "specify in seconds or 'NUMmp' aka Mega-Pystones"), Option('--resultdir', action="store", type="string", default=None, dest="resultdir", help="directory under which to store results in USER@HOST subdirs", ), ) def gettimeout(): timeout = option.timeout.lower() if timeout.endswith('mp'): megapystone = float(timeout[:-2]) t, stone = pystone.Proc0(10000) pystonetime = t/stone seconds = megapystone * 1000000 * pystonetime return seconds return float(timeout) def callex(space, func, *args, **kwargs): try: return func(*args, **kwargs) except OperationError, e: ilevelinfo = py.code.ExceptionInfo() if e.match(space, space.w_KeyboardInterrupt): raise KeyboardInterrupt appexcinfo = appsupport.AppExceptionInfo(space, e) if appexcinfo.traceback: print "appexcinfo.traceback:" py.std.pprint.pprint(appexcinfo.traceback) raise py.test.collect.Item.Failed(excinfo=appexcinfo) raise py.test.collect.Item.Failed(excinfo=ilevelinfo) # # compliance modules where we invoke test_main() usually call into # test_support.(run_suite|run_doctests) # we intercept those calls and use the provided information # for our collection process. This allows us to run all the # tests one by one. # app = ApplevelClass(''' #NOT_RPYTHON import unittest from test import test_support import sys def getmethods(suite_or_class): """ flatten out suites down to TestCase instances/methods. """ if isinstance(suite_or_class, unittest.TestCase): res = [suite_or_class] elif isinstance(suite_or_class, unittest.TestSuite): res = [] for x in suite_or_class._tests: res.extend(getmethods(x)) elif isinstance(suite_or_class, list): res = [] for x in suite_or_class: res.extend(getmethods(x)) else: raise TypeError, "expected TestSuite or TestClass, got %r" %(suite_or_class) return res # # exported API # def intercept_test_support(): """ intercept calls to test_support.run_doctest and run_suite. Return doctestmodules, suites which will hold collected items from these test_support invocations. """ suites = [] doctestmodules = [] def hack_run_doctest(module, verbose=None): doctestmodules.append(module) test_support.run_doctest = hack_run_doctest def hack_run_suite(suite, testclass=None): suites.append(suite) test_support.run_suite = hack_run_suite return suites, doctestmodules def collect_intercepted(suites, doctestmodules): namemethodlist = [] for method in getmethods(suites): name = (method.__class__.__name__ + '.' + method._TestCase__testMethodName) namemethodlist.append((name, method)) doctestlist = [] for mod in doctestmodules: doctestlist.append((mod.__name__, mod)) return namemethodlist, doctestlist def run_testcase_method(method): result = method.defaultTestResult() method.run(result) if result.errors: assert len(result.errors) print result.errors[0][1] if result.failures: assert len(result.failures) print result.failures[0][1] if result.failures or result.errors: return 1 def set_argv(filename): sys.argv[:] = ['python', filename] ''') intercept_test_support = app.interphook('intercept_test_support') collect_intercepted = app.interphook('collect_intercepted') run_testcase_method = app.interphook('run_testcase_method') set_argv = app.interphook('set_argv') def start_intercept(space): w_suites, w_doctestmodules = space.unpacktuple(intercept_test_support(space)) return w_suites, w_doctestmodules def collect_intercept(space, w_suites, w_doctestmodules): w_result = callex(space, collect_intercepted, space, w_suites, w_doctestmodules) w_namemethods, w_doctestlist = space.unpacktuple(w_result) return w_namemethods, w_doctestlist class SimpleRunItem(py.test.collect.Item): """ Run a module file and compare its output to the expected output in the output/ directory. """ def call_capture(self, space, func, *args): regrtest = self.parent.regrtest oldsysout = sys.stdout sys.stdout = capturesysout = py.std.cStringIO.StringIO() try: try: res = regrtest.run_file(space) except: print capturesysout.getvalue() raise else: return res, capturesysout.getvalue() finally: sys.stdout = oldsysout def run(self): # XXX integrate this into InterceptedRunModule # but we want a py.test refactoring towards # more autonomy of colitems regarding # their representations regrtest = self.parent.regrtest space = gettestobjspace() res, output = self.call_capture(space, regrtest.run_file, space) outputpath = regrtest.getoutputpath() if outputpath: # we want to compare outputs # regrtest itself prepends the test_name to the captured output result = outputpath.purebasename + "\n" + output expected = outputpath.read(mode='r') if result != expected: reportdiff(expected, result) py.test.fail("output check failed: %s" % (self.fspath.basename,)) if output: print output, # class InterceptedRunModule(py.test.collect.Module): """ special handling for tests with a proper 'def test_main(): ' definition invoking test_support.run_suite or run_unittest (XXX add support for test_support.run_doctest). """ def __init__(self, name, parent, regrtest): super(InterceptedRunModule, self).__init__(name, parent) self.regrtest = regrtest self.fspath = regrtest.getfspath() def _prepare(self): if hasattr(self, 'name2item'): return self.name2item = {} space = gettestobjspace() if self.regrtest.dumbtest or self.regrtest.getoutputpath(): self.name2item['output'] = SimpleRunItem('output', self) return tup = start_intercept(space) self.regrtest.run_file(space) w_namemethods, w_doctestlist = collect_intercept(space, *tup) # setup {name -> wrapped testcase method} for w_item in space.unpackiterable(w_namemethods): w_name, w_method = space.unpacktuple(w_item) name = space.str_w(w_name) testitem = AppTestCaseMethod(name, parent=self, w_method=w_method) self.name2item[name] = testitem # setup {name -> wrapped doctest module} for w_item in space.unpackiterable(w_doctestlist): w_name, w_module = space.unpacktuple(w_item) name = space.str_w(w_name) testitem = AppDocTestModule(name, parent=self, w_module=w_module) self.name2item[name] = testitem def run(self): self._prepare() keys = self.name2item.keys() keys.sort(lambda x,y: cmp(x.lower(), y.lower())) return keys def join(self, name): self._prepare() try: return self.name2item[name] except KeyError: pass class AppDocTestModule(py.test.collect.Item): def __init__(self, name, parent, w_module): super(AppDocTestModule, self).__init__(name, parent) self.w_module = w_module def run(self): py.test.skip("application level doctest modules not supported yet.") class AppTestCaseMethod(py.test.collect.Item): def __init__(self, name, parent, w_method): super(AppTestCaseMethod, self).__init__(name, parent) self.space = gettestobjspace() self.w_method = w_method def run(self): space = self.space filename = str(self.fspath) callex(space, set_argv, space, space.wrap(filename)) #space.call_function(self.w_method) w_res = callex(space, run_testcase_method, space, self.w_method) if space.is_true(w_res): raise AssertionError( "testcase instance invociation raised errors, see stdoudt") # ________________________________________________________________________ # # classification of all tests files (this is ongoing work) # class RegrTest: """ Regression Test Declaration.""" def __init__(self, basename, enabled=False, dumbtest=False, oldstyle=False, core=False, compiler=None, usemodules = ''): self.basename = basename self.enabled = enabled self.dumbtest = dumbtest # we have to determine the value of oldstyle # lazily because at RegrTest() call time the command # line options haven't been parsed! self._oldstyle = oldstyle self._usemodules = usemodules.split() self._compiler = compiler self.core = core def oldstyle(self): return self._oldstyle #or pypy_option.oldstyle oldstyle = property(oldstyle) def usemodules(self): return self._usemodules #+ pypy_option.usemodules usemodules = property(usemodules) def compiler(self): return self._compiler #or pypy_option.compiler compiler = property(compiler) def getoptions(self): l = [] for name in 'oldstyle', 'core': if getattr(self, name): l.append(name) for name in self.usemodules: l.append(name) return l def ismodified(self): return modregrtestdir.join(self.basename).check() def getfspath(self): fn = modregrtestdir.join(self.basename) if fn.check(): return fn fn = regrtestdir.join(self.basename) return fn def getoutputpath(self): p = modregrtestdir.join('output', self.basename).new(ext='') if p.check(file=1): return p p = regrtestdir.join('output', self.basename).new(ext='') if p.check(file=1): return p def _prepare(self, space): # output tests sometimes depend on not running in # verbose mode if not hasattr(self, '_prepared'): if self.getoutputpath(): space.appexec([], """(): from test import test_support test_support.verbose = False """) self._prepared = True def run_file(self, space): self._prepare(space) fspath = self.getfspath() assert fspath.check() if self.oldstyle: space.enable_old_style_classes_as_default_metaclass() try: modname = fspath.purebasename space.appexec([], '''(): from test import %(modname)s m = %(modname)s if hasattr(m, 'test_main'): m.test_main() ''' % locals()) finally: space.enable_new_style_classes_as_default_metaclass() testmap = [ RegrTest('test___all__.py', enabled=True, core=True), # fixable RegrTest('test___future__.py', enabled=True, dumbtest=1, core=True), RegrTest('test__locale.py', enabled=True), RegrTest('test_aepack.py', enabled=False), RegrTest('test_al.py', enabled=False, dumbtest=1), RegrTest('test_anydbm.py', enabled=True), RegrTest('test_applesingle.py', enabled=False), RegrTest('test_array.py', enabled=True, core=True), RegrTest('test_asynchat.py', enabled=False, usemodules='thread'), RegrTest('test_atexit.py', enabled=True, dumbtest=1, core=True), RegrTest('test_audioop.py', enabled=False, dumbtest=1), RegrTest('test_augassign.py', enabled=True, core=True), RegrTest('test_base64.py', enabled=True), RegrTest('test_bastion.py', enabled=True, dumbtest=1), RegrTest('test_binascii.py', enabled=False), #rev 10840: 2 of 8 tests fail RegrTest('test_binhex.py', enabled=False), #rev 10840: 1 of 1 test fails RegrTest('test_binop.py', enabled=True, core=True), RegrTest('test_bisect.py', enabled=True, core=True), RegrTest('test_bool.py', enabled=True, core=True), RegrTest('test_bsddb.py', enabled=False), RegrTest('test_bsddb185.py', enabled=False), RegrTest('test_bsddb3.py', enabled=False), RegrTest('test_bufio.py', enabled=True, dumbtest=1, core=True), RegrTest('test_builtin.py', enabled=True, core=True), RegrTest('test_bz2.py', enabled=False), RegrTest('test_calendar.py', enabled=True), RegrTest('test_call.py', enabled=True, core=True), RegrTest('test_capi.py', enabled=False, dumbtest=1), RegrTest('test_cd.py', enabled=False, dumbtest=1), RegrTest('test_cfgparser.py', enabled=False), #rev 10840: Uncaught interp-level exception: #File "pypy/objspace/std/fake.py", line 133, in setfastscope #raise UnwrapError('calling %s: %s' % (self.code.cpy_callable, e)) #pypy.objspace.std.model.UnwrapError: calling <built-in function backslashreplace_errors>: cannot unwrap <UserW_ObjectObject() instance of <W_TypeObject(UnicodeError)>> RegrTest('test_cgi.py', enabled=True), RegrTest('test_charmapcodec.py', enabled=True, core=True), RegrTest('test_cl.py', enabled=False, dumbtest=1), RegrTest('test_class.py', enabled=True, oldstyle=True, core=True), RegrTest('test_cmath.py', enabled=True, dumbtest=1, core=True), RegrTest('test_codeccallbacks.py', enabled=True, core=True), RegrTest('test_codecencodings_cn.py', enabled=False), RegrTest('test_codecencodings_hk.py', enabled=False), RegrTest('test_codecencodings_jp.py', enabled=False), RegrTest('test_codecencodings_kr.py', enabled=False), RegrTest('test_codecencodings_tw.py', enabled=False), RegrTest('test_codecmaps_cn.py', enabled=False), RegrTest('test_codecmaps_hk.py', enabled=False), RegrTest('test_codecmaps_jp.py', enabled=False), RegrTest('test_codecmaps_kr.py', enabled=False), RegrTest('test_codecmaps_tw.py', enabled=False), RegrTest('test_codecs.py', enabled=True, core=True), RegrTest('test_codeop.py', enabled=True, core=True), RegrTest('test_coercion.py', enabled=True, oldstyle=True, core=True), RegrTest('test_colorsys.py', enabled=True), RegrTest('test_commands.py', enabled=True), RegrTest('test_compare.py', enabled=True, oldstyle=True, core=True), RegrTest('test_compile.py', enabled=True, core=True), RegrTest('test_compiler.py', enabled=True, core=False), # this test tests the compiler package from stdlib RegrTest('test_complex.py', enabled=True, core=True), RegrTest('test_contains.py', enabled=True, dumbtest=1, core=True), RegrTest('test_cookie.py', enabled=False), RegrTest('test_cookielib.py', enabled=False), RegrTest('test_copy.py', enabled=True, core=True), RegrTest('test_copy_reg.py', enabled=True, core=True), RegrTest('test_cpickle.py', enabled=True, core=True), RegrTest('test_crypt.py', usemodules='crypt', enabled=False, dumbtest=1), RegrTest('test_csv.py', enabled=False), #rev 10840: ImportError: _csv RegrTest('test_curses.py', enabled=False, dumbtest=1), RegrTest('test_datetime.py', enabled=True), RegrTest('test_dbm.py', enabled=False, dumbtest=1), RegrTest('test_decimal.py', enabled=True), RegrTest('test_decorators.py', enabled=True, core=True), RegrTest('test_deque.py', enabled=True, core=True), RegrTest('test_descr.py', enabled=True, core=True, oldstyle=True, usemodules='_weakref'), RegrTest('test_descrtut.py', enabled=True, core=True, oldstyle=True), RegrTest('test_dict.py', enabled=True, core=True), RegrTest('test_difflib.py', enabled=True, dumbtest=1), RegrTest('test_dircache.py', enabled=True, core=True), RegrTest('test_dis.py', enabled=True), RegrTest('test_distutils.py', enabled=True), RegrTest('test_dl.py', enabled=False, dumbtest=1), RegrTest('test_doctest.py', usemodules="thread", enabled=True), RegrTest('test_doctest2.py', enabled=True), RegrTest('test_dumbdbm.py', enabled=True), RegrTest('test_dummy_thread.py', enabled=True, core=True), RegrTest('test_dummy_threading.py', enabled=True, dumbtest=1, core=True), RegrTest('test_email.py', enabled=False), #rev 10840: Uncaught interp-level exception RegrTest('test_email_codecs.py', enabled=False, dumbtest=1), RegrTest('test_enumerate.py', enabled=True, core=True), RegrTest('test_eof.py', enabled=True, core=True), RegrTest('test_errno.py', enabled=True, dumbtest=1), RegrTest('test_exceptions.py', enabled=True, core=True), RegrTest('test_extcall.py', enabled=True, core=True), RegrTest('test_fcntl.py', enabled=False, dumbtest=1), RegrTest('test_file.py', enabled=True, dumbtest=1, usemodules="posix", core=True), RegrTest('test_filecmp.py', enabled=True, core=True), RegrTest('test_fileinput.py', enabled=True, dumbtest=1, core=True), RegrTest('test_fnmatch.py', enabled=True, core=True), RegrTest('test_fork1.py', enabled=False, dumbtest=1), RegrTest('test_format.py', enabled=True, dumbtest=1, core=True), RegrTest('test_fpformat.py', enabled=True, core=True), RegrTest('test_frozen.py', enabled=False), RegrTest('test_funcattrs.py', enabled=True, dumbtest=1, core=True), RegrTest('test_future.py', enabled=True, core=True), RegrTest('test_future1.py', enabled=True, dumbtest=1, core=True), RegrTest('test_future2.py', enabled=True, dumbtest=1, core=True), RegrTest('test_future3.py', enabled=True, core=True), RegrTest('test_gc.py', enabled=True, dumbtest=1, usemodules='_weakref'), RegrTest('test_gdbm.py', enabled=False, dumbtest=1), RegrTest('test_generators.py', enabled=True, core=True, usemodules='thread _weakref'), #rev 10840: 30 of 152 tests fail RegrTest('test_genexps.py', enabled=True, core=True, usemodules='_weakref'), RegrTest('test_getargs.py', enabled=False, dumbtest=1), RegrTest('test_getargs2.py', enabled=False), #rev 10840: ImportError: _testcapi RegrTest('test_getopt.py', enabled=True, dumbtest=1, core=True), RegrTest('test_gettext.py', enabled=False), #rev 10840: 28 of 28 tests fail RegrTest('test_gl.py', enabled=False, dumbtest=1), RegrTest('test_glob.py', enabled=True, core=True), RegrTest('test_global.py', enabled=True, core=True, compiler='ast'), RegrTest('test_grammar.py', enabled=True, core=True), RegrTest('test_grp.py', enabled=False), #rev 10840: ImportError: grp RegrTest('test_gzip.py', enabled=False, dumbtest=1), RegrTest('test_hash.py', enabled=True, core=True), RegrTest('test_heapq.py', enabled=True, core=True), RegrTest('test_hexoct.py', enabled=True, core=True), RegrTest('test_hmac.py', enabled=True), RegrTest('test_hotshot.py', enabled=False), #rev 10840: ImportError: _hotshot RegrTest('test_htmllib.py', enabled=True), RegrTest('test_htmlparser.py', enabled=True), RegrTest('test_httplib.py', enabled=True), RegrTest('test_imageop.py', enabled=False, dumbtest=1), RegrTest('test_imaplib.py', enabled=True, dumbtest=1), RegrTest('test_imgfile.py', enabled=False, dumbtest=1), RegrTest('test_imp.py', enabled=True, core=True, usemodules='thread'), RegrTest('test_import.py', enabled=True, dumbtest=1, core=True), RegrTest('test_importhooks.py', enabled=True, core=True), RegrTest('test_inspect.py', enabled=True, dumbtest=1), RegrTest('test_ioctl.py', enabled=False), RegrTest('test_isinstance.py', enabled=True, core=True), RegrTest('test_iter.py', enabled=True, core=True), #rev 10840: Uncaught interp-level exception: Same place as test_cfgparser RegrTest('test_iterlen.py', enabled=True, core=True), RegrTest('test_itertools.py', enabled=True, core=True), # modified version in pypy/lib/test2 RegrTest('test_largefile.py', enabled=True, dumbtest=1), RegrTest('test_linuxaudiodev.py', enabled=False), RegrTest('test_list.py', enabled=True, core=True), RegrTest('test_locale.py', enabled=False, dumbtest=1), RegrTest('test_logging.py', enabled=False, usemodules='thread'), RegrTest('test_long.py', enabled=True, dumbtest=1, core=True), RegrTest('test_long_future.py', enabled=True, dumbtest=1, core=True), RegrTest('test_longexp.py', enabled=True, core=True), RegrTest('test_macfs.py', enabled=False), RegrTest('test_macostools.py', enabled=False), RegrTest('test_macpath.py', enabled=True), RegrTest('test_mailbox.py', enabled=True), RegrTest('test_marshal.py', enabled=True, dumbtest=1, core=True), RegrTest('test_math.py', enabled=True, core=True, usemodules='math'), RegrTest('test_md5.py', enabled=False), RegrTest('test_mhlib.py', enabled=True), RegrTest('test_mimetools.py', enabled=True), RegrTest('test_mimetypes.py', enabled=True), RegrTest('test_MimeWriter.py', enabled=True, core=False), RegrTest('test_minidom.py', enabled=False, dumbtest=1), RegrTest('test_mmap.py', enabled=False), RegrTest('test_module.py', enabled=True, dumbtest=1, core=True), RegrTest('test_multibytecodec.py', enabled=True), RegrTest('test_multibytecodec_support.py', enabled=True, core=True), RegrTest('test_multifile.py', enabled=True), RegrTest('test_mutants.py', enabled=True, dumbtest=1, core="possibly"), RegrTest('test_netrc.py', enabled=True), RegrTest('test_new.py', enabled=True, core=True, oldstyle=True), RegrTest('test_nis.py', enabled=False), RegrTest('test_normalization.py', enabled=False), RegrTest('test_ntpath.py', enabled=True, dumbtest=1), RegrTest('test_opcodes.py', enabled=True, core=True), RegrTest('test_openpty.py', enabled=False), RegrTest('test_operations.py', enabled=True, core=True), RegrTest('test_operator.py', enabled=True, core=True), RegrTest('test_optparse.py', enabled=False), # this test fails because it expects that PyPy's builtin # functions act as if they are staticmethods that can be put # on classes and don't get bound etc.pp. RegrTest('test_os.py', enabled=True, core=True), RegrTest('test_ossaudiodev.py', enabled=False), RegrTest('test_parser.py', enabled=True, core=True), #rev 10840: 18 of 18 tests fail RegrTest('test_peepholer.py', enabled=True), RegrTest('test_pep247.py', enabled=False, dumbtest=1), RegrTest('test_pep263.py', enabled=True, dumbtest=1), RegrTest('test_pep277.py', enabled=False), # XXX this test is _also_ an output test, damn it # seems to be the only one that invokes run_unittest # and is an unittest RegrTest('test_pep292.py', enabled=True), RegrTest('test_pickle.py', enabled=True, core=True), RegrTest('test_pickletools.py', enabled=True, dumbtest=1, core=False), RegrTest('test_pkg.py', enabled=True, core=True), RegrTest('test_pkgimport.py', enabled=True, core=True), RegrTest('test_plistlib.py', enabled=False), RegrTest('test_poll.py', enabled=False), RegrTest('test_popen.py', enabled=True), RegrTest('test_popen2.py', enabled=True), RegrTest('test_posix.py', enabled=True), RegrTest('test_posixpath.py', enabled=True), RegrTest('test_pow.py', enabled=True, core=True), RegrTest('test_pprint.py', enabled=True, core=True), RegrTest('test_profile.py', enabled=True), RegrTest('test_profilehooks.py', enabled=True, core=True), RegrTest('test_pty.py', enabled=False), RegrTest('test_pwd.py', enabled=False), #rev 10840: ImportError: pwd RegrTest('test_pyclbr.py', enabled=False), RegrTest('test_pyexpat.py', enabled=False), RegrTest('test_queue.py', enabled=False, dumbtest=1), RegrTest('test_quopri.py', enabled=True), RegrTest('test_random.py', enabled=False), #rev 10840: Uncaught app-level exception: #class WichmannHill_TestBasicOps(TestBasicOps): #File "test_random.py", line 125 in WichmannHill_TestBasicOps #gen = random.WichmannHill() #AttributeError: 'module' object has no attribute 'WichmannHill' RegrTest('test_re.py', enabled=True, core=True), RegrTest('test_regex.py', enabled=False), RegrTest('test_repr.py', enabled=True, oldstyle=True, core=True), #rev 10840: 6 of 12 tests fail. Always minor stuff like #'<function object at 0x40db3e0c>' != '<built-in function hash>' RegrTest('test_resource.py', enabled=False), RegrTest('test_rfc822.py', enabled=True), RegrTest('test_rgbimg.py', enabled=False), RegrTest('test_richcmp.py', enabled=True, core=True), #rev 10840: 1 of 11 test fails. The failing one had an infinite recursion. RegrTest('test_robotparser.py', enabled=True), RegrTest('test_sax.py', enabled=False, dumbtest=1), RegrTest('test_scope.py', enabled=True, core=True), RegrTest('test_scriptpackages.py', enabled=False), RegrTest('test_select.py', enabled=False, dumbtest=1), RegrTest('test_set.py', enabled=True, core=True), RegrTest('test_sets.py', enabled=True), RegrTest('test_sgmllib.py', enabled=True), RegrTest('test_sha.py', enabled=True), # one test is taken out (too_slow_test_case_3), rest passses RegrTest('test_shelve.py', enabled=True), RegrTest('test_shlex.py', enabled=True), RegrTest('test_shutil.py', enabled=True), RegrTest('test_signal.py', enabled=False), RegrTest('test_site.py', enabled=False, core=False), # considered cpython impl-detail # Needs non-faked codecs. RegrTest('test_slice.py', enabled=True, dumbtest=1, core=True), RegrTest('test_socket.py', enabled=False, usemodules='thread _weakref'), RegrTest('test_socket_ssl.py', enabled=False), RegrTest('test_socketserver.py', enabled=False, usemodules='thread'), RegrTest('test_softspace.py', enabled=True, dumbtest=1, core=True), RegrTest('test_sort.py', enabled=True, dumbtest=1, core=True), RegrTest('test_str.py', enabled=True, core=True), #rev 10840: at least two tests fail, after several hours I gave up waiting for the rest RegrTest('test_strftime.py', enabled=False, dumbtest=1), RegrTest('test_string.py', enabled=True, core=True), RegrTest('test_StringIO.py', enabled=True, core=True), RegrTest('test_stringprep.py', enabled=True, dumbtest=1), RegrTest('test_strop.py', enabled=False), #rev 10840: ImportError: strop RegrTest('test_strptime.py', enabled=False), #rev 10840: 1 of 42 test fails: seems to be some regex problem RegrTest('test_struct.py', enabled=False, dumbtest=1), RegrTest('test_structseq.py', enabled=False, dumbtest=1), RegrTest('test_subprocess.py', enabled=False), RegrTest('test_sunaudiodev.py', enabled=False, dumbtest=1), RegrTest('test_sundry.py', enabled=False, dumbtest=1), # test_support is not a test RegrTest('test_symtable.py', enabled=False, dumbtest=1), RegrTest('test_syntax.py', enabled=True, core=True), RegrTest('test_sys.py', enabled=True, core=True), RegrTest('test_tcl.py', enabled=False), RegrTest('test_tarfile.py', enabled=False), #rev 10840: 13 of 13 test fail RegrTest('test_tempfile.py', enabled=False), # tempfile does: class ... unlink = _os.unlink!!! #rev 10840: Uncaught interp-level exception: Same place as test_cfgparser RegrTest('test_textwrap.py', enabled=True), RegrTest('test_thread.py', enabled=True, usemodules="thread", core=True), RegrTest('test_threaded_import.py', usemodules="thread", enabled=True, core=True), RegrTest('test_threadedtempfile.py', usemodules="thread", enabled=True, core=False), # tempfile is non-core by itself #rev 10840: ImportError: thread RegrTest('test_threading.py', usemodules="thread", enabled=True, dumbtest=1, core=True), #rev 10840: ImportError: thread RegrTest('test_threading_local.py', usemodules="thread", enabled=True, dumbtest=1, core=True), RegrTest('test_threadsignals.py', usemodules="thread", enabled=False, dumbtest=1), RegrTest('test_time.py', enabled=True, core=True), RegrTest('test_timeout.py', enabled=False), #rev 10840: Uncaught interp-level exception: Same place as test_cfgparser RegrTest('test_timing.py', enabled=False, dumbtest=1), RegrTest('test_tokenize.py', enabled=False), RegrTest('test_trace.py', enabled=True, core=True), RegrTest('test_traceback.py', enabled=True, core=True), #rev 10840: 2 of 2 tests fail RegrTest('test_transformer.py', enabled=True, core=True), RegrTest('test_tuple.py', enabled=True, core=True), RegrTest('test_types.py', enabled=True, core=True), #rev 11598: one of the mod related to dict iterators is questionable # and questions whether how we implement them is meaningful in the # long run RegrTest('test_ucn.py', enabled=False), RegrTest('test_unary.py', enabled=True, core=True), RegrTest('test_unicode.py', enabled=True, core=True), RegrTest('test_unicode_file.py', enabled=False), RegrTest('test_unicodedata.py', enabled=False), RegrTest('test_unittest.py', enabled=True, core=True), RegrTest('test_univnewlines.py', enabled=True, core=True), RegrTest('test_unpack.py', enabled=True, dumbtest=1, core=True), RegrTest('test_urllib.py', enabled=True), RegrTest('test_urllib2.py', enabled=True, dumbtest=1), RegrTest('test_urllib2net.py', enabled=True), RegrTest('test_urllibnet.py', enabled=False), # try to understand failure!!! RegrTest('test_urlparse.py', enabled=True), RegrTest('test_userdict.py', enabled=True, core=True), RegrTest('test_userlist.py', enabled=True, core=True), RegrTest('test_userstring.py', enabled=True, core=True), RegrTest('test_uu.py', enabled=False), #rev 10840: 1 of 9 test fails RegrTest('test_warnings.py', enabled=True, core=True), RegrTest('test_wave.py', enabled=False, dumbtest=1), RegrTest('test_weakref.py', enabled=True, core=True, usemodules='_weakref'), RegrTest('test_whichdb.py', enabled=True), RegrTest('test_winreg.py', enabled=False), RegrTest('test_winsound.py', enabled=False), RegrTest('test_xmllib.py', enabled=False), RegrTest('test_xmlrpc.py', enabled=False), #rev 10840: 2 of 5 tests fail RegrTest('test_xpickle.py', enabled=False), RegrTest('test_xrange.py', enabled=True, core=True), RegrTest('test_zipfile.py', enabled=False, dumbtest=1), RegrTest('test_zipimport.py', enabled=True), # considered non-core because it depends on 'import zlib' # which we don't have RegrTest('test_zlib.py', enabled=False), #10840: ImportError: zlib ] class RegrDirectory(py.test.collect.Directory): """ The central hub for gathering CPython's compliance tests Basically we work off the above 'testmap' which describes for all test modules their specific type. XXX If you find errors in the classification please correct them! """ def get(self, name, cache={}): if not cache: for x in testmap: cache[x.basename] = x return cache.get(name, None) def run(self): return [x.basename for x in testmap] def join(self, name): regrtest = self.get(name) if regrtest is not None: if not option.extracttests: return RunFileExternal(name, parent=self, regrtest=regrtest) else: return InterceptedRunModule(name, self, regrtest) Directory = RegrDirectory def getrev(path): try: return py.path.svnwc(pypydir).info().rev except (KeyboardInterrupt, SystemExit): raise except: # on windows people not always have 'svn' in their path # but there are also other kinds of problems that # could occur and we just default to revision # "unknown" for them return 'unknown' def getexecutable(_cache={}): execpath = py.path.local(option.pypy_executable) if not _cache: text = execpath.sysexec('-c', 'import sys; ' 'print sys.version; ' 'print sys.pypy_svn_url; ' 'print sys.pypy_translation_info; ') lines = [line.strip() for line in text.split('\n')] assert len(lines) == 4 and lines[3] == '' assert lines[2].startswith('{') and lines[2].endswith('}') info = eval(lines[2]) info['version'] = lines[0] info['rev'] = eval(lines[1])[1] _cache.update(info) return execpath, _cache class RunFileExternal(py.test.collect.Module): def __init__(self, name, parent, regrtest): super(RunFileExternal, self).__init__(name, parent) self.regrtest = regrtest self.fspath = regrtest.getfspath() def tryiter(self, stopitems=()): # shortcut pre-counting of items return [] def run(self): if self.regrtest.ismodified(): return ['modified'] return ['unmodified'] def join(self, name): return ReallyRunFileExternal(name, parent=self) def ensuretestresultdir(): resultdir = option.resultdir default_place = False if resultdir is not None: resultdir = py.path.local(option.resultdir) else: if option.use_compiled: return None default_place = True resultdir = testresultdir if not resultdir.check(dir=1): if default_place: py.test.skip("""'testresult' directory not found. To run tests in reporting mode (without -E), you first have to check it out as follows: svn co http://codespeak.net/svn/pypy/testresult %s""" % ( testresultdir, )) else: py.test.skip("'%s' test result dir not found" % resultdir) return resultdir # # testmethod: # invoking in a seprate process: py.py TESTFILE # import os import time import socket import getpass class ReallyRunFileExternal(py.test.collect.Item): _resultcache = None def _haskeyword(self, keyword): if keyword == 'core': return self.parent.regrtest.core if keyword not in ('error', 'ok', 'timeout'): return super(ReallyRunFileExternal, self).haskeyword(keyword) if self._resultcache is None: from pypy.tool.pytest.overview import ResultCache self.__class__._resultcache = rc = ResultCache() rc.parselatest() result = self._resultcache.getlatestrelevant(self.fspath.purebasename) if not result: return False if keyword == 'timeout': return result.istimeout() if keyword == 'error': return result.iserror() if keyword == 'ok': return result.isok() assert False, "should not be there" def getinvocation(self, regrtest): fspath = regrtest.getfspath() python = sys.executable pypy_script = pypydir.join('bin', 'py.py') alarm_script = pypydir.join('tool', 'alarm.py') watchdog_script = pypydir.join('tool', 'watchdog.py') regr_script = pypydir.join('tool', 'pytest', 'run-script', 'regrverbose.py') if option.use_compiled: execpath, info = getexecutable() pypy_options = [] if regrtest.oldstyle: if (option.use_compiled and not info.get('objspace.std.oldstyle', False)): py.test.skip("old-style classes not available with this pypy-c") pypy_options.append('--oldstyle') if regrtest.compiler: pypy_options.append('--compiler=%s' % regrtest.compiler) pypy_options.extend( ['--withmod-%s' % mod for mod in regrtest.usemodules]) sopt = " ".join(pypy_options) # we use the regrverbose script to run the test, but don't get # confused: it still doesn't set verbose to True by default if # regrtest.outputpath() is true, because output tests get confused # in verbose mode. You can always force verbose mode by passing # the -v option to py.test. The regrverbose script contains the # logic that CPython uses in its regrtest.py. regrrun = str(regr_script) if not regrtest.getoutputpath() or pypy_option.verbose: regrrun_verbosity = '1' else: regrrun_verbosity = '0' TIMEOUT = gettimeout() if option.use_compiled: cmd = "%s %s %s %s" %( execpath, regrrun, regrrun_verbosity, fspath.purebasename) if sys.platform != 'win32': cmd = "%s %s %s %s" %( python, watchdog_script, TIMEOUT, cmd) else: cmd = "%s %s %d %s %s %s %s %s" %( python, alarm_script, TIMEOUT, pypy_script, sopt, regrrun, regrrun_verbosity, fspath.purebasename) return cmd def run(self): """ invoke a subprocess running the test file via PyPy. record its output into the 'result/user@host' subdirectory. (we might want to create subdirectories for each user, because we will probably all produce such result runs and they will not be the same i am afraid. """ regrtest = self.parent.regrtest result = self.getresult(regrtest) testresultdir = ensuretestresultdir() if testresultdir is not None: resultdir = testresultdir.join(result['userhost']) assert resultdir.ensure(dir=1) fn = resultdir.join(regrtest.basename).new(ext='.txt') if result.istimeout(): if fn.check(file=1): try: oldresult = ResultFromMime(fn) except TypeError: pass else: if not oldresult.istimeout(): py.test.skip("timed out, not overwriting " "more interesting non-timeout outcome") fn.write(result.repr_mimemessage().as_string(unixfrom=False)) if result['exit-status']: time.sleep(0.5) # time for a Ctrl-C to reach us :-) print >>sys.stdout, result.getnamedtext('stdout') print >>sys.stderr, result.getnamedtext('stderr') py.test.fail("running test failed, see stderr output below") def getstatusouterr(self, cmd): tempdir = py.path.local.mkdtemp() try: stdout = tempdir.join(self.fspath.basename) + '.out' stderr = tempdir.join(self.fspath.basename) + '.err' if sys.platform == 'win32': status = os.system("%s >%s 2>%s" %(cmd, stdout, stderr)) if status>=0: status = status else: status = 'abnormal termination 0x%x' % status else: status = os.system("%s >>%s 2>>%s" %(cmd, stdout, stderr)) if os.WIFEXITED(status): status = os.WEXITSTATUS(status) else: status = 'abnormal termination 0x%x' % status return status, stdout.read(mode='rU'), stderr.read(mode='rU') finally: tempdir.remove() def getresult(self, regrtest): cmd = self.getinvocation(regrtest) result = Result() fspath = regrtest.getfspath() result['fspath'] = str(fspath) result['pypy-revision'] = getrev(pypydir) if option.use_compiled: execpath, info = getexecutable() result['pypy-revision'] = info['rev'] result['executable'] = execpath.basename for key, value in info.items(): if key == 'rev': continue result['executable-%s' % key] = str(value) else: result['executable'] = 'py.py' result['options'] = regrtest.getoptions() result['timeout'] = gettimeout() result['startdate'] = time.ctime() starttime = time.time() # really run the test in a sub process exit_status, test_stdout, test_stderr = self.getstatusouterr(cmd) timedout = test_stderr.rfind(26*"=" + "timedout" + 26*"=") != -1 if not timedout: timedout = test_stderr.rfind("KeyboardInterrupt") != -1 result['execution-time'] = time.time() - starttime result.addnamedtext('stdout', test_stdout) result.addnamedtext('stderr', test_stderr) outcome = 'OK' expectedpath = regrtest.getoutputpath() if not exit_status: if expectedpath is not None: expected = expectedpath.read(mode='rU') test_stdout = "%s\n%s" % (self.fspath.purebasename, test_stdout) if test_stdout != expected: exit_status = 2 res, out, err = py.io.StdCapture.call(reportdiff, expected, test_stdout) outcome = 'ERROUT' result.addnamedtext('reportdiff', out) else: if 'FAIL' in test_stdout or 'ERROR' in test_stderr: outcome = 'FAIL' elif timedout: outcome = "T/O" else: outcome = "ERR" result['exit-status'] = exit_status result['outcome'] = outcome return result # # Sanity check (could be done more nicely too) # import os samefile = getattr(os.path, 'samefile', lambda x,y : str(x) == str(y)) if samefile(os.getcwd(), str(regrtestdir.dirpath())): raise NotImplementedError( "Cannot run py.test with this current directory:\n" "the app-level sys.path will contain %s before %s)." % ( regrtestdir.dirpath(), modregrtestdir.dirpath()))
Python
r"""Utilities to compile possibly incomplete Python source code. This module provides two interfaces, broadly similar to the builtin function compile(), which take program text, a filename and a 'mode' and: - Return code object if the command is complete and valid - Return None if the command is incomplete - Raise SyntaxError, ValueError or OverflowError if the command is a syntax error (OverflowError and ValueError can be produced by malformed literals). Approach: First, check if the source consists entirely of blank lines and comments; if so, replace it with 'pass', because the built-in parser doesn't always do the right thing for these. Compile three times: as is, with \n, and with \n\n appended. If it compiles as is, it's complete. If it compiles with one \n appended, we expect more. If it doesn't compile either way, we compare the error we get when compiling with \n or \n\n appended. If the errors are the same, the code is broken. But if the errors are different, we expect more. Not intuitive; not even guaranteed to hold in future releases; but this matches the compiler's behavior from Python 1.4 through 2.2, at least. Caveat: It is possible (but not likely) that the parser stops parsing with a successful outcome before reaching the end of the source; in this case, trailing symbols may be ignored instead of causing an error. For example, a backslash followed by two newlines may be followed by arbitrary garbage. This will be fixed once the API for the parser is better. The two interfaces are: compile_command(source, filename, symbol): Compiles a single command in the manner described above. CommandCompiler(): Instances of this class have __call__ methods identical in signature to compile_command; the difference is that if the instance compiles program text containing a __future__ statement, the instance 'remembers' and compiles all subsequent program texts with the statement in force. The module also provides another class: Compile(): Instances of this class act like the built-in function compile, but with 'memory' in the sense described above. """ import __future__ _features = [getattr(__future__, fname) for fname in __future__.all_feature_names] __all__ = ["compile_command", "Compile", "CommandCompiler"] PyCF_DONT_IMPLY_DEDENT = 0x200 # Matches pythonrun.h def _maybe_compile(compiler, source, filename, symbol): # Check for source consisting of only blank lines and comments for line in source.split("\n"): line = line.strip() if line and line[0] != '#': break # Leave it alone else: if symbol != "eval": source = "pass" # Replace it with a 'pass' statement err = err1 = err2 = None code = code1 = code2 = None try: code = compiler(source, filename, symbol) except SyntaxError, err: pass try: code1 = compiler(source + "\n", filename, symbol) except SyntaxError, err1: pass try: code2 = compiler(source + "\n\n", filename, symbol) except SyntaxError, err2: pass if code: return code try: e1 = err1.__dict__ except AttributeError: e1 = err1 try: e2 = err2.__dict__ except AttributeError: e2 = err2 if not code1 and e1 == e2: raise SyntaxError, err1 def _compile(source, filename, symbol): return compile(source, filename, symbol, PyCF_DONT_IMPLY_DEDENT) def compile_command(source, filename="<input>", symbol="single"): r"""Compile a command and determine whether it is incomplete. Arguments: source -- the source string; may contain \n characters filename -- optional filename from which source was read; default "<input>" symbol -- optional grammar start symbol; "single" (default) or "eval" Return value / exceptions raised: - Return a code object if the command is complete and valid - Return None if the command is incomplete - Raise SyntaxError, ValueError or OverflowError if the command is a syntax error (OverflowError and ValueError can be produced by malformed literals). """ return _maybe_compile(_compile, source, filename, symbol) class Compile: """Instances of this class behave much like the built-in compile function, but if one is used to compile text containing a future statement, it "remembers" and compiles all subsequent program texts with the statement in force.""" def __init__(self): self.flags = PyCF_DONT_IMPLY_DEDENT def __call__(self, source, filename, symbol): codeob = compile(source, filename, symbol, self.flags, 1) for feature in _features: if codeob.co_flags & feature.compiler_flag: self.flags |= feature.compiler_flag return codeob class CommandCompiler: """Instances of this class have __call__ methods identical in signature to compile_command; the difference is that if the instance compiles program text containing a __future__ statement, the instance 'remembers' and compiles all subsequent program texts with the statement in force.""" def __init__(self,): self.compiler = Compile() def __call__(self, source, filename="<input>", symbol="single"): r"""Compile a command and determine whether it is incomplete. Arguments: source -- the source string; may contain \n characters filename -- optional filename from which source was read; default "<input>" symbol -- optional grammar start symbol; "single" (default) or "eval" Return value / exceptions raised: - Return a code object if the command is complete and valid - Return None if the command is incomplete - Raise SyntaxError, ValueError or OverflowError if the command is a syntax error (OverflowError and ValueError can be produced by malformed literals). """ return _maybe_compile(self.compiler, source, filename, symbol)
Python
"""Simple HTTP Server. This module builds on BaseHTTPServer by implementing the standard GET and HEAD requests in a fairly straightforward manner. """ __version__ = "0.6" __all__ = ["SimpleHTTPRequestHandler"] import os import posixpath import BaseHTTPServer import urllib import cgi import shutil import mimetypes from StringIO import StringIO class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Simple HTTP request handler with GET and HEAD commands. This serves files from the current directory and any of its subdirectories. The MIME type for files is determined by calling the .guess_type() method. The GET and HEAD requests are identical except that the HEAD request omits the actual contents of the file. """ server_version = "SimpleHTTP/" + __version__ def do_GET(self): """Serve a GET request.""" f = self.send_head() if f: self.copyfile(f, self.wfile) f.close() def do_HEAD(self): """Serve a HEAD request.""" f = self.send_head() if f: f.close() def send_head(self): """Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which case the caller has nothing further to do. """ path = self.translate_path(self.path) f = None if os.path.isdir(path): for index in "index.html", "index.htm": index = os.path.join(path, index) if os.path.exists(index): path = index break else: return self.list_directory(path) ctype = self.guess_type(path) try: # Always read in binary mode. Opening files in text mode may cause # newline translations, making the actual size of the content # transmitted *less* than the content-length! f = open(path, 'rb') except IOError: self.send_error(404, "File not found") return None self.send_response(200) self.send_header("Content-type", ctype) self.send_header("Content-Length", str(os.fstat(f.fileno())[6])) self.end_headers() return f def list_directory(self, path): """Helper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head(). """ try: list = os.listdir(path) except os.error: self.send_error(404, "No permission to list directory") return None list.sort(key=lambda a: a.lower()) f = StringIO() f.write("<title>Directory listing for %s</title>\n" % self.path) f.write("<h2>Directory listing for %s</h2>\n" % self.path) f.write("<hr>\n<ul>\n") for name in list: fullname = os.path.join(path, name) displayname = linkname = name # Append / for directories or @ for symbolic links if os.path.isdir(fullname): displayname = name + "/" linkname = name + "/" if os.path.islink(fullname): displayname = name + "@" # Note: a link to a directory displays with @ and links with / f.write('<li><a href="%s">%s</a>\n' % (urllib.quote(linkname), cgi.escape(displayname))) f.write("</ul>\n<hr>\n") length = f.tell() f.seek(0) self.send_response(200) self.send_header("Content-type", "text/html") self.send_header("Content-Length", str(length)) self.end_headers() return f def translate_path(self, path): """Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.) """ path = posixpath.normpath(urllib.unquote(path)) words = path.split('/') words = filter(None, words) path = os.getcwd() for word in words: drive, word = os.path.splitdrive(word) head, word = os.path.split(word) if word in (os.curdir, os.pardir): continue path = os.path.join(path, word) return path def copyfile(self, source, outputfile): """Copy all data between two file objects. The SOURCE argument is a file object open for reading (or anything with a read() method) and the DESTINATION argument is a file object open for writing (or anything with a write() method). The only reason for overriding this would be to change the block size or perhaps to replace newlines by CRLF -- note however that this the default server uses this to copy binary data as well. """ shutil.copyfileobj(source, outputfile) def guess_type(self, path): """Guess the type of a file. Argument is a PATH (a filename). Return value is a string of the form type/subtype, usable for a MIME Content-type header. The default implementation looks the file's extension up in the table self.extensions_map, using application/octet-stream as a default; however it would be permissible (if slow) to look inside the data to make a better guess. """ base, ext = posixpath.splitext(path) if ext in self.extensions_map: return self.extensions_map[ext] ext = ext.lower() if ext in self.extensions_map: return self.extensions_map[ext] else: return self.extensions_map[''] extensions_map = mimetypes.types_map.copy() extensions_map.update({ '': 'application/octet-stream', # Default '.py': 'text/plain', '.c': 'text/plain', '.h': 'text/plain', }) def test(HandlerClass = SimpleHTTPRequestHandler, ServerClass = BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass) if __name__ == '__main__': test()
Python
"""Interpret sun audio headers.""" MAGIC = '.snd' class error(Exception): pass def get_long_be(s): """Convert a 4-char value to integer.""" return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3]) def gethdr(fp): """Read a sound header from an open file.""" if fp.read(4) != MAGIC: raise error, 'gethdr: bad magic word' hdr_size = get_long_be(fp.read(4)) data_size = get_long_be(fp.read(4)) encoding = get_long_be(fp.read(4)) sample_rate = get_long_be(fp.read(4)) channels = get_long_be(fp.read(4)) excess = hdr_size - 24 if excess < 0: raise error, 'gethdr: bad hdr_size' if excess > 0: info = fp.read(excess) else: info = '' return (data_size, encoding, sample_rate, channels, info) def printhdr(file): """Read and print the sound header of a named file.""" hdr = gethdr(open(file, 'r')) data_size, encoding, sample_rate, channels, info = hdr while info[-1:] == '\0': info = info[:-1] print 'File name: ', file print 'Data size: ', data_size print 'Encoding: ', encoding print 'Sample rate:', sample_rate print 'Channels: ', channels print 'Info: ', repr(info)
Python
import errno import hotshot import hotshot.stats import os import sys import test.pystone def main(logfile): p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() print "Pystone(%s) time for %d passes = %g" % \ (test.pystone.__version__, test.pystone.LOOPS, benchtime) print "This machine benchmarks at %g pystones/second" % stones stats = hotshot.stats.load(logfile) stats.strip_dirs() stats.sort_stats('time', 'calls') try: stats.print_stats(20) except IOError, e: if e.errno != errno.EPIPE: raise if __name__ == '__main__': if sys.argv[1:]: main(sys.argv[1]) else: import tempfile main(tempfile.NamedTemporaryFile().name)
Python
import _hotshot import os.path import parser import symbol import sys from _hotshot import \ WHAT_ENTER, \ WHAT_EXIT, \ WHAT_LINENO, \ WHAT_DEFINE_FILE, \ WHAT_DEFINE_FUNC, \ WHAT_ADD_INFO __all__ = ["LogReader", "ENTER", "EXIT", "LINE"] ENTER = WHAT_ENTER EXIT = WHAT_EXIT LINE = WHAT_LINENO class LogReader: def __init__(self, logfn): # fileno -> filename self._filemap = {} # (fileno, lineno) -> filename, funcname self._funcmap = {} self._reader = _hotshot.logreader(logfn) self._nextitem = self._reader.next self._info = self._reader.info if self._info.has_key('current-directory'): self.cwd = self._info['current-directory'] else: self.cwd = None # This mirrors the call stack of the profiled code as the log # is read back in. It contains tuples of the form: # # (file name, line number of function def, function name) # self._stack = [] self._append = self._stack.append self._pop = self._stack.pop def close(self): self._reader.close() def fileno(self): """Return the file descriptor of the log reader's log file.""" return self._reader.fileno() def addinfo(self, key, value): """This method is called for each additional ADD_INFO record. This can be overridden by applications that want to receive these events. The default implementation does not need to be called by alternate implementations. The initial set of ADD_INFO records do not pass through this mechanism; this is only needed to receive notification when new values are added. Subclasses can inspect self._info after calling LogReader.__init__(). """ pass def get_filename(self, fileno): try: return self._filemap[fileno] except KeyError: raise ValueError, "unknown fileno" def get_filenames(self): return self._filemap.values() def get_fileno(self, filename): filename = os.path.normcase(os.path.normpath(filename)) for fileno, name in self._filemap.items(): if name == filename: return fileno raise ValueError, "unknown filename" def get_funcname(self, fileno, lineno): try: return self._funcmap[(fileno, lineno)] except KeyError: raise ValueError, "unknown function location" # Iteration support: # This adds an optional (& ignored) parameter to next() so that the # same bound method can be used as the __getitem__() method -- this # avoids using an additional method call which kills the performance. def next(self, index=0): while 1: # This call may raise StopIteration: what, tdelta, fileno, lineno = self._nextitem() # handle the most common cases first if what == WHAT_ENTER: filename, funcname = self._decode_location(fileno, lineno) t = (filename, lineno, funcname) self._append(t) return what, t, tdelta if what == WHAT_EXIT: return what, self._pop(), tdelta if what == WHAT_LINENO: filename, firstlineno, funcname = self._stack[-1] return what, (filename, lineno, funcname), tdelta if what == WHAT_DEFINE_FILE: filename = os.path.normcase(os.path.normpath(tdelta)) self._filemap[fileno] = filename elif what == WHAT_DEFINE_FUNC: filename = self._filemap[fileno] self._funcmap[(fileno, lineno)] = (filename, tdelta) elif what == WHAT_ADD_INFO: # value already loaded into self.info; call the # overridable addinfo() handler so higher-level code # can pick up the new value if tdelta == 'current-directory': self.cwd = lineno self.addinfo(tdelta, lineno) else: raise ValueError, "unknown event type" def __iter__(self): return self # # helpers # def _decode_location(self, fileno, lineno): try: return self._funcmap[(fileno, lineno)] except KeyError: # # This should only be needed when the log file does not # contain all the DEFINE_FUNC records needed to allow the # function name to be retrieved from the log file. # if self._loadfile(fileno): filename = funcname = None try: filename, funcname = self._funcmap[(fileno, lineno)] except KeyError: filename = self._filemap.get(fileno) funcname = None self._funcmap[(fileno, lineno)] = (filename, funcname) return filename, funcname def _loadfile(self, fileno): try: filename = self._filemap[fileno] except KeyError: print "Could not identify fileId", fileno return 1 if filename is None: return 1 absname = os.path.normcase(os.path.join(self.cwd, filename)) try: fp = open(absname) except IOError: return st = parser.suite(fp.read()) fp.close() # Scan the tree looking for def and lambda nodes, filling in # self._funcmap with all the available information. funcdef = symbol.funcdef lambdef = symbol.lambdef stack = [st.totuple(1)] while stack: tree = stack.pop() try: sym = tree[0] except (IndexError, TypeError): continue if sym == funcdef: self._funcmap[(fileno, tree[2][2])] = filename, tree[2][1] elif sym == lambdef: self._funcmap[(fileno, tree[1][2])] = filename, "<lambda>" stack.extend(list(tree[1:]))
Python
"""High-perfomance logging profiler, mostly written in C.""" import _hotshot from _hotshot import ProfilerError class Profile: def __init__(self, logfn, lineevents=0, linetimings=1): self.lineevents = lineevents and 1 or 0 self.linetimings = (linetimings and lineevents) and 1 or 0 self._prof = p = _hotshot.profiler( logfn, self.lineevents, self.linetimings) # Attempt to avoid confusing results caused by the presence of # Python wrappers around these functions, but only if we can # be sure the methods have not been overridden or extended. if self.__class__ is Profile: self.close = p.close self.start = p.start self.stop = p.stop self.addinfo = p.addinfo def close(self): """Close the logfile and terminate the profiler.""" self._prof.close() def fileno(self): """Return the file descriptor of the profiler's log file.""" return self._prof.fileno() def start(self): """Start the profiler.""" self._prof.start() def stop(self): """Stop the profiler.""" self._prof.stop() def addinfo(self, key, value): """Add an arbitrary labelled value to the profile log.""" self._prof.addinfo(key, value) # These methods offer the same interface as the profile.Profile class, # but delegate most of the work to the C implementation underneath. def run(self, cmd): """Profile an exec-compatible string in the script environment. The globals from the __main__ module are used as both the globals and locals for the script. """ import __main__ dict = __main__.__dict__ return self.runctx(cmd, dict, dict) def runctx(self, cmd, globals, locals): """Evaluate an exec-compatible string in a specific environment. The string is compiled before profiling begins. """ code = compile(cmd, "<string>", "exec") self._prof.runcode(code, globals, locals) return self def runcall(self, func, *args, **kw): """Profile a single call of a callable. Additional positional and keyword arguments may be passed along; the result of the call is returned, and exceptions are allowed to propogate cleanly, while ensuring that profiling is disabled on the way out. """ return self._prof.runcall(func, args, kw)
Python
"""Statistics analyzer for HotShot.""" import profile import pstats import hotshot.log from hotshot.log import ENTER, EXIT def load(filename): return StatsLoader(filename).load() class StatsLoader: def __init__(self, logfn): self._logfn = logfn self._code = {} self._stack = [] self.pop_frame = self._stack.pop def load(self): # The timer selected by the profiler should never be used, so make # sure it doesn't work: p = Profile() p.get_time = _brokentimer log = hotshot.log.LogReader(self._logfn) taccum = 0 for event in log: what, (filename, lineno, funcname), tdelta = event if tdelta > 0: taccum += tdelta # We multiply taccum to convert from the microseconds we # have to the seconds that the profile/pstats module work # with; this allows the numbers to have some basis in # reality (ignoring calibration issues for now). if what == ENTER: frame = self.new_frame(filename, lineno, funcname) p.trace_dispatch_call(frame, taccum * .000001) taccum = 0 elif what == EXIT: frame = self.pop_frame() p.trace_dispatch_return(frame, taccum * .000001) taccum = 0 # no further work for line events assert not self._stack return pstats.Stats(p) def new_frame(self, *args): # args must be filename, firstlineno, funcname # our code objects are cached since we don't need to create # new ones every time try: code = self._code[args] except KeyError: code = FakeCode(*args) self._code[args] = code # frame objects are create fresh, since the back pointer will # vary considerably if self._stack: back = self._stack[-1] else: back = None frame = FakeFrame(code, back) self._stack.append(frame) return frame class Profile(profile.Profile): def simulate_cmd_complete(self): pass class FakeCode: def __init__(self, filename, firstlineno, funcname): self.co_filename = filename self.co_firstlineno = firstlineno self.co_name = self.__name__ = funcname class FakeFrame: def __init__(self, code, back): self.f_back = back self.f_code = code def _brokentimer(): raise RuntimeError, "this timer should not be called"
Python
"""Calendar printing functions Note when comparing these calendars to the ones printed by cal(1): By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention). Use setfirstweekday() to set the first day of the week (0=Monday, 6=Sunday).""" import datetime __all__ = ["error","setfirstweekday","firstweekday","isleap", "leapdays","weekday","monthrange","monthcalendar", "prmonth","month","prcal","calendar","timegm", "month_name", "month_abbr", "day_name", "day_abbr"] # Exception raised for bad input (with string parameter for details) error = ValueError # Constants for months referenced later January = 1 February = 2 # Number of days per month (except for February in leap years) mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # This module used to have hard-coded lists of day and month names, as # English strings. The classes following emulate a read-only version of # that, but supply localized names. Note that the values are computed # fresh on each call, in case the user changes locale between calls. class _localized_month: _months = [datetime.date(2001, i+1, 1).strftime for i in range(12)] _months.insert(0, lambda x: "") def __init__(self, format): self.format = format def __getitem__(self, i): funcs = self._months[i] if isinstance(i, slice): return [f(self.format) for f in funcs] else: return funcs(self.format) def __len__(self): return 13 class _localized_day: # January 1, 2001, was a Monday. _days = [datetime.date(2001, 1, i+1).strftime for i in range(7)] def __init__(self, format): self.format = format def __getitem__(self, i): funcs = self._days[i] if isinstance(i, slice): return [f(self.format) for f in funcs] else: return funcs(self.format) def __len__(self): return 7 # Full and abbreviated names of weekdays day_name = _localized_day('%A') day_abbr = _localized_day('%a') # Full and abbreviated names of months (1-based arrays!!!) month_name = _localized_month('%B') month_abbr = _localized_month('%b') # Constants for weekdays (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7) _firstweekday = 0 # 0 = Monday, 6 = Sunday def firstweekday(): return _firstweekday def setfirstweekday(weekday): """Set weekday (Monday=0, Sunday=6) to start each week.""" global _firstweekday if not MONDAY <= weekday <= SUNDAY: raise ValueError, \ 'bad weekday number; must be 0 (Monday) to 6 (Sunday)' _firstweekday = weekday def isleap(year): """Return 1 for leap years, 0 for non-leap years.""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) def leapdays(y1, y2): """Return number of leap years in range [y1, y2). Assume y1 <= y2.""" y1 -= 1 y2 -= 1 return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400) def weekday(year, month, day): """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12), day (1-31).""" return datetime.date(year, month, day).weekday() def monthrange(year, month): """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month.""" if not 1 <= month <= 12: raise ValueError, 'bad month number' day1 = weekday(year, month, 1) ndays = mdays[month] + (month == February and isleap(year)) return day1, ndays def monthcalendar(year, month): """Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero.""" day1, ndays = monthrange(year, month) rows = [] r7 = range(7) day = (_firstweekday - day1 + 6) % 7 - 5 # for leading 0's in first week while day <= ndays: row = [0, 0, 0, 0, 0, 0, 0] for i in r7: if 1 <= day <= ndays: row[i] = day day = day + 1 rows.append(row) return rows def prweek(theweek, width): """Print a single week (no newline).""" print week(theweek, width), def week(theweek, width): """Returns a single week in a string (no newline).""" days = [] for day in theweek: if day == 0: s = '' else: s = '%2i' % day # right-align single-digit days days.append(s.center(width)) return ' '.join(days) def weekheader(width): """Return a header for a week.""" if width >= 9: names = day_name else: names = day_abbr days = [] for i in range(_firstweekday, _firstweekday + 7): days.append(names[i%7][:width].center(width)) return ' '.join(days) def prmonth(theyear, themonth, w=0, l=0): """Print a month's calendar.""" print month(theyear, themonth, w, l), def month(theyear, themonth, w=0, l=0): """Return a month's calendar string (multi-line).""" w = max(2, w) l = max(1, l) s = ("%s %r" % (month_name[themonth], theyear)).center( 7 * (w + 1) - 1).rstrip() + \ '\n' * l + weekheader(w).rstrip() + '\n' * l for aweek in monthcalendar(theyear, themonth): s = s + week(aweek, w).rstrip() + '\n' * l return s[:-l] + '\n' # Spacing of month columns for 3-column year calendar _colwidth = 7*3 - 1 # Amount printed by prweek() _spacing = 6 # Number of spaces between columns def format3c(a, b, c, colwidth=_colwidth, spacing=_spacing): """Prints 3-column formatting for year calendars""" print format3cstring(a, b, c, colwidth, spacing) def format3cstring(a, b, c, colwidth=_colwidth, spacing=_spacing): """Returns a string formatted from 3 strings, centered within 3 columns.""" return (a.center(colwidth) + ' ' * spacing + b.center(colwidth) + ' ' * spacing + c.center(colwidth)) def prcal(year, w=0, l=0, c=_spacing): """Print a year's calendar.""" print calendar(year, w, l, c), def calendar(year, w=0, l=0, c=_spacing): """Returns a year's calendar as a multi-line string.""" w = max(2, w) l = max(1, l) c = max(2, c) colwidth = (w + 1) * 7 - 1 s = repr(year).center(colwidth * 3 + c * 2).rstrip() + '\n' * l header = weekheader(w) header = format3cstring(header, header, header, colwidth, c).rstrip() for q in range(January, January+12, 3): s = (s + '\n' * l + format3cstring(month_name[q], month_name[q+1], month_name[q+2], colwidth, c).rstrip() + '\n' * l + header + '\n' * l) data = [] height = 0 for amonth in range(q, q + 3): cal = monthcalendar(year, amonth) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): weeks = [] for cal in data: if i >= len(cal): weeks.append('') else: weeks.append(week(cal[i], w)) s = s + format3cstring(weeks[0], weeks[1], weeks[2], colwidth, c).rstrip() + '\n' * l return s[:-l] + '\n' EPOCH = 1970 _EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal() def timegm(tuple): """Unrelated but handy function to calculate Unix timestamp from GMT.""" year, month, day, hour, minute, second = tuple[:6] days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1 hours = days*24 + hour minutes = hours*60 + minute seconds = minutes*60 + second return seconds
Python
# !/usr/bin/env python """Guess which db package to use to open a db file.""" import os import struct import sys try: import dbm _dbmerror = dbm.error except ImportError: dbm = None # just some sort of valid exception which might be raised in the # dbm test _dbmerror = IOError def whichdb(filename): """Guess which db package to use to open a db file. Return values: - None if the database file can't be read; - empty string if the file can be read but can't be recognized - the module name (e.g. "dbm" or "gdbm") if recognized. Importing the given module may still fail, and opening the database using that module may still fail. """ # Check for dbm first -- this has a .pag and a .dir file try: f = open(filename + os.extsep + "pag", "rb") f.close() # dbm linked with gdbm on OS/2 doesn't have .dir file if not (dbm.library == "GNU gdbm" and sys.platform == "os2emx"): f = open(filename + os.extsep + "dir", "rb") f.close() return "dbm" except IOError: # some dbm emulations based on Berkeley DB generate a .db file # some do not, but they should be caught by the dbhash checks try: f = open(filename + os.extsep + "db", "rb") f.close() # guarantee we can actually open the file using dbm # kind of overkill, but since we are dealing with emulations # it seems like a prudent step if dbm is not None: d = dbm.open(filename) d.close() return "dbm" except (IOError, _dbmerror): pass # Check for dumbdbm next -- this has a .dir and a .dat file try: # First check for presence of files os.stat(filename + os.extsep + "dat") size = os.stat(filename + os.extsep + "dir").st_size # dumbdbm files with no keys are empty if size == 0: return "dumbdbm" f = open(filename + os.extsep + "dir", "rb") try: if f.read(1) in ["'", '"']: return "dumbdbm" finally: f.close() except (OSError, IOError): pass # See if the file exists, return None if not try: f = open(filename, "rb") except IOError: return None # Read the start of the file -- the magic number s16 = f.read(16) f.close() s = s16[0:4] # Return "" if not at least 4 bytes if len(s) != 4: return "" # Convert to 4-byte int in native byte order -- return "" if impossible try: (magic,) = struct.unpack("=l", s) except struct.error: return "" # Check for GNU dbm if magic == 0x13579ace: return "gdbm" # Check for old Berkeley db hash file format v2 if magic in (0x00061561, 0x61150600): return "bsddb185" # Later versions of Berkeley db hash file have a 12-byte pad in # front of the file type try: (magic,) = struct.unpack("=l", s16[-4:]) except struct.error: return "" # Check for BSD hash if magic in (0x00061561, 0x61150600): return "dbhash" # Unknown return "" if __name__ == "__main__": for filename in sys.argv[1:]: print whichdb(filename) or "UNKNOWN", filename
Python
"""Generic socket server classes. This module tries to capture the various aspects of defining a server: For socket-based servers: - address family: - AF_INET{,6}: IP (Internet Protocol) sockets (default) - AF_UNIX: Unix domain sockets - others, e.g. AF_DECNET are conceivable (see <socket.h> - socket type: - SOCK_STREAM (reliable stream, e.g. TCP) - SOCK_DGRAM (datagrams, e.g. UDP) For request-based servers (including socket-based): - client address verification before further looking at the request (This is actually a hook for any processing that needs to look at the request before anything else, e.g. logging) - how to handle multiple requests: - synchronous (one request is handled at a time) - forking (each request is handled by a new process) - threading (each request is handled by a new thread) The classes in this module favor the server type that is simplest to write: a synchronous TCP/IP server. This is bad class design, but save some typing. (There's also the issue that a deep class hierarchy slows down method lookups.) There are five classes in an inheritance diagram, four of which represent synchronous servers of four types: +------------+ | BaseServer | +------------+ | v +-----------+ +------------------+ | TCPServer |------->| UnixStreamServer | +-----------+ +------------------+ | v +-----------+ +--------------------+ | UDPServer |------->| UnixDatagramServer | +-----------+ +--------------------+ Note that UnixDatagramServer derives from UDPServer, not from UnixStreamServer -- the only difference between an IP and a Unix stream server is the address family, which is simply repeated in both unix server classes. Forking and threading versions of each type of server can be created using the ForkingServer and ThreadingServer mix-in classes. For instance, a threading UDP server class is created as follows: class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass The Mix-in class must come first, since it overrides a method defined in UDPServer! Setting the various member variables also changes the behavior of the underlying server mechanism. To implement a service, you must derive a class from BaseRequestHandler and redefine its handle() method. You can then run various versions of the service by combining one of the server classes with your request handler class. The request handler class must be different for datagram or stream services. This can be hidden by using the mix-in request handler classes StreamRequestHandler or DatagramRequestHandler. Of course, you still have to use your head! For instance, it makes no sense to use a forking server if the service contains state in memory that can be modified by requests (since the modifications in the child process would never reach the initial state kept in the parent process and passed to each child). In this case, you can use a threading server, but you will probably have to use locks to avoid two requests that come in nearly simultaneous to apply conflicting changes to the server state. On the other hand, if you are building e.g. an HTTP server, where all data is stored externally (e.g. in the file system), a synchronous class will essentially render the service "deaf" while one request is being handled -- which may be for a very long time if a client is slow to reqd all the data it has requested. Here a threading or forking server is appropriate. In some cases, it may be appropriate to process part of a request synchronously, but to finish processing in a forked child depending on the request data. This can be implemented by using a synchronous server and doing an explicit fork in the request handler class handle() method. Another approach to handling multiple simultaneous requests in an environment that supports neither threads nor fork (or where these are too expensive or inappropriate for the service) is to maintain an explicit table of partially finished requests and to use select() to decide which request to work on next (or whether to handle a new incoming request). This is particularly important for stream services where each client can potentially be connected for a long time (if threads or subprocesses cannot be used). Future work: - Standard classes for Sun RPC (which uses either UDP or TCP) - Standard mix-in classes to implement various authentication and encryption schemes - Standard framework for select-based multiplexing XXX Open problems: - What to do with out-of-band data? BaseServer: - split generic "request" functionality out into BaseServer class. Copyright (C) 2000 Luke Kenneth Casson Leighton <lkcl@samba.org> example: read entries from a SQL database (requires overriding get_request() to return a table entry from the database). entry is processed by a RequestHandlerClass. """ # Author of the BaseServer patch: Luke Kenneth Casson Leighton # XXX Warning! # There is a test suite for this module, but it cannot be run by the # standard regression test. # To run it manually, run Lib/test/test_socketserver.py. __version__ = "0.4" import socket import sys import os __all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer", "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler", "StreamRequestHandler","DatagramRequestHandler", "ThreadingMixIn", "ForkingMixIn"] if hasattr(socket, "AF_UNIX"): __all__.extend(["UnixStreamServer","UnixDatagramServer", "ThreadingUnixStreamServer", "ThreadingUnixDatagramServer"]) class BaseServer: """Base class for server classes. Methods for the caller: - __init__(server_address, RequestHandlerClass) - serve_forever() - handle_request() # if you do not use serve_forever() - fileno() -> int # for select() Methods that may be overridden: - server_bind() - server_activate() - get_request() -> request, client_address - verify_request(request, client_address) - server_close() - process_request(request, client_address) - close_request(request) - handle_error() Methods for derived classes: - finish_request(request, client_address) Class variables that may be overridden by derived classes or instances: - address_family - socket_type - allow_reuse_address Instance variables: - RequestHandlerClass - socket """ def __init__(self, server_address, RequestHandlerClass): """Constructor. May be extended, do not override.""" self.server_address = server_address self.RequestHandlerClass = RequestHandlerClass def server_activate(self): """Called by constructor to activate the server. May be overridden. """ pass def serve_forever(self): """Handle one request at a time until doomsday.""" while 1: self.handle_request() # The distinction between handling, getting, processing and # finishing a request is fairly arbitrary. Remember: # # - handle_request() is the top-level call. It calls # get_request(), verify_request() and process_request() # - get_request() is different for stream or datagram sockets # - process_request() is the place that may fork a new process # or create a new thread to finish the request # - finish_request() instantiates the request handler class; # this constructor will handle the request all by itself def handle_request(self): """Handle one request, possibly blocking.""" try: request, client_address = self.get_request() except socket.error: return if self.verify_request(request, client_address): try: self.process_request(request, client_address) except: self.handle_error(request, client_address) self.close_request(request) def verify_request(self, request, client_address): """Verify the request. May be overridden. Return True if we should proceed with this request. """ return True def process_request(self, request, client_address): """Call finish_request. Overridden by ForkingMixIn and ThreadingMixIn. """ self.finish_request(request, client_address) self.close_request(request) def server_close(self): """Called to clean-up the server. May be overridden. """ pass def finish_request(self, request, client_address): """Finish one request by instantiating RequestHandlerClass.""" self.RequestHandlerClass(request, client_address, self) def close_request(self, request): """Called to clean up an individual request.""" pass def handle_error(self, request, client_address): """Handle an error gracefully. May be overridden. The default is to print a traceback and continue. """ print '-'*40 print 'Exception happened during processing of request from', print client_address import traceback traceback.print_exc() # XXX But this goes to stderr! print '-'*40 class TCPServer(BaseServer): """Base class for various socket-based server classes. Defaults to synchronous IP stream (i.e., TCP). Methods for the caller: - __init__(server_address, RequestHandlerClass) - serve_forever() - handle_request() # if you don't use serve_forever() - fileno() -> int # for select() Methods that may be overridden: - server_bind() - server_activate() - get_request() -> request, client_address - verify_request(request, client_address) - process_request(request, client_address) - close_request(request) - handle_error() Methods for derived classes: - finish_request(request, client_address) Class variables that may be overridden by derived classes or instances: - address_family - socket_type - request_queue_size (only for stream sockets) - allow_reuse_address Instance variables: - server_address - RequestHandlerClass - socket """ address_family = socket.AF_INET socket_type = socket.SOCK_STREAM request_queue_size = 5 allow_reuse_address = False def __init__(self, server_address, RequestHandlerClass): """Constructor. May be extended, do not override.""" BaseServer.__init__(self, server_address, RequestHandlerClass) self.socket = socket.socket(self.address_family, self.socket_type) self.server_bind() self.server_activate() def server_bind(self): """Called by constructor to bind the socket. May be overridden. """ if self.allow_reuse_address: self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) def server_activate(self): """Called by constructor to activate the server. May be overridden. """ self.socket.listen(self.request_queue_size) def server_close(self): """Called to clean-up the server. May be overridden. """ self.socket.close() def fileno(self): """Return socket file number. Interface required by select(). """ return self.socket.fileno() def get_request(self): """Get the request and client address from the socket. May be overridden. """ return self.socket.accept() def close_request(self, request): """Called to clean up an individual request.""" request.close() class UDPServer(TCPServer): """UDP server class.""" allow_reuse_address = False socket_type = socket.SOCK_DGRAM max_packet_size = 8192 def get_request(self): data, client_addr = self.socket.recvfrom(self.max_packet_size) return (data, self.socket), client_addr def server_activate(self): # No need to call listen() for UDP. pass def close_request(self, request): # No need to close anything. pass class ForkingMixIn: """Mix-in class to handle each request in a new process.""" active_children = None max_children = 40 def collect_children(self): """Internal routine to wait for died children.""" while self.active_children: if len(self.active_children) < self.max_children: options = os.WNOHANG else: # If the maximum number of children are already # running, block while waiting for a child to exit options = 0 try: pid, status = os.waitpid(0, options) except os.error: pid = None if not pid: break self.active_children.remove(pid) def process_request(self, request, client_address): """Fork a new subprocess to process the request.""" self.collect_children() pid = os.fork() if pid: # Parent process if self.active_children is None: self.active_children = [] self.active_children.append(pid) self.close_request(request) return else: # Child process. # This must never return, hence os._exit()! try: self.finish_request(request, client_address) os._exit(0) except: try: self.handle_error(request, client_address) finally: os._exit(1) class ThreadingMixIn: """Mix-in class to handle each request in a new thread.""" # Decides how threads will act upon termination of the # main process daemon_threads = False def process_request_thread(self, request, client_address): """Same as in BaseServer but as a thread. In addition, exception handling is done here. """ try: self.finish_request(request, client_address) self.close_request(request) except: self.handle_error(request, client_address) self.close_request(request) def process_request(self, request, client_address): """Start a new thread to process the request.""" import threading t = threading.Thread(target = self.process_request_thread, args = (request, client_address)) if self.daemon_threads: t.setDaemon (1) t.start() class ForkingUDPServer(ForkingMixIn, UDPServer): pass class ForkingTCPServer(ForkingMixIn, TCPServer): pass class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass if hasattr(socket, 'AF_UNIX'): class UnixStreamServer(TCPServer): address_family = socket.AF_UNIX class UnixDatagramServer(UDPServer): address_family = socket.AF_UNIX class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass class BaseRequestHandler: """Base class for request handler classes. This class is instantiated for each request to be handled. The constructor sets the instance variables request, client_address and server, and then calls the handle() method. To implement a specific service, all you need to do is to derive a class which defines a handle() method. The handle() method can find the request as self.request, the client address as self.client_address, and the server (in case it needs access to per-server information) as self.server. Since a separate instance is created for each request, the handle() method can define arbitrary other instance variariables. """ def __init__(self, request, client_address, server): self.request = request self.client_address = client_address self.server = server try: self.setup() self.handle() self.finish() finally: sys.exc_traceback = None # Help garbage collection def setup(self): pass def handle(self): pass def finish(self): pass # The following two classes make it possible to use the same service # class for stream or datagram servers. # Each class sets up these instance variables: # - rfile: a file object from which receives the request is read # - wfile: a file object to which the reply is written # When the handle() method returns, wfile is flushed properly class StreamRequestHandler(BaseRequestHandler): """Define self.rfile and self.wfile for stream sockets.""" # Default buffer sizes for rfile, wfile. # We default rfile to buffered because otherwise it could be # really slow for large data (a getc() call per byte); we make # wfile unbuffered because (a) often after a write() we want to # read and we need to flush the line; (b) big writes to unbuffered # files are typically optimized by stdio even when big reads # aren't. rbufsize = -1 wbufsize = 0 def setup(self): self.connection = self.request self.rfile = self.connection.makefile('rb', self.rbufsize) self.wfile = self.connection.makefile('wb', self.wbufsize) def finish(self): if not self.wfile.closed: self.wfile.flush() self.wfile.close() self.rfile.close() class DatagramRequestHandler(BaseRequestHandler): # XXX Regrettably, I cannot get this working on Linux; # s.recvfrom() doesn't return a meaningful client address. """Define self.rfile and self.wfile for datagram sockets.""" def setup(self): import StringIO self.packet, self.socket = self.request self.rfile = StringIO.StringIO(self.packet) self.wfile = StringIO.StringIO() def finish(self): self.socket.sendto(self.wfile.getvalue(), self.client_address)
Python
#!/usr/bin/env python # portions copyright 2001, Autonomous Zones Industries, Inc., all rights... # err... reserved and offered to the public under the terms of the # Python 2.2 license. # Author: Zooko O'Whielacronx # http://zooko.com/ # mailto:zooko@zooko.com # # Copyright 2000, Mojam Media, Inc., all rights reserved. # Author: Skip Montanaro # # Copyright 1999, Bioreason, Inc., all rights reserved. # Author: Andrew Dalke # # Copyright 1995-1997, Automatrix, Inc., all rights reserved. # Author: Skip Montanaro # # Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved. # # # Permission to use, copy, modify, and distribute this Python software and # its associated documentation for any purpose without fee is hereby # granted, provided that the above copyright notice appears in all copies, # and that both that copyright notice and this permission notice appear in # supporting documentation, and that the name of neither Automatrix, # Bioreason or Mojam Media be used in advertising or publicity pertaining to # distribution of the software without specific, written prior permission. # """program/module to trace Python program or function execution Sample use, command line: trace.py -c -f counts --ignore-dir '$prefix' spam.py eggs trace.py -t --ignore-dir '$prefix' spam.py eggs trace.py --trackcalls spam.py eggs Sample use, programmatically # create a Trace object, telling it what to ignore, and whether to # do tracing or line-counting or both. trace = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0, count=1) # run the new command using the given trace trace.run('main()') # make a report, telling it where you want output r = trace.results() r.write_results(show_missing=True) """ import linecache import os import re import sys import threading import token import tokenize import types import gc try: import cPickle pickle = cPickle except ImportError: import pickle def usage(outfile): outfile.write("""Usage: %s [OPTIONS] <file> [ARGS] Meta-options: --help Display this help then exit. --version Output version information then exit. Otherwise, exactly one of the following three options must be given: -t, --trace Print each line to sys.stdout before it is executed. -c, --count Count the number of times each line is executed and write the counts to <module>.cover for each module executed, in the module's directory. See also `--coverdir', `--file', `--no-report' below. -l, --listfuncs Keep track of which functions are executed at least once and write the results to sys.stdout after the program exits. -T, --trackcalls Keep track of caller/called pairs and write the results to sys.stdout after the program exits. -r, --report Generate a report from a counts file; do not execute any code. `--file' must specify the results file to read, which must have been created in a previous run with `--count --file=FILE'. Modifiers: -f, --file=<file> File to accumulate counts over several runs. -R, --no-report Do not generate the coverage report files. Useful if you want to accumulate over several runs. -C, --coverdir=<dir> Directory where the report files. The coverage report for <package>.<module> is written to file <dir>/<package>/<module>.cover. -m, --missing Annotate executable lines that were not executed with '>>>>>> '. -s, --summary Write a brief summary on stdout for each file. (Can only be used with --count or --report.) Filters, may be repeated multiple times: --ignore-module=<mod> Ignore the given module and its submodules (if it is a package). --ignore-dir=<dir> Ignore files in the given directory (multiple directories can be joined by os.pathsep). """ % sys.argv[0]) PRAGMA_NOCOVER = "#pragma NO COVER" # Simple rx to find lines with no code. rx_blank = re.compile(r'^\s*(#.*)?$') class Ignore: def __init__(self, modules = None, dirs = None): self._mods = modules or [] self._dirs = dirs or [] self._dirs = map(os.path.normpath, self._dirs) self._ignore = { '<string>': 1 } def names(self, filename, modulename): if self._ignore.has_key(modulename): return self._ignore[modulename] # haven't seen this one before, so see if the module name is # on the ignore list. Need to take some care since ignoring # "cmp" musn't mean ignoring "cmpcache" but ignoring # "Spam" must also mean ignoring "Spam.Eggs". for mod in self._mods: if mod == modulename: # Identical names, so ignore self._ignore[modulename] = 1 return 1 # check if the module is a proper submodule of something on # the ignore list n = len(mod) # (will not overflow since if the first n characters are the # same and the name has not already occured, then the size # of "name" is greater than that of "mod") if mod == modulename[:n] and modulename[n] == '.': self._ignore[modulename] = 1 return 1 # Now check that __file__ isn't in one of the directories if filename is None: # must be a built-in, so we must ignore self._ignore[modulename] = 1 return 1 # Ignore a file when it contains one of the ignorable paths for d in self._dirs: # The '+ os.sep' is to ensure that d is a parent directory, # as compared to cases like: # d = "/usr/local" # filename = "/usr/local.py" # or # d = "/usr/local.py" # filename = "/usr/local.py" if filename.startswith(d + os.sep): self._ignore[modulename] = 1 return 1 # Tried the different ways, so we don't ignore this module self._ignore[modulename] = 0 return 0 def modname(path): """Return a plausible module name for the patch.""" base = os.path.basename(path) filename, ext = os.path.splitext(base) return filename def fullmodname(path): """Return a plausible module name for the path.""" # If the file 'path' is part of a package, then the filename isn't # enough to uniquely identify it. Try to do the right thing by # looking in sys.path for the longest matching prefix. We'll # assume that the rest is the package name. longest = "" for dir in sys.path: if path.startswith(dir) and path[len(dir)] == os.path.sep: if len(dir) > len(longest): longest = dir if longest: base = path[len(longest) + 1:] else: base = path base = base.replace(os.sep, ".") if os.altsep: base = base.replace(os.altsep, ".") filename, ext = os.path.splitext(base) return filename class CoverageResults: def __init__(self, counts=None, calledfuncs=None, infile=None, callers=None, outfile=None): self.counts = counts if self.counts is None: self.counts = {} self.counter = self.counts.copy() # map (filename, lineno) to count self.calledfuncs = calledfuncs if self.calledfuncs is None: self.calledfuncs = {} self.calledfuncs = self.calledfuncs.copy() self.callers = callers if self.callers is None: self.callers = {} self.callers = self.callers.copy() self.infile = infile self.outfile = outfile if self.infile: # Try to merge existing counts file. try: counts, calledfuncs, callers = \ pickle.load(open(self.infile, 'rb')) self.update(self.__class__(counts, calledfuncs, callers)) except (IOError, EOFError, ValueError), err: print >> sys.stderr, ("Skipping counts file %r: %s" % (self.infile, err)) def update(self, other): """Merge in the data from another CoverageResults""" counts = self.counts calledfuncs = self.calledfuncs callers = self.callers other_counts = other.counts other_calledfuncs = other.calledfuncs other_callers = other.callers for key in other_counts.keys(): counts[key] = counts.get(key, 0) + other_counts[key] for key in other_calledfuncs.keys(): calledfuncs[key] = 1 for key in other_callers.keys(): callers[key] = 1 def write_results(self, show_missing=True, summary=False, coverdir=None): """ @param coverdir """ if self.calledfuncs: print print "functions called:" calls = self.calledfuncs.keys() calls.sort() for filename, modulename, funcname in calls: print ("filename: %s, modulename: %s, funcname: %s" % (filename, modulename, funcname)) if self.callers: print print "calling relationships:" calls = self.callers.keys() calls.sort() lastfile = lastcfile = "" for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in calls: if pfile != lastfile: print print "***", pfile, "***" lastfile = pfile lastcfile = "" if cfile != pfile and lastcfile != cfile: print " -->", cfile lastcfile = cfile print " %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc) # turn the counts data ("(filename, lineno) = count") into something # accessible on a per-file basis per_file = {} for filename, lineno in self.counts.keys(): lines_hit = per_file[filename] = per_file.get(filename, {}) lines_hit[lineno] = self.counts[(filename, lineno)] # accumulate summary info, if needed sums = {} for filename, count in per_file.iteritems(): # skip some "files" we don't care about... if filename == "<string>": continue if filename.endswith(".pyc") or filename.endswith(".pyo"): filename = filename[:-1] if coverdir is None: dir = os.path.dirname(os.path.abspath(filename)) modulename = modname(filename) else: dir = coverdir if not os.path.exists(dir): os.makedirs(dir) modulename = fullmodname(filename) # If desired, get a list of the line numbers which represent # executable content (returned as a dict for better lookup speed) if show_missing: lnotab = find_executable_linenos(filename) else: lnotab = {} source = linecache.getlines(filename) coverpath = os.path.join(dir, modulename + ".cover") n_hits, n_lines = self.write_results_file(coverpath, source, lnotab, count) if summary and n_lines: percent = int(100 * n_hits / n_lines) sums[modulename] = n_lines, percent, modulename, filename if summary and sums: mods = sums.keys() mods.sort() print "lines cov% module (path)" for m in mods: n_lines, percent, modulename, filename = sums[m] print "%5d %3d%% %s (%s)" % sums[m] if self.outfile: # try and store counts and module info into self.outfile try: pickle.dump((self.counts, self.calledfuncs, self.callers), open(self.outfile, 'wb'), 1) except IOError, err: print >> sys.stderr, "Can't save counts files because %s" % err def write_results_file(self, path, lines, lnotab, lines_hit): """Return a coverage results file in path.""" try: outfile = open(path, "w") except IOError, err: print >> sys.stderr, ("trace: Could not open %r for writing: %s" "- skipping" % (path, err)) return 0, 0 n_lines = 0 n_hits = 0 for i, line in enumerate(lines): lineno = i + 1 # do the blank/comment match to try to mark more lines # (help the reader find stuff that hasn't been covered) if lineno in lines_hit: outfile.write("%5d: " % lines_hit[lineno]) n_hits += 1 n_lines += 1 elif rx_blank.match(line): outfile.write(" ") else: # lines preceded by no marks weren't hit # Highlight them if so indicated, unless the line contains # #pragma: NO COVER if lineno in lnotab and not PRAGMA_NOCOVER in lines[i]: outfile.write(">>>>>> ") n_lines += 1 else: outfile.write(" ") outfile.write(lines[i].expandtabs(8)) outfile.close() return n_hits, n_lines def find_lines_from_code(code, strs): """Return dict where keys are lines in the line number table.""" linenos = {} line_increments = [ord(c) for c in code.co_lnotab[1::2]] table_length = len(line_increments) docstring = False lineno = code.co_firstlineno for li in line_increments: lineno += li if lineno not in strs: linenos[lineno] = 1 return linenos def find_lines(code, strs): """Return lineno dict for all code objects reachable from code.""" # get all of the lineno information from the code of this scope level linenos = find_lines_from_code(code, strs) # and check the constants for references to other code objects for c in code.co_consts: if isinstance(c, types.CodeType): # find another code object, so recurse into it linenos.update(find_lines(c, strs)) return linenos def find_strings(filename): """Return a dict of possible docstring positions. The dict maps line numbers to strings. There is an entry for line that contains only a string or a part of a triple-quoted string. """ d = {} # If the first token is a string, then it's the module docstring. # Add this special case so that the test in the loop passes. prev_ttype = token.INDENT f = open(filename) for ttype, tstr, start, end, line in tokenize.generate_tokens(f.readline): if ttype == token.STRING: if prev_ttype == token.INDENT: sline, scol = start eline, ecol = end for i in range(sline, eline + 1): d[i] = 1 prev_ttype = ttype f.close() return d def find_executable_linenos(filename): """Return dict where keys are line numbers in the line number table.""" try: prog = open(filename, "rU").read() except IOError, err: print >> sys.stderr, ("Not printing coverage data for %r: %s" % (filename, err)) return {} code = compile(prog, filename, "exec") strs = find_strings(filename) return find_lines(code, strs) class Trace: def __init__(self, count=1, trace=1, countfuncs=0, countcallers=0, ignoremods=(), ignoredirs=(), infile=None, outfile=None): """ @param count true iff it should count number of times each line is executed @param trace true iff it should print out each line that is being counted @param countfuncs true iff it should just output a list of (filename, modulename, funcname,) for functions that were called at least once; This overrides `count' and `trace' @param ignoremods a list of the names of modules to ignore @param ignoredirs a list of the names of directories to ignore all of the (recursive) contents of @param infile file from which to read stored counts to be added into the results @param outfile file in which to write the results """ self.infile = infile self.outfile = outfile self.ignore = Ignore(ignoremods, ignoredirs) self.counts = {} # keys are (filename, linenumber) self.blabbed = {} # for debugging self.pathtobasename = {} # for memoizing os.path.basename self.donothing = 0 self.trace = trace self._calledfuncs = {} self._callers = {} self._caller_cache = {} if countcallers: self.globaltrace = self.globaltrace_trackcallers elif countfuncs: self.globaltrace = self.globaltrace_countfuncs elif trace and count: self.globaltrace = self.globaltrace_lt self.localtrace = self.localtrace_trace_and_count elif trace: self.globaltrace = self.globaltrace_lt self.localtrace = self.localtrace_trace elif count: self.globaltrace = self.globaltrace_lt self.localtrace = self.localtrace_count else: # Ahem -- do nothing? Okay. self.donothing = 1 def run(self, cmd): import __main__ dict = __main__.__dict__ if not self.donothing: sys.settrace(self.globaltrace) threading.settrace(self.globaltrace) try: exec cmd in dict, dict finally: if not self.donothing: sys.settrace(None) threading.settrace(None) def runctx(self, cmd, globals=None, locals=None): if globals is None: globals = {} if locals is None: locals = {} if not self.donothing: sys.settrace(self.globaltrace) threading.settrace(self.globaltrace) try: exec cmd in globals, locals finally: if not self.donothing: sys.settrace(None) threading.settrace(None) def runfunc(self, func, *args, **kw): result = None if not self.donothing: sys.settrace(self.globaltrace) try: result = func(*args, **kw) finally: if not self.donothing: sys.settrace(None) return result def file_module_function_of(self, frame): code = frame.f_code filename = code.co_filename if filename: modulename = modname(filename) else: modulename = None funcname = code.co_name clsname = None if code in self._caller_cache: if self._caller_cache[code] is not None: clsname = self._caller_cache[code] else: self._caller_cache[code] = None ## use of gc.get_referrers() was suggested by Michael Hudson # all functions which refer to this code object funcs = [f for f in gc.get_referrers(code) if hasattr(f, "func_doc")] # require len(func) == 1 to avoid ambiguity caused by calls to # new.function(): "In the face of ambiguity, refuse the # temptation to guess." if len(funcs) == 1: dicts = [d for d in gc.get_referrers(funcs[0]) if isinstance(d, dict)] if len(dicts) == 1: classes = [c for c in gc.get_referrers(dicts[0]) if hasattr(c, "__bases__")] if len(classes) == 1: # ditto for new.classobj() clsname = str(classes[0]) # cache the result - assumption is that new.* is # not called later to disturb this relationship # _caller_cache could be flushed if functions in # the new module get called. self._caller_cache[code] = clsname if clsname is not None: # final hack - module name shows up in str(cls), but we've already # computed module name, so remove it clsname = clsname.split(".")[1:] clsname = ".".join(clsname) funcname = "%s.%s" % (clsname, funcname) return filename, modulename, funcname def globaltrace_trackcallers(self, frame, why, arg): """Handler for call events. Adds information about who called who to the self._callers dict. """ if why == 'call': # XXX Should do a better job of identifying methods this_func = self.file_module_function_of(frame) parent_func = self.file_module_function_of(frame.f_back) self._callers[(parent_func, this_func)] = 1 def globaltrace_countfuncs(self, frame, why, arg): """Handler for call events. Adds (filename, modulename, funcname) to the self._calledfuncs dict. """ if why == 'call': this_func = self.file_module_function_of(frame) self._calledfuncs[this_func] = 1 def globaltrace_lt(self, frame, why, arg): """Handler for call events. If the code block being entered is to be ignored, returns `None', else returns self.localtrace. """ if why == 'call': code = frame.f_code filename = code.co_filename if filename: # XXX modname() doesn't work right for packages, so # the ignore support won't work right for packages modulename = modname(filename) if modulename is not None: ignore_it = self.ignore.names(filename, modulename) if not ignore_it: if self.trace: print (" --- modulename: %s, funcname: %s" % (modulename, code.co_name)) return self.localtrace else: return None def localtrace_trace_and_count(self, frame, why, arg): if why == "line": # record the file name and line number of every trace filename = frame.f_code.co_filename lineno = frame.f_lineno key = filename, lineno self.counts[key] = self.counts.get(key, 0) + 1 bname = os.path.basename(filename) print "%s(%d): %s" % (bname, lineno, linecache.getline(filename, lineno)), return self.localtrace def localtrace_trace(self, frame, why, arg): if why == "line": # record the file name and line number of every trace filename = frame.f_code.co_filename lineno = frame.f_lineno bname = os.path.basename(filename) print "%s(%d): %s" % (bname, lineno, linecache.getline(filename, lineno)), return self.localtrace def localtrace_count(self, frame, why, arg): if why == "line": filename = frame.f_code.co_filename lineno = frame.f_lineno key = filename, lineno self.counts[key] = self.counts.get(key, 0) + 1 return self.localtrace def results(self): return CoverageResults(self.counts, infile=self.infile, outfile=self.outfile, calledfuncs=self._calledfuncs, callers=self._callers) def _err_exit(msg): sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) sys.exit(1) def main(argv=None): import getopt if argv is None: argv = sys.argv try: opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lT", ["help", "version", "trace", "count", "report", "no-report", "summary", "file=", "missing", "ignore-module=", "ignore-dir=", "coverdir=", "listfuncs", "trackcalls"]) except getopt.error, msg: sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) sys.stderr.write("Try `%s --help' for more information\n" % sys.argv[0]) sys.exit(1) trace = 0 count = 0 report = 0 no_report = 0 counts_file = None missing = 0 ignore_modules = [] ignore_dirs = [] coverdir = None summary = 0 listfuncs = False countcallers = False for opt, val in opts: if opt == "--help": usage(sys.stdout) sys.exit(0) if opt == "--version": sys.stdout.write("trace 2.0\n") sys.exit(0) if opt == "-T" or opt == "--trackcalls": countcallers = True continue if opt == "-l" or opt == "--listfuncs": listfuncs = True continue if opt == "-t" or opt == "--trace": trace = 1 continue if opt == "-c" or opt == "--count": count = 1 continue if opt == "-r" or opt == "--report": report = 1 continue if opt == "-R" or opt == "--no-report": no_report = 1 continue if opt == "-f" or opt == "--file": counts_file = val continue if opt == "-m" or opt == "--missing": missing = 1 continue if opt == "-C" or opt == "--coverdir": coverdir = val continue if opt == "-s" or opt == "--summary": summary = 1 continue if opt == "--ignore-module": ignore_modules.append(val) continue if opt == "--ignore-dir": for s in val.split(os.pathsep): s = os.path.expandvars(s) # should I also call expanduser? (after all, could use $HOME) s = s.replace("$prefix", os.path.join(sys.prefix, "lib", "python" + sys.version[:3])) s = s.replace("$exec_prefix", os.path.join(sys.exec_prefix, "lib", "python" + sys.version[:3])) s = os.path.normpath(s) ignore_dirs.append(s) continue assert 0, "Should never get here" if listfuncs and (count or trace): _err_exit("cannot specify both --listfuncs and (--trace or --count)") if not (count or trace or report or listfuncs or countcallers): _err_exit("must specify one of --trace, --count, --report, " "--listfuncs, or --trackcalls") if report and no_report: _err_exit("cannot specify both --report and --no-report") if report and not counts_file: _err_exit("--report requires a --file") if no_report and len(prog_argv) == 0: _err_exit("missing name of file to run") # everything is ready if report: results = CoverageResults(infile=counts_file, outfile=counts_file) results.write_results(missing, summary=summary, coverdir=coverdir) else: sys.argv = prog_argv progname = prog_argv[0] sys.path[0] = os.path.split(progname)[0] t = Trace(count, trace, countfuncs=listfuncs, countcallers=countcallers, ignoremods=ignore_modules, ignoredirs=ignore_dirs, infile=counts_file, outfile=counts_file) try: t.run('execfile(%r)' % (progname,)) except IOError, err: _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err)) except SystemExit: pass results = t.results() if not no_report: results.write_results(missing, summary=summary, coverdir=coverdir) if __name__=='__main__': main()
Python
"""Spawn a command with pipes to its stdin, stdout, and optionally stderr. The normal os.popen(cmd, mode) call spawns a shell command and provides a file interface to just the input or output of the process depending on whether mode is 'r' or 'w'. This module provides the functions popen2(cmd) and popen3(cmd) which return two or three pipes to the spawned command. """ import os import sys __all__ = ["popen2", "popen3", "popen4"] try: MAXFD = os.sysconf('SC_OPEN_MAX') except (AttributeError, ValueError): MAXFD = 256 _active = [] def _cleanup(): for inst in _active[:]: inst.poll() class Popen3: """Class representing a child process. Normally instances are created by the factory functions popen2() and popen3().""" sts = -1 # Child not completed yet def __init__(self, cmd, capturestderr=False, bufsize=-1): """The parameter 'cmd' is the shell command to execute in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). The 'capturestderr' flag, if true, specifies that the object should capture standard error output of the child process. The default is false. If the 'bufsize' parameter is specified, it specifies the size of the I/O buffers to/from the child process.""" _cleanup() p2cread, p2cwrite = os.pipe() c2pread, c2pwrite = os.pipe() if capturestderr: errout, errin = os.pipe() self.pid = os.fork() if self.pid == 0: # Child os.dup2(p2cread, 0) os.dup2(c2pwrite, 1) if capturestderr: os.dup2(errin, 2) self._run_child(cmd) os.close(p2cread) self.tochild = os.fdopen(p2cwrite, 'w', bufsize) os.close(c2pwrite) self.fromchild = os.fdopen(c2pread, 'r', bufsize) if capturestderr: os.close(errin) self.childerr = os.fdopen(errout, 'r', bufsize) else: self.childerr = None _active.append(self) def _run_child(self, cmd): if isinstance(cmd, basestring): cmd = ['/bin/sh', '-c', cmd] for i in range(3, MAXFD): try: os.close(i) except OSError: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1) def poll(self): """Return the exit status of the child process if it has finished, or -1 if it hasn't finished yet.""" if self.sts < 0: try: pid, sts = os.waitpid(self.pid, os.WNOHANG) if pid == self.pid: self.sts = sts _active.remove(self) except os.error: pass return self.sts def wait(self): """Wait for and return the exit status of the child process.""" if self.sts < 0: pid, sts = os.waitpid(self.pid, 0) if pid == self.pid: self.sts = sts _active.remove(self) return self.sts class Popen4(Popen3): childerr = None def __init__(self, cmd, bufsize=-1): _cleanup() p2cread, p2cwrite = os.pipe() c2pread, c2pwrite = os.pipe() self.pid = os.fork() if self.pid == 0: # Child os.dup2(p2cread, 0) os.dup2(c2pwrite, 1) os.dup2(c2pwrite, 2) self._run_child(cmd) os.close(p2cread) self.tochild = os.fdopen(p2cwrite, 'w', bufsize) os.close(c2pwrite) self.fromchild = os.fdopen(c2pread, 'r', bufsize) _active.append(self) if sys.platform[:3] == "win" or sys.platform == "os2emx": # Some things don't make sense on non-Unix platforms. del Popen3, Popen4 def popen2(cmd, bufsize=-1, mode='t'): """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin) are returned.""" w, r = os.popen2(cmd, mode, bufsize) return r, w def popen3(cmd, bufsize=-1, mode='t'): """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin, child_stderr) are returned.""" w, r, e = os.popen3(cmd, mode, bufsize) return r, w, e def popen4(cmd, bufsize=-1, mode='t'): """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout_stderr, child_stdin) are returned.""" w, r = os.popen4(cmd, mode, bufsize) return r, w else: def popen2(cmd, bufsize=-1, mode='t'): """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin) are returned.""" inst = Popen3(cmd, False, bufsize) return inst.fromchild, inst.tochild def popen3(cmd, bufsize=-1, mode='t'): """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin, child_stderr) are returned.""" inst = Popen3(cmd, True, bufsize) return inst.fromchild, inst.tochild, inst.childerr def popen4(cmd, bufsize=-1, mode='t'): """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout_stderr, child_stdin) are returned.""" inst = Popen4(cmd, bufsize) return inst.fromchild, inst.tochild __all__.extend(["Popen3", "Popen4"]) def _test(): cmd = "cat" teststr = "ab cd\n" if os.name == "nt": cmd = "more" # "more" doesn't act the same way across Windows flavors, # sometimes adding an extra newline at the start or the # end. So we strip whitespace off both ends for comparison. expected = teststr.strip() print "testing popen2..." r, w = popen2(cmd) w.write(teststr) w.close() got = r.read() if got.strip() != expected: raise ValueError("wrote %r read %r" % (teststr, got)) print "testing popen3..." try: r, w, e = popen3([cmd]) except: r, w, e = popen3(cmd) w.write(teststr) w.close() got = r.read() if got.strip() != expected: raise ValueError("wrote %r read %r" % (teststr, got)) got = e.read() if got: raise ValueError("unexpected %r on stderr" % (got,)) for inst in _active[:]: inst.wait() if _active: raise ValueError("_active not empty") print "All OK" if __name__ == '__main__': _test()
Python
"""An FTP client class and some helper functions. Based on RFC 959: File Transfer Protocol (FTP), by J. Postel and J. Reynolds Example: >>> from ftplib import FTP >>> ftp = FTP('ftp.python.org') # connect to host, default port >>> ftp.login() # default, i.e.: user anonymous, passwd anonymous@ '230 Guest login ok, access restrictions apply.' >>> ftp.retrlines('LIST') # list directory contents total 9 drwxr-xr-x 8 root wheel 1024 Jan 3 1994 . drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .. drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr -rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg '226 Transfer complete.' >>> ftp.quit() '221 Goodbye.' >>> A nice test that reveals some of the network dialogue would be: python ftplib.py -d localhost -l -p -l """ # # Changes and improvements suggested by Steve Majewski. # Modified by Jack to work on the mac. # Modified by Siebren to support docstrings and PASV. # import os import sys # Import SOCKS module if it exists, else standard socket module socket try: import SOCKS; socket = SOCKS; del SOCKS # import SOCKS as socket from socket import getfqdn; socket.getfqdn = getfqdn; del getfqdn except ImportError: import socket __all__ = ["FTP","Netrc"] # Magic number from <socket.h> MSG_OOB = 0x1 # Process data out of band # The standard FTP server control port FTP_PORT = 21 # Exception raised when an error or invalid response is received class Error(Exception): pass class error_reply(Error): pass # unexpected [123]xx reply class error_temp(Error): pass # 4xx errors class error_perm(Error): pass # 5xx errors class error_proto(Error): pass # response does not begin with [1-5] # All exceptions (hopefully) that may be raised here and that aren't # (always) programming errors on our side all_errors = (Error, socket.error, IOError, EOFError) # Line terminators (we always output CRLF, but accept any of CRLF, CR, LF) CRLF = '\r\n' # The class itself class FTP: '''An FTP client class. To create a connection, call the class using these argument: host, user, passwd, acct These are all strings, and have default value ''. Then use self.connect() with optional host and port argument. To download a file, use ftp.retrlines('RETR ' + filename), or ftp.retrbinary() with slightly different arguments. To upload a file, use ftp.storlines() or ftp.storbinary(), which have an open file as argument (see their definitions below for details). The download/upload functions first issue appropriate TYPE and PORT or PASV commands. ''' debugging = 0 host = '' port = FTP_PORT sock = None file = None welcome = None passiveserver = 1 # Initialization method (called by class instantiation). # Initialize host to localhost, port to standard ftp port # Optional arguments are host (for connect()), # and user, passwd, acct (for login()) def __init__(self, host='', user='', passwd='', acct=''): if host: self.connect(host) if user: self.login(user, passwd, acct) def connect(self, host = '', port = 0): '''Connect to host. Arguments are: - host: hostname to connect to (string, default previous host) - port: port to connect to (integer, default previous port)''' if host: self.host = host if port: self.port = port msg = "getaddrinfo returns an empty list" for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) except socket.error, msg: if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg self.af = af self.file = self.sock.makefile('rb') self.welcome = self.getresp() return self.welcome def getwelcome(self): '''Get the welcome message from the server. (this is read and squirreled away by connect())''' if self.debugging: print '*welcome*', self.sanitize(self.welcome) return self.welcome def set_debuglevel(self, level): '''Set the debugging level. The required argument level means: 0: no debugging output (default) 1: print commands and responses but not body text etc. 2: also print raw lines read and sent before stripping CR/LF''' self.debugging = level debug = set_debuglevel def set_pasv(self, val): '''Use passive or active mode for data transfers. With a false argument, use the normal PORT mode, With a true argument, use the PASV command.''' self.passiveserver = val # Internal: "sanitize" a string for printing def sanitize(self, s): if s[:5] == 'pass ' or s[:5] == 'PASS ': i = len(s) while i > 5 and s[i-1] in '\r\n': i = i-1 s = s[:5] + '*'*(i-5) + s[i:] return repr(s) # Internal: send one line to the server, appending CRLF def putline(self, line): line = line + CRLF if self.debugging > 1: print '*put*', self.sanitize(line) self.sock.sendall(line) # Internal: send one command to the server (through putline()) def putcmd(self, line): if self.debugging: print '*cmd*', self.sanitize(line) self.putline(line) # Internal: return one line from the server, stripping CRLF. # Raise EOFError if the connection is closed def getline(self): line = self.file.readline() if self.debugging > 1: print '*get*', self.sanitize(line) if not line: raise EOFError if line[-2:] == CRLF: line = line[:-2] elif line[-1:] in CRLF: line = line[:-1] return line # Internal: get a response from the server, which may possibly # consist of multiple lines. Return a single string with no # trailing CRLF. If the response consists of multiple lines, # these are separated by '\n' characters in the string def getmultiline(self): line = self.getline() if line[3:4] == '-': code = line[:3] while 1: nextline = self.getline() line = line + ('\n' + nextline) if nextline[:3] == code and \ nextline[3:4] != '-': break return line # Internal: get a response from the server. # Raise various errors if the response indicates an error def getresp(self): resp = self.getmultiline() if self.debugging: print '*resp*', self.sanitize(resp) self.lastresp = resp[:3] c = resp[:1] if c == '4': raise error_temp, resp if c == '5': raise error_perm, resp if c not in '123': raise error_proto, resp return resp def voidresp(self): """Expect a response beginning with '2'.""" resp = self.getresp() if resp[0] != '2': raise error_reply, resp return resp def abort(self): '''Abort a file transfer. Uses out-of-band data. This does not follow the procedure from the RFC to send Telnet IP and Synch; that doesn't seem to work with the servers I've tried. Instead, just send the ABOR command as OOB data.''' line = 'ABOR' + CRLF if self.debugging > 1: print '*put urgent*', self.sanitize(line) self.sock.sendall(line, MSG_OOB) resp = self.getmultiline() if resp[:3] not in ('426', '226'): raise error_proto, resp def sendcmd(self, cmd): '''Send a command and return the response.''' self.putcmd(cmd) return self.getresp() def voidcmd(self, cmd): """Send a command and expect a response beginning with '2'.""" self.putcmd(cmd) return self.voidresp() def sendport(self, host, port): '''Send a PORT command with the current host and the given port number. ''' hbytes = host.split('.') pbytes = [repr(port/256), repr(port%256)] bytes = hbytes + pbytes cmd = 'PORT ' + ','.join(bytes) return self.voidcmd(cmd) def sendeprt(self, host, port): '''Send a EPRT command with the current host and the given port number.''' af = 0 if self.af == socket.AF_INET: af = 1 if self.af == socket.AF_INET6: af = 2 if af == 0: raise error_proto, 'unsupported address family' fields = ['', repr(af), host, repr(port), ''] cmd = 'EPRT ' + '|'.join(fields) return self.voidcmd(cmd) def makeport(self): '''Create a new socket and send a PORT command for it.''' msg = "getaddrinfo returns an empty list" sock = None for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE): af, socktype, proto, canonname, sa = res try: sock = socket.socket(af, socktype, proto) sock.bind(sa) except socket.error, msg: if sock: sock.close() sock = None continue break if not sock: raise socket.error, msg sock.listen(1) port = sock.getsockname()[1] # Get proper port host = self.sock.getsockname()[0] # Get proper host if self.af == socket.AF_INET: resp = self.sendport(host, port) else: resp = self.sendeprt(host, port) return sock def makepasv(self): if self.af == socket.AF_INET: host, port = parse227(self.sendcmd('PASV')) else: host, port = parse229(self.sendcmd('EPSV'), self.sock.getpeername()) return host, port def ntransfercmd(self, cmd, rest=None): """Initiate a transfer over the data connection. If the transfer is active, send a port command and the transfer command, and accept the connection. If the server is passive, send a pasv command, connect to it, and start the transfer command. Either way, return the socket for the connection and the expected size of the transfer. The expected size may be None if it could not be determined. Optional `rest' argument can be a string that is sent as the argument to a RESTART command. This is essentially a server marker used to tell the server to skip over any data up to the given marker. """ size = None if self.passiveserver: host, port = self.makepasv() af, socktype, proto, canon, sa = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0] conn = socket.socket(af, socktype, proto) conn.connect(sa) if rest is not None: self.sendcmd("REST %s" % rest) resp = self.sendcmd(cmd) if resp[0] != '1': raise error_reply, resp else: sock = self.makeport() if rest is not None: self.sendcmd("REST %s" % rest) resp = self.sendcmd(cmd) if resp[0] != '1': raise error_reply, resp conn, sockaddr = sock.accept() if resp[:3] == '150': # this is conditional in case we received a 125 size = parse150(resp) return conn, size def transfercmd(self, cmd, rest=None): """Like ntransfercmd() but returns only the socket.""" return self.ntransfercmd(cmd, rest)[0] def login(self, user = '', passwd = '', acct = ''): '''Login, default anonymous.''' if not user: user = 'anonymous' if not passwd: passwd = '' if not acct: acct = '' if user == 'anonymous' and passwd in ('', '-'): # If there is no anonymous ftp password specified # then we'll just use anonymous@ # We don't send any other thing because: # - We want to remain anonymous # - We want to stop SPAM # - We don't want to let ftp sites to discriminate by the user, # host or country. passwd = passwd + 'anonymous@' resp = self.sendcmd('USER ' + user) if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd) if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct) if resp[0] != '2': raise error_reply, resp return resp def retrbinary(self, cmd, callback, blocksize=8192, rest=None): """Retrieve data in binary mode. `cmd' is a RETR command. `callback' is a callback function is called for each block. No more than `blocksize' number of bytes will be read from the socket. Optional `rest' is passed to transfercmd(). A new port is created for you. Return the response code. """ self.voidcmd('TYPE I') conn = self.transfercmd(cmd, rest) while 1: data = conn.recv(blocksize) if not data: break callback(data) conn.close() return self.voidresp() def retrlines(self, cmd, callback = None): '''Retrieve data in line mode. The argument is a RETR or LIST command. The callback function (2nd argument) is called for each line, with trailing CRLF stripped. This creates a new port for you. print_line() is the default callback.''' if callback is None: callback = print_line resp = self.sendcmd('TYPE A') conn = self.transfercmd(cmd) fp = conn.makefile('rb') while 1: line = fp.readline() if self.debugging > 2: print '*retr*', repr(line) if not line: break if line[-2:] == CRLF: line = line[:-2] elif line[-1:] == '\n': line = line[:-1] callback(line) fp.close() conn.close() return self.voidresp() def storbinary(self, cmd, fp, blocksize=8192): '''Store a file in binary mode.''' self.voidcmd('TYPE I') conn = self.transfercmd(cmd) while 1: buf = fp.read(blocksize) if not buf: break conn.sendall(buf) conn.close() return self.voidresp() def storlines(self, cmd, fp): '''Store a file in line mode.''' self.voidcmd('TYPE A') conn = self.transfercmd(cmd) while 1: buf = fp.readline() if not buf: break if buf[-2:] != CRLF: if buf[-1] in CRLF: buf = buf[:-1] buf = buf + CRLF conn.sendall(buf) conn.close() return self.voidresp() def acct(self, password): '''Send new account name.''' cmd = 'ACCT ' + password return self.voidcmd(cmd) def nlst(self, *args): '''Return a list of files in a given directory (default the current).''' cmd = 'NLST' for arg in args: cmd = cmd + (' ' + arg) files = [] self.retrlines(cmd, files.append) return files def dir(self, *args): '''List a directory in long form. By default list current directory to stdout. Optional last argument is callback function; all non-empty arguments before it are concatenated to the LIST command. (This *should* only be used for a pathname.)''' cmd = 'LIST' func = None if args[-1:] and type(args[-1]) != type(''): args, func = args[:-1], args[-1] for arg in args: if arg: cmd = cmd + (' ' + arg) self.retrlines(cmd, func) def rename(self, fromname, toname): '''Rename a file.''' resp = self.sendcmd('RNFR ' + fromname) if resp[0] != '3': raise error_reply, resp return self.voidcmd('RNTO ' + toname) def delete(self, filename): '''Delete a file.''' resp = self.sendcmd('DELE ' + filename) if resp[:3] in ('250', '200'): return resp elif resp[:1] == '5': raise error_perm, resp else: raise error_reply, resp def cwd(self, dirname): '''Change to a directory.''' if dirname == '..': try: return self.voidcmd('CDUP') except error_perm, msg: if msg.args[0][:3] != '500': raise elif dirname == '': dirname = '.' # does nothing, but could return error cmd = 'CWD ' + dirname return self.voidcmd(cmd) def size(self, filename): '''Retrieve the size of a file.''' # Note that the RFC doesn't say anything about 'SIZE' resp = self.sendcmd('SIZE ' + filename) if resp[:3] == '213': s = resp[3:].strip() try: return int(s) except (OverflowError, ValueError): return long(s) def mkd(self, dirname): '''Make a directory, return its full pathname.''' resp = self.sendcmd('MKD ' + dirname) return parse257(resp) def rmd(self, dirname): '''Remove a directory.''' return self.voidcmd('RMD ' + dirname) def pwd(self): '''Return current working directory.''' resp = self.sendcmd('PWD') return parse257(resp) def quit(self): '''Quit, and close the connection.''' resp = self.voidcmd('QUIT') self.close() return resp def close(self): '''Close the connection without assuming anything about it.''' if self.file: self.file.close() self.sock.close() self.file = self.sock = None _150_re = None def parse150(resp): '''Parse the '150' response for a RETR request. Returns the expected transfer size or None; size is not guaranteed to be present in the 150 message. ''' if resp[:3] != '150': raise error_reply, resp global _150_re if _150_re is None: import re _150_re = re.compile("150 .* \((\d+) bytes\)", re.IGNORECASE) m = _150_re.match(resp) if not m: return None s = m.group(1) try: return int(s) except (OverflowError, ValueError): return long(s) _227_re = None def parse227(resp): '''Parse the '227' response for a PASV request. Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)' Return ('host.addr.as.numbers', port#) tuple.''' if resp[:3] != '227': raise error_reply, resp global _227_re if _227_re is None: import re _227_re = re.compile(r'(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)') m = _227_re.search(resp) if not m: raise error_proto, resp numbers = m.groups() host = '.'.join(numbers[:4]) port = (int(numbers[4]) << 8) + int(numbers[5]) return host, port def parse229(resp, peer): '''Parse the '229' response for a EPSV request. Raises error_proto if it does not contain '(|||port|)' Return ('host.addr.as.numbers', port#) tuple.''' if resp[:3] <> '229': raise error_reply, resp left = resp.find('(') if left < 0: raise error_proto, resp right = resp.find(')', left + 1) if right < 0: raise error_proto, resp # should contain '(|||port|)' if resp[left + 1] <> resp[right - 1]: raise error_proto, resp parts = resp[left + 1:right].split(resp[left+1]) if len(parts) <> 5: raise error_proto, resp host = peer[0] port = int(parts[3]) return host, port def parse257(resp): '''Parse the '257' response for a MKD or PWD request. This is a response to a MKD or PWD request: a directory name. Returns the directoryname in the 257 reply.''' if resp[:3] != '257': raise error_reply, resp if resp[3:5] != ' "': return '' # Not compliant to RFC 959, but UNIX ftpd does this dirname = '' i = 5 n = len(resp) while i < n: c = resp[i] i = i+1 if c == '"': if i >= n or resp[i] != '"': break i = i+1 dirname = dirname + c return dirname def print_line(line): '''Default retrlines callback to print a line.''' print line def ftpcp(source, sourcename, target, targetname = '', type = 'I'): '''Copy file from one FTP-instance to another.''' if not targetname: targetname = sourcename type = 'TYPE ' + type source.voidcmd(type) target.voidcmd(type) sourcehost, sourceport = parse227(source.sendcmd('PASV')) target.sendport(sourcehost, sourceport) # RFC 959: the user must "listen" [...] BEFORE sending the # transfer request. # So: STOR before RETR, because here the target is a "user". treply = target.sendcmd('STOR ' + targetname) if treply[:3] not in ('125', '150'): raise error_proto # RFC 959 sreply = source.sendcmd('RETR ' + sourcename) if sreply[:3] not in ('125', '150'): raise error_proto # RFC 959 source.voidresp() target.voidresp() class Netrc: """Class to parse & provide access to 'netrc' format files. See the netrc(4) man page for information on the file format. WARNING: This class is obsolete -- use module netrc instead. """ __defuser = None __defpasswd = None __defacct = None def __init__(self, filename=None): if filename is None: if "HOME" in os.environ: filename = os.path.join(os.environ["HOME"], ".netrc") else: raise IOError, \ "specify file to load or set $HOME" self.__hosts = {} self.__macros = {} fp = open(filename, "r") in_macro = 0 while 1: line = fp.readline() if not line: break if in_macro and line.strip(): macro_lines.append(line) continue elif in_macro: self.__macros[macro_name] = tuple(macro_lines) in_macro = 0 words = line.split() host = user = passwd = acct = None default = 0 i = 0 while i < len(words): w1 = words[i] if i+1 < len(words): w2 = words[i + 1] else: w2 = None if w1 == 'default': default = 1 elif w1 == 'machine' and w2: host = w2.lower() i = i + 1 elif w1 == 'login' and w2: user = w2 i = i + 1 elif w1 == 'password' and w2: passwd = w2 i = i + 1 elif w1 == 'account' and w2: acct = w2 i = i + 1 elif w1 == 'macdef' and w2: macro_name = w2 macro_lines = [] in_macro = 1 break i = i + 1 if default: self.__defuser = user or self.__defuser self.__defpasswd = passwd or self.__defpasswd self.__defacct = acct or self.__defacct if host: if host in self.__hosts: ouser, opasswd, oacct = \ self.__hosts[host] user = user or ouser passwd = passwd or opasswd acct = acct or oacct self.__hosts[host] = user, passwd, acct fp.close() def get_hosts(self): """Return a list of hosts mentioned in the .netrc file.""" return self.__hosts.keys() def get_account(self, host): """Returns login information for the named host. The return value is a triple containing userid, password, and the accounting field. """ host = host.lower() user = passwd = acct = None if host in self.__hosts: user, passwd, acct = self.__hosts[host] user = user or self.__defuser passwd = passwd or self.__defpasswd acct = acct or self.__defacct return user, passwd, acct def get_macros(self): """Return a list of all defined macro names.""" return self.__macros.keys() def get_macro(self, macro): """Return a sequence of lines which define a named macro.""" return self.__macros[macro] def test(): '''Test program. Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...''' debugging = 0 rcfile = None while sys.argv[1] == '-d': debugging = debugging+1 del sys.argv[1] if sys.argv[1][:2] == '-r': # get name of alternate ~/.netrc file: rcfile = sys.argv[1][2:] del sys.argv[1] host = sys.argv[1] ftp = FTP(host) ftp.set_debuglevel(debugging) userid = passwd = acct = '' try: netrc = Netrc(rcfile) except IOError: if rcfile is not None: sys.stderr.write("Could not open account file" " -- using anonymous login.") else: try: userid, passwd, acct = netrc.get_account(host) except KeyError: # no account for host sys.stderr.write( "No account -- using anonymous login.") ftp.login(userid, passwd, acct) for file in sys.argv[2:]: if file[:2] == '-l': ftp.dir(file[2:]) elif file[:2] == '-d': cmd = 'CWD' if file[2:]: cmd = cmd + ' ' + file[2:] resp = ftp.sendcmd(cmd) elif file == '-p': ftp.set_pasv(not ftp.passiveserver) else: ftp.retrbinary('RETR ' + file, \ sys.stdout.write, 1024) ftp.quit() if __name__ == '__main__': test()
Python
"""Simple class to read IFF chunks. An IFF chunk (used in formats such as AIFF, TIFF, RMFF (RealMedia File Format)) has the following structure: +----------------+ | ID (4 bytes) | +----------------+ | size (4 bytes) | +----------------+ | data | | ... | +----------------+ The ID is a 4-byte string which identifies the type of chunk. The size field (a 32-bit value, encoded using big-endian byte order) gives the size of the whole chunk, including the 8-byte header. Usually an IFF-type file consists of one or more chunks. The proposed usage of the Chunk class defined here is to instantiate an instance at the start of each chunk and read from the instance until it reaches the end, after which a new instance can be instantiated. At the end of the file, creating a new instance will fail with a EOFError exception. Usage: while True: try: chunk = Chunk(file) except EOFError: break chunktype = chunk.getname() while True: data = chunk.read(nbytes) if not data: pass # do something with data The interface is file-like. The implemented methods are: read, close, seek, tell, isatty. Extra methods are: skip() (called by close, skips to the end of the chunk), getname() (returns the name (ID) of the chunk) The __init__ method has one required argument, a file-like object (including a chunk instance), and one optional argument, a flag which specifies whether or not chunks are aligned on 2-byte boundaries. The default is 1, i.e. aligned. """ class Chunk: def __init__(self, file, align=True, bigendian=True, inclheader=False): import struct self.closed = False self.align = align # whether to align to word (2-byte) boundaries if bigendian: strflag = '>' else: strflag = '<' self.file = file self.chunkname = file.read(4) if len(self.chunkname) < 4: raise EOFError try: self.chunksize = struct.unpack(strflag+'l', file.read(4))[0] except struct.error: raise EOFError if inclheader: self.chunksize = self.chunksize - 8 # subtract header self.size_read = 0 try: self.offset = self.file.tell() except (AttributeError, IOError): self.seekable = False else: self.seekable = True def getname(self): """Return the name (ID) of the current chunk.""" return self.chunkname def getsize(self): """Return the size of the current chunk.""" return self.chunksize def close(self): if not self.closed: self.skip() self.closed = True def isatty(self): if self.closed: raise ValueError, "I/O operation on closed file" return False def seek(self, pos, whence=0): """Seek to specified position into the chunk. Default position is 0 (start of chunk). If the file is not seekable, this will result in an error. """ if self.closed: raise ValueError, "I/O operation on closed file" if not self.seekable: raise IOError, "cannot seek" if whence == 1: pos = pos + self.size_read elif whence == 2: pos = pos + self.chunksize if pos < 0 or pos > self.chunksize: raise RuntimeError self.file.seek(self.offset + pos, 0) self.size_read = pos def tell(self): if self.closed: raise ValueError, "I/O operation on closed file" return self.size_read def read(self, size=-1): """Read at most size bytes from the chunk. If size is omitted or negative, read until the end of the chunk. """ if self.closed: raise ValueError, "I/O operation on closed file" if self.size_read >= self.chunksize: return '' if size < 0: size = self.chunksize - self.size_read if size > self.chunksize - self.size_read: size = self.chunksize - self.size_read data = self.file.read(size) self.size_read = self.size_read + len(data) if self.size_read == self.chunksize and \ self.align and \ (self.chunksize & 1): dummy = self.file.read(1) self.size_read = self.size_read + len(dummy) return data def skip(self): """Skip the rest of the chunk. If you are not interested in the contents of the chunk, this method should be called so that the file points to the start of the next chunk. """ if self.closed: raise ValueError, "I/O operation on closed file" if self.seekable: try: n = self.chunksize - self.size_read # maybe fix alignment if self.align and (self.chunksize & 1): n = n + 1 self.file.seek(n, 1) self.size_read = self.size_read + n return except IOError: pass while self.size_read < self.chunksize: n = min(8192, self.chunksize - self.size_read) dummy = self.read(n) if not dummy: raise EOFError
Python
"""riscos specific module for conversion between pathnames and URLs. Based on macurl2path. Do not import directly, use urllib instead.""" import string import urllib import os __all__ = ["url2pathname","pathname2url"] __slash_dot = string.maketrans("/.", "./") def url2pathname(url): "Convert URL to a RISC OS path." tp = urllib.splittype(url)[0] if tp and tp <> 'file': raise RuntimeError, 'Cannot convert non-local URL to pathname' # Turn starting /// into /, an empty hostname means current host if url[:3] == '///': url = url[2:] elif url[:2] == '//': raise RuntimeError, 'Cannot convert non-local URL to pathname' components = string.split(url, '/') if not components[0]: if '$' in components: del components[0] else: components[0] = '$' # Remove . and embedded .. i = 0 while i < len(components): if components[i] == '.': del components[i] elif components[i] == '..' and i > 0 and \ components[i-1] not in ('', '..'): del components[i-1:i+1] i -= 1 elif components[i] == '..': components[i] = '^' i += 1 elif components[i] == '' and i > 0 and components[i-1] <> '': del components[i] else: i += 1 components = map(lambda x: urllib.unquote(x).translate(__slash_dot), components) return '.'.join(components) def pathname2url(pathname): "Convert a RISC OS path name to a file url." return urllib.quote('///' + pathname.translate(__slash_dot), "/$:") def test(): for url in ["index.html", "/SCSI::SCSI4/$/Anwendung/Comm/Apps/!Fresco/Welcome", "/SCSI::SCSI4/$/Anwendung/Comm/Apps/../!Fresco/Welcome", "../index.html", "bar/index.html", "/foo/bar/index.html", "/foo/bar/", "/"]: print '%r -> %r' % (url, url2pathname(url)) print "*******************************************************" for path in ["SCSI::SCSI4.$.Anwendung", "PythonApp:Lib", "PythonApp:Lib.rourl2path/py"]: print '%r -> %r' % (path, pathname2url(path)) if __name__ == '__main__': test()
Python
"""A more or less complete dictionary like interface for the RISC OS environment.""" import riscos class _Environ: def __init__(self, initial = None): pass def __repr__(self): return repr(riscos.getenvdict()) def __cmp__(self, dict): return cmp(riscos.getenvdict(), dict) def __len__(self): return len(riscos.getenvdict()) def __getitem__(self, key): ret = riscos.getenv(key) if ret<>None: return ret else: raise KeyError def __setitem__(self, key, item): riscos.putenv(key, item) def __delitem__(self, key): riscos.delenv(key) def clear(self): # too dangerous on RISC OS pass def copy(self): return riscos.getenvdict() def keys(self): return riscos.getenvdict().keys() def items(self): return riscos.getenvdict().items() def values(self): return riscos.getenvdict().values() def has_key(self, key): value = riscos.getenv(key) return value<>None def __contains__(self, key): return riscos.getenv(key) is not None def update(self, dict): for k, v in dict.items(): riscos.putenv(k, v) def get(self, key, failobj=None): value = riscos.getenv(key) if value<>None: return value else: return failobj
Python
# Module 'riscospath' -- common operations on RISC OS pathnames. # contributed by Andrew Clover ( andrew@oaktree.co.uk ) # The "os.path" name is an alias for this module on RISC OS systems; # on other systems (e.g. Mac, Windows), os.path provides the same # operations in a manner specific to that platform, and is an alias # to another module (e.g. macpath, ntpath). """ Instead of importing this module directly, import os and refer to this module as os.path. """ # strings representing various path-related bits and pieces curdir = '@' pardir = '^' extsep = '/' sep = '.' pathsep = ',' defpath = '<Run$Dir>' altsep = None # Imports - make an error-generating swi object if the swi module is not # available (ie. we are not running on RISC OS Python) import os, stat, string try: import swi except ImportError: class _swi: def swi(*a): raise AttributeError, 'This function only available under RISC OS' block= swi swi= _swi() [_false, _true]= range(2) _roots= ['$', '&', '%', '@', '\\'] # _allowMOSFSNames # After importing riscospath, set _allowMOSFSNames true if you want the module # to understand the "-SomeFS-" notation left over from the old BBC Master MOS, # as well as the standard "SomeFS:" notation. Set this to be fully backwards # compatible but remember that "-SomeFS-" can also be a perfectly valid file # name so care must be taken when splitting and joining paths. _allowMOSFSNames= _false ## Path manipulation, RISC OS stylee. def _split(p): """ split filing system name (including special field) and drive specifier from rest of path. This is needed by many riscospath functions. """ dash= _allowMOSFSNames and p[:1]=='-' if dash: q= string.find(p, '-', 1)+1 else: if p[:1]==':': q= 0 else: q= string.find(p, ':')+1 # q= index of start of non-FS portion of path s= string.find(p, '#') if s==-1 or s>q: s= q # find end of main FS name, not including special field else: for c in p[dash:s]: if c not in string.ascii_letters: q= 0 break # disallow invalid non-special-field characters in FS name r= q if p[q:q+1]==':': r= string.find(p, '.', q+1)+1 if r==0: r= len(p) # find end of drive name (if any) following FS name (if any) return (p[:q], p[q:r], p[r:]) def normcase(p): """ Normalize the case of a pathname. This converts to lowercase as the native RISC 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. """ return string.lower(p) def isabs(p): """ Return whether a path is absolute. Under RISC OS, a file system specifier does not make a path absolute, but a drive name or number does, and so does using the symbol for root, URD, library, CSD or PSD. This means it is perfectly possible to have an "absolute" URL dependent on the current working directory, and equally you can have a "relative" URL that's on a completely different device to the current one argh. """ (fs, drive, path)= _split(p) return drive!='' or path[:1] in _roots def join(a, *p): """ Join path elements with the directory separator, replacing the entire path when an absolute or FS-changing path part is found. """ j= a for b in p: (fs, drive, path)= _split(b) if j=='' or fs!='' or drive!='' or path[:1] in _roots: j= b elif j[-1]==':': j= j+b else: j= j+'.'+b return j def split(p): """ Split a path in head (everything up to the last '.') and tail (the rest). FS name must still be dealt with separately since special field may contain '.'. """ (fs, drive, path)= _split(p) q= string.rfind(path, '.') if q!=-1: return (fs+drive+path[:q], path[q+1:]) return ('', p) def splitext(p): """ Split a path in root and extension. This assumes the 'using slash for dot and dot for slash with foreign files' convention common in RISC OS is in force. """ (tail, head)= split(p) if '/' in head: q= len(head)-string.rfind(head, '/') return (p[:-q], p[-q:]) return (p, '') def splitdrive(p): """ Split a pathname into a drive specification (including FS name) and the rest of the path. The terminating dot of the drive name is included in the drive specification. """ (fs, drive, path)= _split(p) return (fs+drive, p) def basename(p): """ Return the tail (basename) part of a path. """ return split(p)[1] def dirname(p): """ Return the head (dirname) part of a path. """ return split(p)[0] def commonprefix(ps): """ Return the longest prefix of all list elements. Purely string-based; does not separate any path parts. Why am I in os.path? """ if len(ps)==0: return '' prefix= ps[0] for p in ps[1:]: prefix= prefix[:len(p)] for i in range(len(prefix)): if prefix[i] <> p[i]: prefix= prefix[:i] if i==0: return '' break return prefix ## File access functions. Why are we in os.path? def getsize(p): """ Return the size of a file, reported by os.stat(). """ st= os.stat(p) return st[stat.ST_SIZE] def getmtime(p): """ Return the last modification time of a file, reported by os.stat(). """ st = os.stat(p) return st[stat.ST_MTIME] getatime= getmtime # RISC OS-specific file access functions def exists(p): """ Test whether a path exists. """ try: return swi.swi('OS_File', '5s;i', p)!=0 except swi.error: return 0 lexists = exists def isdir(p): """ Is a path a directory? Includes image files. """ try: return swi.swi('OS_File', '5s;i', p) in [2, 3] except swi.error: return 0 def isfile(p): """ Test whether a path is a file, including image files. """ try: return swi.swi('OS_File', '5s;i', p) in [1, 3] except swi.error: return 0 def islink(p): """ RISC OS has no links or mounts. """ return _false ismount= islink # Same-file testing. # samefile works on filename comparison since there is no ST_DEV and ST_INO is # not reliably unique (esp. directories). First it has to normalise the # pathnames, which it can do 'properly' using OS_FSControl since samefile can # assume it's running on RISC OS (unlike normpath). def samefile(fa, fb): """ Test whether two pathnames reference the same actual file. """ l= 512 b= swi.block(l) swi.swi('OS_FSControl', 'isb..i', 37, fa, b, l) fa= b.ctrlstring() swi.swi('OS_FSControl', 'isb..i', 37, fb, b, l) fb= b.ctrlstring() return fa==fb def sameopenfile(a, b): """ Test whether two open file objects reference the same file. """ return os.fstat(a)[stat.ST_INO]==os.fstat(b)[stat.ST_INO] ## Path canonicalisation # 'user directory' is taken as meaning the User Root Directory, which is in # practice never used, for anything. def expanduser(p): (fs, drive, path)= _split(p) l= 512 b= swi.block(l) if path[:1]!='@': return p if fs=='': fsno= swi.swi('OS_Args', '00;i') swi.swi('OS_FSControl', 'iibi', 33, fsno, b, l) fsname= b.ctrlstring() else: if fs[:1]=='-': fsname= fs[1:-1] else: fsname= fs[:-1] fsname= string.split(fsname, '#', 1)[0] # remove special field from fs x= swi.swi('OS_FSControl', 'ib2s.i;.....i', 54, b, fsname, l) if x<l: urd= b.tostring(0, l-x-1) else: # no URD! try CSD x= swi.swi('OS_FSControl', 'ib0s.i;.....i', 54, b, fsname, l) if x<l: urd= b.tostring(0, l-x-1) else: # no CSD! use root urd= '$' return fsname+':'+urd+path[1:] # Environment variables are in angle brackets. def expandvars(p): """ Expand environment variables using OS_GSTrans. """ l= 512 b= swi.block(l) return b.tostring(0, swi.swi('OS_GSTrans', 'sbi;..i', p, b, l)) # Return an absolute path. RISC OS' osfscontrol_canonicalise_path does this among others abspath = os.expand # realpath is a no-op on systems without islink support realpath = abspath # Normalize a path. Only special path element under RISC OS is "^" for "..". def normpath(p): """ Normalize path, eliminating up-directory ^s. """ (fs, drive, path)= _split(p) rhs= '' ups= 0 while path!='': (path, el)= split(path) if el=='^': ups= ups+1 else: if ups>0: ups= ups-1 else: if rhs=='': rhs= el else: rhs= el+'.'+rhs while ups>0: ups= ups-1 rhs= '^.'+rhs return fs+drive+rhs # Directory tree walk. # Independent of host system. Why am I in os.path? def walk(top, func, arg): """Directory tree walk with callback function. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), call func(arg, dirname, fnames). dirname is the name of the directory, and fnames a list of the names of the files and subdirectories in dirname (excluding '.' and '..'). func may modify the fnames list in-place (e.g. via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in fnames; this can be used to implement a filter, or to impose a specific order of visiting. No semantics are defined for, or required of, arg, beyond that arg is always passed to func. It can be used, e.g., to pass a filename pattern, or a mutable object designed to accumulate statistics. Passing None for arg is common.""" try: names= os.listdir(top) except os.error: return func(arg, top, names) for name in names: name= join(top, name) if isdir(name) and not islink(name): walk(name, func, arg)
Python
"""Drop-in replacement for the thread module. Meant to be used as a brain-dead substitute so that threaded code does not need to be rewritten for when the thread module is not present. Suggested usage is:: try: import thread except ImportError: import dummy_thread as thread """ __author__ = "Brett Cannon" __email__ = "brett@python.org" # Exports only things specified by thread documentation # (skipping obsolete synonyms allocate(), start_new(), exit_thread()) __all__ = ['error', 'start_new_thread', 'exit', 'get_ident', 'allocate_lock', 'interrupt_main', 'LockType'] import traceback as _traceback class error(Exception): """Dummy implementation of thread.error.""" def __init__(self, *args): self.args = args def start_new_thread(function, args, kwargs={}): """Dummy implementation of thread.start_new_thread(). Compatibility is maintained by making sure that ``args`` is a tuple and ``kwargs`` is a dictionary. If an exception is raised and it is SystemExit (which can be done by thread.exit()) it is caught and nothing is done; all other exceptions are printed out by using traceback.print_exc(). If the executed function calls interrupt_main the KeyboardInterrupt will be raised when the function returns. """ if type(args) != type(tuple()): raise TypeError("2nd arg must be a tuple") if type(kwargs) != type(dict()): raise TypeError("3rd arg must be a dict") global _main _main = False try: function(*args, **kwargs) except SystemExit: pass except: _traceback.print_exc() _main = True global _interrupt if _interrupt: _interrupt = False raise KeyboardInterrupt def exit(): """Dummy implementation of thread.exit().""" raise SystemExit def get_ident(): """Dummy implementation of thread.get_ident(). Since this module should only be used when threadmodule is not available, it is safe to assume that the current process is the only thread. Thus a constant can be safely returned. """ return -1 def allocate_lock(): """Dummy implementation of thread.allocate_lock().""" return LockType() class LockType(object): """Class implementing dummy implementation of thread.LockType. Compatibility is maintained by maintaining self.locked_status which is a boolean that stores the state of the lock. Pickling of the lock, though, should not be done since if the thread module is then used with an unpickled ``lock()`` from here problems could occur from this class not having atomic methods. """ def __init__(self): self.locked_status = False def acquire(self, waitflag=None): """Dummy implementation of acquire(). For blocking calls, self.locked_status is automatically set to True and returned appropriately based on value of ``waitflag``. If it is non-blocking, then the value is actually checked and not set if it is already acquired. This is all done so that threading.Condition's assert statements aren't triggered and throw a little fit. """ if waitflag is None: self.locked_status = True return None elif not waitflag: if not self.locked_status: self.locked_status = True return True else: return False else: self.locked_status = True return True def release(self): """Release the dummy lock.""" # XXX Perhaps shouldn't actually bother to test? Could lead # to problems for complex, threaded code. if not self.locked_status: raise error self.locked_status = False return True def locked(self): return self.locked_status # Used to signal that interrupt_main was called in a "thread" _interrupt = False # True when not executing in a "thread" _main = True def interrupt_main(): """Set _interrupt flag to True to have start_new_thread raise KeyboardInterrupt upon exiting.""" if _main: raise KeyboardInterrupt else: global _interrupt _interrupt = True
Python
"""Open an arbitrary URL. See the following document for more info on URLs: "Names and Addresses, URIs, URLs, URNs, URCs", at http://www.w3.org/pub/WWW/Addressing/Overview.html See also the HTTP spec (from which the error codes are derived): "HTTP - Hypertext Transfer Protocol", at http://www.w3.org/pub/WWW/Protocols/ Related standards and specs: - RFC1808: the "relative URL" spec. (authoritative status) - RFC1738 - the "URL standard". (authoritative status) - RFC1630 - the "URI spec". (informational status) The object returned by URLopener().open(file) will differ per protocol. All you know is that is has methods read(), readline(), readlines(), fileno(), close() and info(). The read*(), fileno() and close() methods work like those of open files. The info() method returns a mimetools.Message object which can be used to query various info about the object, if available. (mimetools.Message objects are queried with the getheader() method.) """ import string import socket import os import time import sys from urlparse import urljoin as basejoin __all__ = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve", "urlcleanup", "quote", "quote_plus", "unquote", "unquote_plus", "urlencode", "url2pathname", "pathname2url", "splittag", "localhost", "thishost", "ftperrors", "basejoin", "unwrap", "splittype", "splithost", "splituser", "splitpasswd", "splitport", "splitnport", "splitquery", "splitattr", "splitvalue", "splitgophertype", "getproxies"] __version__ = '1.16' # XXX This version is not always updated :-( MAXFTPCACHE = 10 # Trim the ftp cache beyond this size # Helper for non-unix systems if os.name == 'mac': from macurl2path import url2pathname, pathname2url elif os.name == 'nt': from nturl2path import url2pathname, pathname2url elif os.name == 'riscos': from rourl2path import url2pathname, pathname2url else: def url2pathname(pathname): return unquote(pathname) def pathname2url(pathname): return quote(pathname) # This really consists of two pieces: # (1) a class which handles opening of all sorts of URLs # (plus assorted utilities etc.) # (2) a set of functions for parsing URLs # XXX Should these be separated out into different modules? # Shortcut for basic usage _urlopener = None def urlopen(url, data=None, proxies=None): """urlopen(url [, data]) -> open file-like object""" global _urlopener if proxies is not None: opener = FancyURLopener(proxies=proxies) elif not _urlopener: opener = FancyURLopener() _urlopener = opener else: opener = _urlopener if data is None: return opener.open(url) else: return opener.open(url, data) def urlretrieve(url, filename=None, reporthook=None, data=None): global _urlopener if not _urlopener: _urlopener = FancyURLopener() return _urlopener.retrieve(url, filename, reporthook, data) def urlcleanup(): if _urlopener: _urlopener.cleanup() ftpcache = {} class URLopener: """Class to open URLs. This is a class rather than just a subroutine because we may need more than one set of global protocol-specific options. Note -- this is a base class for those who don't want the automatic handling of errors type 302 (relocated) and 401 (authorization needed).""" __tempfiles = None version = "Python-urllib/%s" % __version__ # Constructor def __init__(self, proxies=None, **x509): if proxies is None: proxies = getproxies() assert hasattr(proxies, 'has_key'), "proxies must be a mapping" self.proxies = proxies self.key_file = x509.get('key_file') self.cert_file = x509.get('cert_file') self.addheaders = [('User-agent', self.version)] self.__tempfiles = [] self.__unlink = os.unlink # See cleanup() self.tempcache = None # Undocumented feature: if you assign {} to tempcache, # it is used to cache files retrieved with # self.retrieve(). This is not enabled by default # since it does not work for changing documents (and I # haven't got the logic to check expiration headers # yet). self.ftpcache = ftpcache # Undocumented feature: you can use a different # ftp cache by assigning to the .ftpcache member; # in case you want logically independent URL openers # XXX This is not threadsafe. Bah. def __del__(self): self.close() def close(self): self.cleanup() def cleanup(self): # This code sometimes runs when the rest of this module # has already been deleted, so it can't use any globals # or import anything. if self.__tempfiles: for file in self.__tempfiles: try: self.__unlink(file) except OSError: pass del self.__tempfiles[:] if self.tempcache: self.tempcache.clear() def addheader(self, *args): """Add a header to be used by the HTTP interface only e.g. u.addheader('Accept', 'sound/basic')""" self.addheaders.append(args) # External interface def open(self, fullurl, data=None): """Use URLopener().open(file) instead of open(file, 'r').""" fullurl = unwrap(toBytes(fullurl)) if self.tempcache and fullurl in self.tempcache: filename, headers = self.tempcache[fullurl] fp = open(filename, 'rb') return addinfourl(fp, headers, fullurl) urltype, url = splittype(fullurl) if not urltype: urltype = 'file' if urltype in self.proxies: proxy = self.proxies[urltype] urltype, proxyhost = splittype(proxy) host, selector = splithost(proxyhost) url = (host, fullurl) # Signal special case to open_*() else: proxy = None name = 'open_' + urltype self.type = urltype name = name.replace('-', '_') if not hasattr(self, name): if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else: return self.open_unknown(fullurl, data) try: if data is None: return getattr(self, name)(url) else: return getattr(self, name)(url, data) except socket.error, msg: raise IOError, ('socket error', msg), sys.exc_info()[2] def open_unknown(self, fullurl, data=None): """Overridable interface to open unknown URL type.""" type, url = splittype(fullurl) raise IOError, ('url error', 'unknown url type', type) def open_unknown_proxy(self, proxy, fullurl, data=None): """Overridable interface to open unknown URL type.""" type, url = splittype(fullurl) raise IOError, ('url error', 'invalid proxy for %s' % type, proxy) # External interface def retrieve(self, url, filename=None, reporthook=None, data=None): """retrieve(url) returns (filename, headers) for a local object or (tempfilename, headers) for a remote object.""" url = unwrap(toBytes(url)) if self.tempcache and url in self.tempcache: return self.tempcache[url] type, url1 = splittype(url) if filename is None and (not type or type == 'file'): try: fp = self.open_local_file(url1) hdrs = fp.info() del fp return url2pathname(splithost(url1)[1]), hdrs except IOError, msg: pass fp = self.open(url, data) headers = fp.info() if filename: tfp = open(filename, 'wb') else: import tempfile garbage, path = splittype(url) garbage, path = splithost(path or "") path, garbage = splitquery(path or "") path, garbage = splitattr(path or "") suffix = os.path.splitext(path)[1] (fd, filename) = tempfile.mkstemp(suffix) self.__tempfiles.append(filename) tfp = os.fdopen(fd, 'wb') result = filename, headers if self.tempcache is not None: self.tempcache[url] = result bs = 1024*8 size = -1 blocknum = 1 if reporthook: if "content-length" in headers: size = int(headers["Content-Length"]) reporthook(0, bs, size) block = fp.read(bs) if reporthook: reporthook(1, bs, size) while block: tfp.write(block) block = fp.read(bs) blocknum = blocknum + 1 if reporthook: reporthook(blocknum, bs, size) fp.close() tfp.close() del fp del tfp return result # Each method named open_<type> knows how to open that type of URL def open_http(self, url, data=None): """Use HTTP protocol.""" import httplib user_passwd = None if isinstance(url, str): host, selector = splithost(url) if host: user_passwd, host = splituser(host) host = unquote(host) realhost = host else: host, selector = url urltype, rest = splittype(selector) url = rest user_passwd = None if urltype.lower() != 'http': realhost = None else: realhost, rest = splithost(rest) if realhost: user_passwd, realhost = splituser(realhost) if user_passwd: selector = "%s://%s%s" % (urltype, realhost, rest) if proxy_bypass(realhost): host = realhost #print "proxy via http:", host, selector if not host: raise IOError, ('http error', 'no host given') if user_passwd: import base64 auth = base64.encodestring(user_passwd).strip() else: auth = None h = httplib.HTTP(host) if data is not None: h.putrequest('POST', selector) h.putheader('Content-type', 'application/x-www-form-urlencoded') h.putheader('Content-length', '%d' % len(data)) else: h.putrequest('GET', selector) if auth: h.putheader('Authorization', 'Basic %s' % auth) if realhost: h.putheader('Host', realhost) for args in self.addheaders: h.putheader(*args) h.endheaders() if data is not None: h.send(data) errcode, errmsg, headers = h.getreply() fp = h.getfile() if errcode == 200: return addinfourl(fp, headers, "http:" + url) else: if data is None: return self.http_error(url, fp, errcode, errmsg, headers) else: return self.http_error(url, fp, errcode, errmsg, headers, data) def http_error(self, url, fp, errcode, errmsg, headers, data=None): """Handle http errors. Derived class can override this, or provide specific handlers named http_error_DDD where DDD is the 3-digit error code.""" # First check if there's a specific handler for this error name = 'http_error_%d' % errcode if hasattr(self, name): method = getattr(self, name) if data is None: result = method(url, fp, errcode, errmsg, headers) else: result = method(url, fp, errcode, errmsg, headers, data) if result: return result return self.http_error_default(url, fp, errcode, errmsg, headers) def http_error_default(self, url, fp, errcode, errmsg, headers): """Default error handler: close the connection and raise IOError.""" void = fp.read() fp.close() raise IOError, ('http error', errcode, errmsg, headers) if hasattr(socket, "ssl"): def open_https(self, url, data=None): """Use HTTPS protocol.""" import httplib user_passwd = None if isinstance(url, str): host, selector = splithost(url) if host: user_passwd, host = splituser(host) host = unquote(host) realhost = host else: host, selector = url urltype, rest = splittype(selector) url = rest user_passwd = None if urltype.lower() != 'https': realhost = None else: realhost, rest = splithost(rest) if realhost: user_passwd, realhost = splituser(realhost) if user_passwd: selector = "%s://%s%s" % (urltype, realhost, rest) #print "proxy via https:", host, selector if not host: raise IOError, ('https error', 'no host given') if user_passwd: import base64 auth = base64.encodestring(user_passwd).strip() else: auth = None h = httplib.HTTPS(host, 0, key_file=self.key_file, cert_file=self.cert_file) if data is not None: h.putrequest('POST', selector) h.putheader('Content-type', 'application/x-www-form-urlencoded') h.putheader('Content-length', '%d' % len(data)) else: h.putrequest('GET', selector) if auth: h.putheader('Authorization', 'Basic %s' % auth) if realhost: h.putheader('Host', realhost) for args in self.addheaders: h.putheader(*args) h.endheaders() if data is not None: h.send(data) errcode, errmsg, headers = h.getreply() fp = h.getfile() if errcode == 200: return addinfourl(fp, headers, "https:" + url) else: if data is None: return self.http_error(url, fp, errcode, errmsg, headers) else: return self.http_error(url, fp, errcode, errmsg, headers, data) def open_gopher(self, url): """Use Gopher protocol.""" import gopherlib host, selector = splithost(url) if not host: raise IOError, ('gopher error', 'no host given') host = unquote(host) type, selector = splitgophertype(selector) selector, query = splitquery(selector) selector = unquote(selector) if query: query = unquote(query) fp = gopherlib.send_query(selector, query, host) else: fp = gopherlib.send_selector(selector, host) return addinfourl(fp, noheaders(), "gopher:" + url) def open_file(self, url): """Use local file or FTP depending on form of URL.""" if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/': return self.open_ftp(url) else: return self.open_local_file(url) def open_local_file(self, url): """Use local file.""" import mimetypes, mimetools, email.Utils, StringIO host, file = splithost(url) localname = url2pathname(file) try: stats = os.stat(localname) except OSError, e: raise IOError(e.errno, e.strerror, e.filename) size = stats.st_size modified = email.Utils.formatdate(stats.st_mtime, usegmt=True) mtype = mimetypes.guess_type(url)[0] headers = mimetools.Message(StringIO.StringIO( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified))) if not host: urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(localname, 'rb'), headers, urlfile) host, port = splitport(host) if not port \ and socket.gethostbyname(host) in (localhost(), thishost()): urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(localname, 'rb'), headers, urlfile) raise IOError, ('local file error', 'not on local host') def open_ftp(self, url): """Use FTP protocol.""" import mimetypes, mimetools, StringIO host, path = splithost(url) if not host: raise IOError, ('ftp error', 'no host given') host, port = splitport(host) user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = unquote(host) user = unquote(user or '') passwd = unquote(passwd or '') host = socket.gethostbyname(host) if not port: import ftplib port = ftplib.FTP_PORT else: port = int(port) path, attrs = splitattr(path) path = unquote(path) dirs = path.split('/') dirs, file = dirs[:-1], dirs[-1] if dirs and not dirs[0]: dirs = dirs[1:] if dirs and not dirs[0]: dirs[0] = '/' key = user, host, port, '/'.join(dirs) # XXX thread unsafe! if len(self.ftpcache) > MAXFTPCACHE: # Prune the cache, rather arbitrarily for k in self.ftpcache.keys(): if k != key: v = self.ftpcache[k] del self.ftpcache[k] v.close() try: if not key in self.ftpcache: self.ftpcache[key] = \ ftpwrapper(user, passwd, host, port, dirs) if not file: type = 'D' else: type = 'I' for attr in attrs: attr, value = splitvalue(attr) if attr.lower() == 'type' and \ value in ('a', 'A', 'i', 'I', 'd', 'D'): type = value.upper() (fp, retrlen) = self.ftpcache[key].retrfile(file, type) mtype = mimetypes.guess_type("ftp:" + url)[0] headers = "" if mtype: headers += "Content-Type: %s\n" % mtype if retrlen is not None and retrlen >= 0: headers += "Content-Length: %d\n" % retrlen headers = mimetools.Message(StringIO.StringIO(headers)) return addinfourl(fp, headers, "ftp:" + url) except ftperrors(), msg: raise IOError, ('ftp error', msg), sys.exc_info()[2] def open_data(self, url, data=None): """Use "data" URL.""" # ignore POSTed data # # syntax of data URLs: # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data # mediatype := [ type "/" subtype ] *( ";" parameter ) # data := *urlchar # parameter := attribute "=" value import StringIO, mimetools try: [type, data] = url.split(',', 1) except ValueError: raise IOError, ('data error', 'bad data URL') if not type: type = 'text/plain;charset=US-ASCII' semi = type.rfind(';') if semi >= 0 and '=' not in type[semi:]: encoding = type[semi+1:] type = type[:semi] else: encoding = '' msg = [] msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT', time.gmtime(time.time()))) msg.append('Content-type: %s' % type) if encoding == 'base64': import base64 data = base64.decodestring(data) else: data = unquote(data) msg.append('Content-length: %d' % len(data)) msg.append('') msg.append(data) msg = '\n'.join(msg) f = StringIO.StringIO(msg) headers = mimetools.Message(f, 0) f.fileno = None # needed for addinfourl return addinfourl(f, headers, url) class FancyURLopener(URLopener): """Derived class with handlers for errors we can handle (perhaps).""" def __init__(self, *args, **kwargs): URLopener.__init__(self, *args, **kwargs) self.auth_cache = {} self.tries = 0 self.maxtries = 10 def http_error_default(self, url, fp, errcode, errmsg, headers): """Default error handling -- don't raise an exception.""" return addinfourl(fp, headers, "http:" + url) def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): """Error 302 -- relocated (temporarily).""" self.tries += 1 if self.maxtries and self.tries >= self.maxtries: if hasattr(self, "http_error_500"): meth = self.http_error_500 else: meth = self.http_error_default self.tries = 0 return meth(url, fp, 500, "Internal Server Error: Redirect Recursion", headers) result = self.redirect_internal(url, fp, errcode, errmsg, headers, data) self.tries = 0 return result def redirect_internal(self, url, fp, errcode, errmsg, headers, data): if 'location' in headers: newurl = headers['location'] elif 'uri' in headers: newurl = headers['uri'] else: return void = fp.read() fp.close() # In case the server sent a relative URL, join with original: newurl = basejoin(self.type + ":" + url, newurl) return self.open(newurl) def http_error_301(self, url, fp, errcode, errmsg, headers, data=None): """Error 301 -- also relocated (permanently).""" return self.http_error_302(url, fp, errcode, errmsg, headers, data) def http_error_303(self, url, fp, errcode, errmsg, headers, data=None): """Error 303 -- also relocated (essentially identical to 302).""" return self.http_error_302(url, fp, errcode, errmsg, headers, data) def http_error_307(self, url, fp, errcode, errmsg, headers, data=None): """Error 307 -- relocated, but turn POST into error.""" if data is None: return self.http_error_302(url, fp, errcode, errmsg, headers, data) else: return self.http_error_default(url, fp, errcode, errmsg, headers) def http_error_401(self, url, fp, errcode, errmsg, headers, data=None): """Error 401 -- authentication required. See this URL for a description of the basic authentication scheme: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt""" if not 'www-authenticate' in headers: URLopener.http_error_default(self, url, fp, errcode, errmsg, headers) stuff = headers['www-authenticate'] import re match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff) if not match: URLopener.http_error_default(self, url, fp, errcode, errmsg, headers) scheme, realm = match.groups() if scheme.lower() != 'basic': URLopener.http_error_default(self, url, fp, errcode, errmsg, headers) name = 'retry_' + self.type + '_basic_auth' if data is None: return getattr(self,name)(url, realm) else: return getattr(self,name)(url, realm, data) def retry_http_basic_auth(self, url, realm, data=None): host, selector = splithost(url) i = host.find('@') + 1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host newurl = 'http://' + host + selector if data is None: return self.open(newurl) else: return self.open(newurl, data) def retry_https_basic_auth(self, url, realm, data=None): host, selector = splithost(url) i = host.find('@') + 1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host newurl = '//' + host + selector return self.open_https(newurl, data) def get_user_passwd(self, host, realm, clear_cache = 0): key = realm + '@' + host.lower() if key in self.auth_cache: if clear_cache: del self.auth_cache[key] else: return self.auth_cache[key] user, passwd = self.prompt_user_passwd(host, realm) if user or passwd: self.auth_cache[key] = (user, passwd) return user, passwd def prompt_user_passwd(self, host, realm): """Override this in a GUI environment!""" import getpass try: user = raw_input("Enter username for %s at %s: " % (realm, host)) passwd = getpass.getpass("Enter password for %s in %s at %s: " % (user, realm, host)) return user, passwd except KeyboardInterrupt: print return None, None # Utility functions _localhost = None def localhost(): """Return the IP address of the magic hostname 'localhost'.""" global _localhost if _localhost is None: _localhost = socket.gethostbyname('localhost') return _localhost _thishost = None def thishost(): """Return the IP address of the current host.""" global _thishost if _thishost is None: _thishost = socket.gethostbyname(socket.gethostname()) return _thishost _ftperrors = None def ftperrors(): """Return the set of errors raised by the FTP class.""" global _ftperrors if _ftperrors is None: import ftplib _ftperrors = ftplib.all_errors return _ftperrors _noheaders = None def noheaders(): """Return an empty mimetools.Message object.""" global _noheaders if _noheaders is None: import mimetools import StringIO _noheaders = mimetools.Message(StringIO.StringIO(), 0) _noheaders.fp.close() # Recycle file descriptor return _noheaders # Utility classes class ftpwrapper: """Class used by open_ftp() for cache of open FTP connections.""" def __init__(self, user, passwd, host, port, dirs): self.user = user self.passwd = passwd self.host = host self.port = port self.dirs = dirs self.init() def init(self): import ftplib self.busy = 0 self.ftp = ftplib.FTP() self.ftp.connect(self.host, self.port) self.ftp.login(self.user, self.passwd) for dir in self.dirs: self.ftp.cwd(dir) def retrfile(self, file, type): import ftplib self.endtransfer() if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1 else: cmd = 'TYPE ' + type; isdir = 0 try: self.ftp.voidcmd(cmd) except ftplib.all_errors: self.init() self.ftp.voidcmd(cmd) conn = None if file and not isdir: # Use nlst to see if the file exists at all try: self.ftp.nlst(file) except ftplib.error_perm, reason: raise IOError, ('ftp error', reason), sys.exc_info()[2] # Restore the transfer mode! self.ftp.voidcmd(cmd) # Try to retrieve as a file try: cmd = 'RETR ' + file conn = self.ftp.ntransfercmd(cmd) except ftplib.error_perm, reason: if str(reason)[:3] != '550': raise IOError, ('ftp error', reason), sys.exc_info()[2] if not conn: # Set transfer mode to ASCII! self.ftp.voidcmd('TYPE A') # Try a directory listing if file: cmd = 'LIST ' + file else: cmd = 'LIST' conn = self.ftp.ntransfercmd(cmd) self.busy = 1 # Pass back both a suitably decorated object and a retrieval length return (addclosehook(conn[0].makefile('rb'), self.endtransfer), conn[1]) def endtransfer(self): if not self.busy: return self.busy = 0 try: self.ftp.voidresp() except ftperrors(): pass def close(self): self.endtransfer() try: self.ftp.close() except ftperrors(): pass class addbase: """Base class for addinfo and addclosehook.""" def __init__(self, fp): self.fp = fp self.read = self.fp.read self.readline = self.fp.readline if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines if hasattr(self.fp, "fileno"): self.fileno = self.fp.fileno if hasattr(self.fp, "__iter__"): self.__iter__ = self.fp.__iter__ if hasattr(self.fp, "next"): self.next = self.fp.next def __repr__(self): return '<%s at %r whose fp = %r>' % (self.__class__.__name__, id(self), self.fp) def close(self): self.read = None self.readline = None self.readlines = None self.fileno = None if self.fp: self.fp.close() self.fp = None class addclosehook(addbase): """Class to add a close hook to an open file.""" def __init__(self, fp, closehook, *hookargs): addbase.__init__(self, fp) self.closehook = closehook self.hookargs = hookargs def close(self): addbase.close(self) if self.closehook: self.closehook(*self.hookargs) self.closehook = None self.hookargs = None class addinfo(addbase): """class to add an info() method to an open file.""" def __init__(self, fp, headers): addbase.__init__(self, fp) self.headers = headers def info(self): return self.headers class addinfourl(addbase): """class to add info() and geturl() methods to an open file.""" def __init__(self, fp, headers, url): addbase.__init__(self, fp) self.headers = headers self.url = url def info(self): return self.headers def geturl(self): return self.url # Utilities to parse URLs (most of these return None for missing parts): # unwrap('<URL:type://host/path>') --> 'type://host/path' # splittype('type:opaquestring') --> 'type', 'opaquestring' # splithost('//host[:port]/path') --> 'host[:port]', '/path' # splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]' # splitpasswd('user:passwd') -> 'user', 'passwd' # splitport('host:port') --> 'host', 'port' # splitquery('/path?query') --> '/path', 'query' # splittag('/path#tag') --> '/path', 'tag' # splitattr('/path;attr1=value1;attr2=value2;...') -> # '/path', ['attr1=value1', 'attr2=value2', ...] # splitvalue('attr=value') --> 'attr', 'value' # splitgophertype('/Xselector') --> 'X', 'selector' # unquote('abc%20def') -> 'abc def' # quote('abc def') -> 'abc%20def') try: unicode except NameError: def _is_unicode(x): return 0 else: def _is_unicode(x): return isinstance(x, unicode) def toBytes(url): """toBytes(u"URL") --> 'URL'.""" # Most URL schemes require ASCII. If that changes, the conversion # can be relaxed if _is_unicode(url): try: url = url.encode("ASCII") except UnicodeError: raise UnicodeError("URL " + repr(url) + " contains non-ASCII characters") return url def unwrap(url): """unwrap('<URL:type://host/path>') --> 'type://host/path'.""" url = url.strip() if url[:1] == '<' and url[-1:] == '>': url = url[1:-1].strip() if url[:4] == 'URL:': url = url[4:].strip() return url _typeprog = None def splittype(url): """splittype('type:opaquestring') --> 'type', 'opaquestring'.""" global _typeprog if _typeprog is None: import re _typeprog = re.compile('^([^/:]+):') match = _typeprog.match(url) if match: scheme = match.group(1) return scheme.lower(), url[len(scheme) + 1:] return None, url _hostprog = None def splithost(url): """splithost('//host[:port]/path') --> 'host[:port]', '/path'.""" global _hostprog if _hostprog is None: import re _hostprog = re.compile('^//([^/]*)(.*)$') match = _hostprog.match(url) if match: return match.group(1, 2) return None, url _userprog = None def splituser(host): """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.""" global _userprog if _userprog is None: import re _userprog = re.compile('^(.*)@(.*)$') match = _userprog.match(host) if match: return map(unquote, match.group(1, 2)) return None, host _passwdprog = None def splitpasswd(user): """splitpasswd('user:passwd') -> 'user', 'passwd'.""" global _passwdprog if _passwdprog is None: import re _passwdprog = re.compile('^([^:]*):(.*)$') match = _passwdprog.match(user) if match: return match.group(1, 2) return user, None # splittag('/path#tag') --> '/path', 'tag' _portprog = None def splitport(host): """splitport('host:port') --> 'host', 'port'.""" global _portprog if _portprog is None: import re _portprog = re.compile('^(.*):([0-9]+)$') match = _portprog.match(host) if match: return match.group(1, 2) return host, None _nportprog = None def splitnport(host, defport=-1): """Split host and port, returning numeric port. Return given default port if no ':' found; defaults to -1. Return numerical port if a valid number are found after ':'. Return None if ':' but not a valid number.""" global _nportprog if _nportprog is None: import re _nportprog = re.compile('^(.*):(.*)$') match = _nportprog.match(host) if match: host, port = match.group(1, 2) try: if not port: raise ValueError, "no digits" nport = int(port) except ValueError: nport = None return host, nport return host, defport _queryprog = None def splitquery(url): """splitquery('/path?query') --> '/path', 'query'.""" global _queryprog if _queryprog is None: import re _queryprog = re.compile('^(.*)\?([^?]*)$') match = _queryprog.match(url) if match: return match.group(1, 2) return url, None _tagprog = None def splittag(url): """splittag('/path#tag') --> '/path', 'tag'.""" global _tagprog if _tagprog is None: import re _tagprog = re.compile('^(.*)#([^#]*)$') match = _tagprog.match(url) if match: return match.group(1, 2) return url, None def splitattr(url): """splitattr('/path;attr1=value1;attr2=value2;...') -> '/path', ['attr1=value1', 'attr2=value2', ...].""" words = url.split(';') return words[0], words[1:] _valueprog = None def splitvalue(attr): """splitvalue('attr=value') --> 'attr', 'value'.""" global _valueprog if _valueprog is None: import re _valueprog = re.compile('^([^=]*)=(.*)$') match = _valueprog.match(attr) if match: return match.group(1, 2) return attr, None def splitgophertype(selector): """splitgophertype('/Xselector') --> 'X', 'selector'.""" if selector[:1] == '/' and selector[1:2]: return selector[1], selector[2:] return None, selector def unquote(s): """unquote('abc%20def') -> 'abc def'.""" mychr = chr myatoi = int list = s.split('%') res = [list[0]] myappend = res.append del list[0] for item in list: if item[1:2]: try: myappend(mychr(myatoi(item[:2], 16)) + item[2:]) except ValueError: myappend('%' + item) else: myappend('%' + item) return "".join(res) def unquote_plus(s): """unquote('%7e/abc+def') -> '~/abc def'""" s = s.replace('+', ' ') return unquote(s) always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' '0123456789' '_.-') _fast_safe_test = always_safe + '/' _fast_safe = None def _fast_quote(s): global _fast_safe if _fast_safe is None: _fast_safe = {} for c in _fast_safe_test: _fast_safe[c] = c res = list(s) for i in range(len(res)): c = res[i] if not c in _fast_safe: res[i] = '%%%02X' % ord(c) return ''.join(res) def quote(s, safe = '/'): """quote('abc def') -> 'abc%20def' Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted. RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists the following reserved characters. reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," Each of these characters is reserved in some component of a URL, but not necessarily in all of them. By default, the quote function is intended for quoting the path section of a URL. Thus, it will not encode '/'. This character is reserved, but in typical usage the quote function is being called on a path where the existing slash characters are used as reserved characters. """ safe = always_safe + safe if _fast_safe_test == safe: return _fast_quote(s) res = list(s) for i in range(len(res)): c = res[i] if c not in safe: res[i] = '%%%02X' % ord(c) return ''.join(res) def quote_plus(s, safe = ''): """Quote the query fragment of a URL; replacing ' ' with '+'""" if ' ' in s: l = s.split(' ') for i in range(len(l)): l[i] = quote(l[i], safe) return '+'.join(l) else: return quote(s, safe) def urlencode(query,doseq=0): """Encode a sequence of two-element tuples or dictionary into a URL query string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the parameters in the output will match the order of parameters in the input. """ if hasattr(query,"items"): # mapping objects query = query.items() else: # it's a bother at times that strings and string-like objects are # sequences... try: # non-sequence items should not work with len() # non-empty strings will fail this if len(query) and not isinstance(query[0], tuple): raise TypeError # zero-length sequences of all types will get here and succeed, # but that's a minor nit - since the original implementation # allowed empty dicts that type of behavior probably should be # preserved for consistency except TypeError: ty,va,tb = sys.exc_info() raise TypeError, "not a valid non-string sequence or mapping object", tb l = [] if not doseq: # preserve old behavior for k, v in query: k = quote_plus(str(k)) v = quote_plus(str(v)) l.append(k + '=' + v) else: for k, v in query: k = quote_plus(str(k)) if isinstance(v, str): v = quote_plus(v) l.append(k + '=' + v) elif _is_unicode(v): # is there a reasonable way to convert to ASCII? # encode generates a string, but "replace" or "ignore" # lose information and "strict" can raise UnicodeError v = quote_plus(v.encode("ASCII","replace")) l.append(k + '=' + v) else: try: # is this a sufficient test for sequence-ness? x = len(v) except TypeError: # not a sequence v = quote_plus(str(v)) l.append(k + '=' + v) else: # loop over the sequence for elt in v: l.append(k + '=' + quote_plus(str(elt))) return '&'.join(l) # Proxy handling def getproxies_environment(): """Return a dictionary of scheme -> proxy server URL mappings. Scan the environment for variables named <scheme>_proxy; this seems to be the standard convention. If you need a different way, you can pass a proxies dictionary to the [Fancy]URLopener constructor. """ proxies = {} for name, value in os.environ.items(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value return proxies if sys.platform == 'darwin': def getproxies_internetconfig(): """Return a dictionary of scheme -> proxy server URL mappings. By convention the mac uses Internet Config to store proxies. An HTTP proxy, for instance, is stored under the HttpProxy key. """ try: import ic except ImportError: return {} try: config = ic.IC() except ic.error: return {} proxies = {} # HTTP: if 'UseHTTPProxy' in config and config['UseHTTPProxy']: try: value = config['HTTPProxyHost'] except ic.error: pass else: proxies['http'] = 'http://%s' % value # FTP: XXXX To be done. # Gopher: XXXX To be done. return proxies def proxy_bypass(x): return 0 def getproxies(): return getproxies_environment() or getproxies_internetconfig() elif os.name == 'nt': def getproxies_registry(): """Return a dictionary of scheme -> proxy server URL mappings. Win32 uses the registry to store proxies. """ proxies = {} try: import _winreg except ImportError: # Std module, so should be around - but you never know! return proxies try: internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Internet Settings') proxyEnable = _winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0] if proxyEnable: # Returned as Unicode but problems if not converted to ASCII proxyServer = str(_winreg.QueryValueEx(internetSettings, 'ProxyServer')[0]) if '=' in proxyServer: # Per-protocol settings for p in proxyServer.split(';'): protocol, address = p.split('=', 1) # See if address has a type:// prefix import re if not re.match('^([^/:]+)://', address): address = '%s://%s' % (protocol, address) proxies[protocol] = address else: # Use one setting for all protocols if proxyServer[:5] == 'http:': proxies['http'] = proxyServer else: proxies['http'] = 'http://%s' % proxyServer proxies['ftp'] = 'ftp://%s' % proxyServer internetSettings.Close() except (WindowsError, ValueError, TypeError): # Either registry key not found etc, or the value in an # unexpected format. # proxies already set up to be empty so nothing to do pass return proxies def getproxies(): """Return a dictionary of scheme -> proxy server URL mappings. Returns settings gathered from the environment, if specified, or the registry. """ return getproxies_environment() or getproxies_registry() def proxy_bypass(host): try: import _winreg import re except ImportError: # Std modules, so should be around - but you never know! return 0 try: internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Internet Settings') proxyEnable = _winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0] proxyOverride = str(_winreg.QueryValueEx(internetSettings, 'ProxyOverride')[0]) # ^^^^ Returned as Unicode but problems if not converted to ASCII except WindowsError: return 0 if not proxyEnable or not proxyOverride: return 0 # try to make a host list from name and IP address. host = [host] try: addr = socket.gethostbyname(host[0]) if addr != host: host.append(addr) except socket.error: pass # make a check value list from the registry entry: replace the # '<local>' string by the localhost entry and the corresponding # canonical entry. proxyOverride = proxyOverride.split(';') i = 0 while i < len(proxyOverride): if proxyOverride[i] == '<local>': proxyOverride[i:i+1] = ['localhost', '127.0.0.1', socket.gethostname(), socket.gethostbyname( socket.gethostname())] i += 1 # print proxyOverride # now check if we match one of the registry values. for test in proxyOverride: test = test.replace(".", r"\.") # mask dots test = test.replace("*", r".*") # change glob sequence test = test.replace("?", r".") # change glob char for val in host: # print "%s <--> %s" %( test, val ) if re.match(test, val, re.I): return 1 return 0 else: # By default use environment variables getproxies = getproxies_environment def proxy_bypass(host): return 0 # Test and time quote() and unquote() def test1(): s = '' for i in range(256): s = s + chr(i) s = s*4 t0 = time.time() qs = quote(s) uqs = unquote(qs) t1 = time.time() if uqs != s: print 'Wrong!' print repr(s) print repr(qs) print repr(uqs) print round(t1 - t0, 3), 'sec' def reporthook(blocknum, blocksize, totalsize): # Report during remote transfers print "Block number: %d, Block size: %d, Total size: %d" % ( blocknum, blocksize, totalsize) # Test program def test(args=[]): if not args: args = [ '/etc/passwd', 'file:/etc/passwd', 'file://localhost/etc/passwd', 'ftp://ftp.python.org/pub/python/README', ## 'gopher://gopher.micro.umn.edu/1/', 'http://www.python.org/index.html', ] if hasattr(URLopener, "open_https"): args.append('https://synergy.as.cmu.edu/~geek/') try: for url in args: print '-'*10, url, '-'*10 fn, h = urlretrieve(url, None, reporthook) print fn if h: print '======' for k in h.keys(): print k + ':', h[k] print '======' fp = open(fn, 'rb') data = fp.read() del fp if '\r' in data: table = string.maketrans("", "") data = data.translate(table, "\r") print data fn, h = None, None print '-'*40 finally: urlcleanup() def main(): import getopt, sys try: opts, args = getopt.getopt(sys.argv[1:], "th") except getopt.error, msg: print msg print "Use -h for help" return t = 0 for o, a in opts: if o == '-t': t = t + 1 if o == '-h': print "Usage: python urllib.py [-t] [url ...]" print "-t runs self-test;", print "otherwise, contents of urls are printed" return if t: if t > 1: test1() test(args) else: if not args: print "Use -h for help" for url in args: print urlopen(url).read(), # Run test program when run as a script if __name__ == '__main__': main()
Python
# -*- Mode: Python; tab-width: 4 -*- # Id: asynchat.py,v 2.26 2000/09/07 22:29:26 rushing Exp # Author: Sam Rushing <rushing@nightmare.com> # ====================================================================== # Copyright 1996 by Sam Rushing # # All Rights Reserved # # Permission to use, copy, modify, and distribute this software and # its documentation for any purpose and without fee is hereby # granted, provided that the above copyright notice appear in all # copies and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of Sam # Rushing not be used in advertising or publicity pertaining to # distribution of the software without specific, written prior # permission. # # SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN # NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # ====================================================================== r"""A class supporting chat-style (command/response) protocols. This class adds support for 'chat' style protocols - where one side sends a 'command', and the other sends a response (examples would be the common internet protocols - smtp, nntp, ftp, etc..). The handle_read() method looks at the input stream for the current 'terminator' (usually '\r\n' for single-line responses, '\r\n.\r\n' for multi-line output), calling self.found_terminator() on its receipt. for example: Say you build an async nntp client using this class. At the start of the connection, you'll have self.terminator set to '\r\n', in order to process the single-line greeting. Just before issuing a 'LIST' command you'll set it to '\r\n.\r\n'. The output of the LIST command will be accumulated (using your own 'collect_incoming_data' method) up to the terminator, and then control will be returned to you - by calling your self.found_terminator() method. """ import socket import asyncore from collections import deque class async_chat (asyncore.dispatcher): """This is an abstract class. You must derive from this class, and add the two methods collect_incoming_data() and found_terminator()""" # these are overridable defaults ac_in_buffer_size = 4096 ac_out_buffer_size = 4096 def __init__ (self, conn=None): self.ac_in_buffer = '' self.ac_out_buffer = '' self.producer_fifo = fifo() asyncore.dispatcher.__init__ (self, conn) def collect_incoming_data(self, data): raise NotImplementedError, "must be implemented in subclass" def found_terminator(self): raise NotImplementedError, "must be implemented in subclass" def set_terminator (self, term): "Set the input delimiter. Can be a fixed string of any length, an integer, or None" self.terminator = term def get_terminator (self): return self.terminator # grab some more data from the socket, # throw it to the collector method, # check for the terminator, # if found, transition to the next state. def handle_read (self): try: data = self.recv (self.ac_in_buffer_size) except socket.error, why: self.handle_error() return self.ac_in_buffer = self.ac_in_buffer + data # Continue to search for self.terminator in self.ac_in_buffer, # while calling self.collect_incoming_data. The while loop # is necessary because we might read several data+terminator # combos with a single recv(1024). while self.ac_in_buffer: lb = len(self.ac_in_buffer) terminator = self.get_terminator() if terminator is None or terminator == '': # no terminator, collect it all self.collect_incoming_data (self.ac_in_buffer) self.ac_in_buffer = '' elif isinstance(terminator, int): # numeric terminator n = terminator if lb < n: self.collect_incoming_data (self.ac_in_buffer) self.ac_in_buffer = '' self.terminator = self.terminator - lb else: self.collect_incoming_data (self.ac_in_buffer[:n]) self.ac_in_buffer = self.ac_in_buffer[n:] self.terminator = 0 self.found_terminator() else: # 3 cases: # 1) end of buffer matches terminator exactly: # collect data, transition # 2) end of buffer matches some prefix: # collect data to the prefix # 3) end of buffer does not match any prefix: # collect data terminator_len = len(terminator) index = self.ac_in_buffer.find(terminator) if index != -1: # we found the terminator if index > 0: # don't bother reporting the empty string (source of subtle bugs) self.collect_incoming_data (self.ac_in_buffer[:index]) self.ac_in_buffer = self.ac_in_buffer[index+terminator_len:] # This does the Right Thing if the terminator is changed here. self.found_terminator() else: # check for a prefix of the terminator index = find_prefix_at_end (self.ac_in_buffer, terminator) if index: if index != lb: # we found a prefix, collect up to the prefix self.collect_incoming_data (self.ac_in_buffer[:-index]) self.ac_in_buffer = self.ac_in_buffer[-index:] break else: # no prefix, collect it all self.collect_incoming_data (self.ac_in_buffer) self.ac_in_buffer = '' def handle_write (self): self.initiate_send () def handle_close (self): self.close() def push (self, data): self.producer_fifo.push (simple_producer (data)) self.initiate_send() def push_with_producer (self, producer): self.producer_fifo.push (producer) self.initiate_send() def readable (self): "predicate for inclusion in the readable for select()" return (len(self.ac_in_buffer) <= self.ac_in_buffer_size) def writable (self): "predicate for inclusion in the writable for select()" # return len(self.ac_out_buffer) or len(self.producer_fifo) or (not self.connected) # this is about twice as fast, though not as clear. return not ( (self.ac_out_buffer == '') and self.producer_fifo.is_empty() and self.connected ) def close_when_done (self): "automatically close this channel once the outgoing queue is empty" self.producer_fifo.push (None) # refill the outgoing buffer by calling the more() method # of the first producer in the queue def refill_buffer (self): while 1: if len(self.producer_fifo): p = self.producer_fifo.first() # a 'None' in the producer fifo is a sentinel, # telling us to close the channel. if p is None: if not self.ac_out_buffer: self.producer_fifo.pop() self.close() return elif isinstance(p, str): self.producer_fifo.pop() self.ac_out_buffer = self.ac_out_buffer + p return data = p.more() if data: self.ac_out_buffer = self.ac_out_buffer + data return else: self.producer_fifo.pop() else: return def initiate_send (self): obs = self.ac_out_buffer_size # try to refill the buffer if (len (self.ac_out_buffer) < obs): self.refill_buffer() if self.ac_out_buffer and self.connected: # try to send the buffer try: num_sent = self.send (self.ac_out_buffer[:obs]) if num_sent: self.ac_out_buffer = self.ac_out_buffer[num_sent:] except socket.error, why: self.handle_error() return def discard_buffers (self): # Emergencies only! self.ac_in_buffer = '' self.ac_out_buffer = '' while self.producer_fifo: self.producer_fifo.pop() class simple_producer: def __init__ (self, data, buffer_size=512): self.data = data self.buffer_size = buffer_size def more (self): if len (self.data) > self.buffer_size: result = self.data[:self.buffer_size] self.data = self.data[self.buffer_size:] return result else: result = self.data self.data = '' return result class fifo: def __init__ (self, list=None): if not list: self.list = deque() else: self.list = deque(list) def __len__ (self): return len(self.list) def is_empty (self): return not self.list def first (self): return self.list[0] def push (self, data): self.list.append(data) def pop (self): if self.list: return (1, self.list.popleft()) else: return (0, None) # Given 'haystack', see if any prefix of 'needle' is at its end. This # assumes an exact match has already been checked. Return the number of # characters matched. # for example: # f_p_a_e ("qwerty\r", "\r\n") => 1 # f_p_a_e ("qwertydkjf", "\r\n") => 0 # f_p_a_e ("qwerty\r\n", "\r\n") => <undefined> # this could maybe be made faster with a computed regex? # [answer: no; circa Python-2.0, Jan 2001] # new python: 28961/s # old python: 18307/s # re: 12820/s # regex: 14035/s def find_prefix_at_end (haystack, needle): l = len(needle) - 1 while l and not haystack.endswith(needle[:l]): l -= 1 return l
Python
"Read and write ZIP files." import struct, os, time import binascii try: import zlib # We may need its compression method except ImportError: zlib = None __all__ = ["BadZipfile", "error", "ZIP_STORED", "ZIP_DEFLATED", "is_zipfile", "ZipInfo", "ZipFile", "PyZipFile"] class BadZipfile(Exception): pass error = BadZipfile # The exception raised by this module # constants for Zip file compression methods ZIP_STORED = 0 ZIP_DEFLATED = 8 # Other ZIP compression methods not supported # Here are some struct module formats for reading headers structEndArchive = "<4s4H2lH" # 9 items, end of archive, 22 bytes stringEndArchive = "PK\005\006" # magic number for end of archive record structCentralDir = "<4s4B4HlLL5HLl"# 19 items, central directory, 46 bytes stringCentralDir = "PK\001\002" # magic number for central directory structFileHeader = "<4s2B4HlLL2H" # 12 items, file header record, 30 bytes stringFileHeader = "PK\003\004" # magic number for file header # indexes of entries in the central directory structure _CD_SIGNATURE = 0 _CD_CREATE_VERSION = 1 _CD_CREATE_SYSTEM = 2 _CD_EXTRACT_VERSION = 3 _CD_EXTRACT_SYSTEM = 4 # is this meaningful? _CD_FLAG_BITS = 5 _CD_COMPRESS_TYPE = 6 _CD_TIME = 7 _CD_DATE = 8 _CD_CRC = 9 _CD_COMPRESSED_SIZE = 10 _CD_UNCOMPRESSED_SIZE = 11 _CD_FILENAME_LENGTH = 12 _CD_EXTRA_FIELD_LENGTH = 13 _CD_COMMENT_LENGTH = 14 _CD_DISK_NUMBER_START = 15 _CD_INTERNAL_FILE_ATTRIBUTES = 16 _CD_EXTERNAL_FILE_ATTRIBUTES = 17 _CD_LOCAL_HEADER_OFFSET = 18 # indexes of entries in the local file header structure _FH_SIGNATURE = 0 _FH_EXTRACT_VERSION = 1 _FH_EXTRACT_SYSTEM = 2 # is this meaningful? _FH_GENERAL_PURPOSE_FLAG_BITS = 3 _FH_COMPRESSION_METHOD = 4 _FH_LAST_MOD_TIME = 5 _FH_LAST_MOD_DATE = 6 _FH_CRC = 7 _FH_COMPRESSED_SIZE = 8 _FH_UNCOMPRESSED_SIZE = 9 _FH_FILENAME_LENGTH = 10 _FH_EXTRA_FIELD_LENGTH = 11 def is_zipfile(filename): """Quickly see if file is a ZIP file by checking the magic number.""" try: fpin = open(filename, "rb") endrec = _EndRecData(fpin) fpin.close() if endrec: return True # file has correct magic number except IOError: pass return False def _EndRecData(fpin): """Return data from the "End of Central Directory" record, or None. The data is a list of the nine items in the ZIP "End of central dir" record followed by a tenth item, the file seek offset of this record.""" fpin.seek(-22, 2) # Assume no archive comment. filesize = fpin.tell() + 22 # Get file size data = fpin.read() if data[0:4] == stringEndArchive and data[-2:] == "\000\000": endrec = struct.unpack(structEndArchive, data) endrec = list(endrec) endrec.append("") # Append the archive comment endrec.append(filesize - 22) # Append the record start offset return endrec # Search the last END_BLOCK bytes of the file for the record signature. # The comment is appended to the ZIP file and has a 16 bit length. # So the comment may be up to 64K long. We limit the search for the # signature to a few Kbytes at the end of the file for efficiency. # also, the signature must not appear in the comment. END_BLOCK = min(filesize, 1024 * 4) fpin.seek(filesize - END_BLOCK, 0) data = fpin.read() start = data.rfind(stringEndArchive) if start >= 0: # Correct signature string was found endrec = struct.unpack(structEndArchive, data[start:start+22]) endrec = list(endrec) comment = data[start+22:] if endrec[7] == len(comment): # Comment length checks out # Append the archive comment and start offset endrec.append(comment) endrec.append(filesize - END_BLOCK + start) return endrec return # Error, return None class ZipInfo: """Class with attributes describing each file in the ZIP archive.""" def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)): self.orig_filename = filename # Original file name in archive # Terminate the file name at the first null byte. Null bytes in file # names are used as tricks by viruses in archives. null_byte = filename.find(chr(0)) if null_byte >= 0: filename = filename[0:null_byte] # This is used to ensure paths in generated ZIP files always use # forward slashes as the directory separator, as required by the # ZIP format specification. if os.sep != "/": filename = filename.replace(os.sep, "/") self.filename = filename # Normalized file name self.date_time = date_time # year, month, day, hour, min, sec # Standard values: self.compress_type = ZIP_STORED # Type of compression for the file self.comment = "" # Comment for each file self.extra = "" # ZIP extra data self.create_system = 0 # System which created ZIP archive self.create_version = 20 # Version which created ZIP archive self.extract_version = 20 # Version needed to extract archive self.reserved = 0 # Must be zero self.flag_bits = 0 # ZIP flag bits self.volume = 0 # Volume number of file header self.internal_attr = 0 # Internal attributes self.external_attr = 0 # External file attributes # Other attributes are set by class ZipFile: # header_offset Byte offset to the file header # file_offset Byte offset to the start of the file data # CRC CRC-32 of the uncompressed file # compress_size Size of the compressed file # file_size Size of the uncompressed file def FileHeader(self): """Return the per-file header as a string.""" dt = self.date_time dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2] dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2) if self.flag_bits & 0x08: # Set these to zero because we write them after the file data CRC = compress_size = file_size = 0 else: CRC = self.CRC compress_size = self.compress_size file_size = self.file_size header = struct.pack(structFileHeader, stringFileHeader, self.extract_version, self.reserved, self.flag_bits, self.compress_type, dostime, dosdate, CRC, compress_size, file_size, len(self.filename), len(self.extra)) return header + self.filename + self.extra class ZipFile: """ Class with methods to open, read, write, close, list zip files. z = ZipFile(file, mode="r", compression=ZIP_STORED) file: Either the path to the file, or a file-like object. If it is a path, the file will be opened and closed by ZipFile. mode: The mode can be either read "r", write "w" or append "a". compression: ZIP_STORED (no compression) or ZIP_DEFLATED (requires zlib). """ fp = None # Set here since __del__ checks it def __init__(self, file, mode="r", compression=ZIP_STORED): """Open the ZIP file with mode read "r", write "w" or append "a".""" if compression == ZIP_STORED: pass elif compression == ZIP_DEFLATED: if not zlib: raise RuntimeError,\ "Compression requires the (missing) zlib module" else: raise RuntimeError, "That compression method is not supported" self.debug = 0 # Level of printing: 0 through 3 self.NameToInfo = {} # Find file info given name self.filelist = [] # List of ZipInfo instances for archive self.compression = compression # Method of compression self.mode = key = mode.replace('b', '')[0] # Check if we were passed a file-like object if isinstance(file, basestring): self._filePassed = 0 self.filename = file modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'} self.fp = open(file, modeDict[mode]) else: self._filePassed = 1 self.fp = file self.filename = getattr(file, 'name', None) if key == 'r': self._GetContents() elif key == 'w': pass elif key == 'a': try: # See if file is a zip file self._RealGetContents() # seek to start of directory and overwrite self.fp.seek(self.start_dir, 0) except BadZipfile: # file is not a zip file, just append self.fp.seek(0, 2) else: if not self._filePassed: self.fp.close() self.fp = None raise RuntimeError, 'Mode must be "r", "w" or "a"' def _GetContents(self): """Read the directory, making sure we close the file if the format is bad.""" try: self._RealGetContents() except BadZipfile: if not self._filePassed: self.fp.close() self.fp = None raise def _RealGetContents(self): """Read in the table of contents for the ZIP file.""" fp = self.fp endrec = _EndRecData(fp) if not endrec: raise BadZipfile, "File is not a zip file" if self.debug > 1: print endrec size_cd = endrec[5] # bytes in central directory offset_cd = endrec[6] # offset of central directory self.comment = endrec[8] # archive comment # endrec[9] is the offset of the "End of Central Dir" record x = endrec[9] - size_cd # "concat" is zero, unless zip was concatenated to another file concat = x - offset_cd if self.debug > 2: print "given, inferred, offset", offset_cd, x, concat # self.start_dir: Position of start of central directory self.start_dir = offset_cd + concat fp.seek(self.start_dir, 0) total = 0 while total < size_cd: centdir = fp.read(46) total = total + 46 if centdir[0:4] != stringCentralDir: raise BadZipfile, "Bad magic number for central directory" centdir = struct.unpack(structCentralDir, centdir) if self.debug > 2: print centdir filename = fp.read(centdir[_CD_FILENAME_LENGTH]) # Create ZipInfo instance to store file information x = ZipInfo(filename) x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH]) x.comment = fp.read(centdir[_CD_COMMENT_LENGTH]) total = (total + centdir[_CD_FILENAME_LENGTH] + centdir[_CD_EXTRA_FIELD_LENGTH] + centdir[_CD_COMMENT_LENGTH]) x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET] + concat # file_offset must be computed below... (x.create_version, x.create_system, x.extract_version, x.reserved, x.flag_bits, x.compress_type, t, d, x.CRC, x.compress_size, x.file_size) = centdir[1:12] x.volume, x.internal_attr, x.external_attr = centdir[15:18] # Convert date/time code to (year, month, day, hour, min, sec) x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F, t>>11, (t>>5)&0x3F, (t&0x1F) * 2 ) self.filelist.append(x) self.NameToInfo[x.filename] = x if self.debug > 2: print "total", total for data in self.filelist: fp.seek(data.header_offset, 0) fheader = fp.read(30) if fheader[0:4] != stringFileHeader: raise BadZipfile, "Bad magic number for file header" fheader = struct.unpack(structFileHeader, fheader) # file_offset is computed here, since the extra field for # the central directory and for the local file header # refer to different fields, and they can have different # lengths data.file_offset = (data.header_offset + 30 + fheader[_FH_FILENAME_LENGTH] + fheader[_FH_EXTRA_FIELD_LENGTH]) fname = fp.read(fheader[_FH_FILENAME_LENGTH]) if fname != data.orig_filename: raise RuntimeError, \ 'File name in directory "%s" and header "%s" differ.' % ( data.orig_filename, fname) def namelist(self): """Return a list of file names in the archive.""" l = [] for data in self.filelist: l.append(data.filename) return l def infolist(self): """Return a list of class ZipInfo instances for files in the archive.""" return self.filelist def printdir(self): """Print a table of contents for the zip file.""" print "%-46s %19s %12s" % ("File Name", "Modified ", "Size") for zinfo in self.filelist: date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size) def testzip(self): """Read all the files and check the CRC.""" for zinfo in self.filelist: try: self.read(zinfo.filename) # Check CRC-32 except BadZipfile: return zinfo.filename def getinfo(self, name): """Return the instance of ZipInfo given 'name'.""" return self.NameToInfo[name] def read(self, name): """Return file bytes (as a string) for name.""" if self.mode not in ("r", "a"): raise RuntimeError, 'read() requires mode "r" or "a"' if not self.fp: raise RuntimeError, \ "Attempt to read ZIP archive that was already closed" zinfo = self.getinfo(name) filepos = self.fp.tell() self.fp.seek(zinfo.file_offset, 0) bytes = self.fp.read(zinfo.compress_size) self.fp.seek(filepos, 0) if zinfo.compress_type == ZIP_STORED: pass elif zinfo.compress_type == ZIP_DEFLATED: if not zlib: raise RuntimeError, \ "De-compression requires the (missing) zlib module" # zlib compress/decompress code by Jeremy Hylton of CNRI dc = zlib.decompressobj(-15) bytes = dc.decompress(bytes) # need to feed in unused pad byte so that zlib won't choke ex = dc.decompress('Z') + dc.flush() if ex: bytes = bytes + ex else: raise BadZipfile, \ "Unsupported compression method %d for file %s" % \ (zinfo.compress_type, name) crc = binascii.crc32(bytes) if crc != zinfo.CRC: raise BadZipfile, "Bad CRC-32 for file %s" % name return bytes def _writecheck(self, zinfo): """Check for errors before writing a file to the archive.""" if zinfo.filename in self.NameToInfo: if self.debug: # Warning for duplicate names print "Duplicate name:", zinfo.filename if self.mode not in ("w", "a"): raise RuntimeError, 'write() requires mode "w" or "a"' if not self.fp: raise RuntimeError, \ "Attempt to write ZIP archive that was already closed" if zinfo.compress_type == ZIP_DEFLATED and not zlib: raise RuntimeError, \ "Compression requires the (missing) zlib module" if zinfo.compress_type not in (ZIP_STORED, ZIP_DEFLATED): raise RuntimeError, \ "That compression method is not supported" def write(self, filename, arcname=None, compress_type=None): """Put the bytes from filename into the archive under the name arcname.""" st = os.stat(filename) mtime = time.localtime(st.st_mtime) date_time = mtime[0:6] # Create ZipInfo instance to store file information if arcname is None: zinfo = ZipInfo(filename, date_time) else: zinfo = ZipInfo(arcname, date_time) zinfo.external_attr = (st[0] & 0xFFFF) << 16L # Unix attributes if compress_type is None: zinfo.compress_type = self.compression else: zinfo.compress_type = compress_type self._writecheck(zinfo) fp = open(filename, "rb") zinfo.flag_bits = 0x00 zinfo.header_offset = self.fp.tell() # Start of header bytes # Must overwrite CRC and sizes with correct data later zinfo.CRC = CRC = 0 zinfo.compress_size = compress_size = 0 zinfo.file_size = file_size = 0 self.fp.write(zinfo.FileHeader()) zinfo.file_offset = self.fp.tell() # Start of file bytes if zinfo.compress_type == ZIP_DEFLATED: cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15) else: cmpr = None while 1: buf = fp.read(1024 * 8) if not buf: break file_size = file_size + len(buf) CRC = binascii.crc32(buf, CRC) if cmpr: buf = cmpr.compress(buf) compress_size = compress_size + len(buf) self.fp.write(buf) fp.close() if cmpr: buf = cmpr.flush() compress_size = compress_size + len(buf) self.fp.write(buf) zinfo.compress_size = compress_size else: zinfo.compress_size = file_size zinfo.CRC = CRC zinfo.file_size = file_size # Seek backwards and write CRC and file sizes position = self.fp.tell() # Preserve current position in file self.fp.seek(zinfo.header_offset + 14, 0) self.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size, zinfo.file_size)) self.fp.seek(position, 0) self.filelist.append(zinfo) self.NameToInfo[zinfo.filename] = zinfo def writestr(self, zinfo_or_arcname, bytes): """Write a file into the archive. The contents is the string 'bytes'. 'zinfo_or_arcname' is either a ZipInfo instance or the name of the file in the archive.""" if not isinstance(zinfo_or_arcname, ZipInfo): zinfo = ZipInfo(filename=zinfo_or_arcname, date_time=time.localtime(time.time())) zinfo.compress_type = self.compression else: zinfo = zinfo_or_arcname self._writecheck(zinfo) zinfo.file_size = len(bytes) # Uncompressed size zinfo.CRC = binascii.crc32(bytes) # CRC-32 checksum if zinfo.compress_type == ZIP_DEFLATED: co = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15) bytes = co.compress(bytes) + co.flush() zinfo.compress_size = len(bytes) # Compressed size else: zinfo.compress_size = zinfo.file_size zinfo.header_offset = self.fp.tell() # Start of header bytes self.fp.write(zinfo.FileHeader()) zinfo.file_offset = self.fp.tell() # Start of file bytes self.fp.write(bytes) if zinfo.flag_bits & 0x08: # Write CRC and file sizes after the file data self.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size, zinfo.file_size)) self.filelist.append(zinfo) self.NameToInfo[zinfo.filename] = zinfo def __del__(self): """Call the "close()" method in case the user forgot.""" self.close() def close(self): """Close the file, and for mode "w" and "a" write the ending records.""" if self.fp is None: return if self.mode in ("w", "a"): # write ending records count = 0 pos1 = self.fp.tell() for zinfo in self.filelist: # write central directory count = count + 1 dt = zinfo.date_time dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2] dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2) centdir = struct.pack(structCentralDir, stringCentralDir, zinfo.create_version, zinfo.create_system, zinfo.extract_version, zinfo.reserved, zinfo.flag_bits, zinfo.compress_type, dostime, dosdate, zinfo.CRC, zinfo.compress_size, zinfo.file_size, len(zinfo.filename), len(zinfo.extra), len(zinfo.comment), 0, zinfo.internal_attr, zinfo.external_attr, zinfo.header_offset) self.fp.write(centdir) self.fp.write(zinfo.filename) self.fp.write(zinfo.extra) self.fp.write(zinfo.comment) pos2 = self.fp.tell() # Write end-of-zip-archive record endrec = struct.pack(structEndArchive, stringEndArchive, 0, 0, count, count, pos2 - pos1, pos1, 0) self.fp.write(endrec) self.fp.flush() if not self._filePassed: self.fp.close() self.fp = None class PyZipFile(ZipFile): """Class to create ZIP archives with Python library files and packages.""" def writepy(self, pathname, basename = ""): """Add all files from "pathname" to the ZIP archive. If pathname is a package directory, search the directory and all package subdirectories recursively for all *.py and enter the modules into the archive. If pathname is a plain directory, listdir *.py and enter all modules. Else, pathname must be a Python *.py file and the module will be put into the archive. Added modules are always module.pyo or module.pyc. This method will compile the module.py into module.pyc if necessary. """ dir, name = os.path.split(pathname) if os.path.isdir(pathname): initname = os.path.join(pathname, "__init__.py") if os.path.isfile(initname): # This is a package directory, add it if basename: basename = "%s/%s" % (basename, name) else: basename = name if self.debug: print "Adding package in", pathname, "as", basename fname, arcname = self._get_codename(initname[0:-3], basename) if self.debug: print "Adding", arcname self.write(fname, arcname) dirlist = os.listdir(pathname) dirlist.remove("__init__.py") # Add all *.py files and package subdirectories for filename in dirlist: path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) if os.path.isdir(path): if os.path.isfile(os.path.join(path, "__init__.py")): # This is a package directory, add it self.writepy(path, basename) # Recursive call elif ext == ".py": fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: print "Adding", arcname self.write(fname, arcname) else: # This is NOT a package directory, add its files at top level if self.debug: print "Adding files from directory", pathname for filename in os.listdir(pathname): path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) if ext == ".py": fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: print "Adding", arcname self.write(fname, arcname) else: if pathname[-3:] != ".py": raise RuntimeError, \ 'Files added with writepy() must end with ".py"' fname, arcname = self._get_codename(pathname[0:-3], basename) if self.debug: print "Adding file", arcname self.write(fname, arcname) def _get_codename(self, pathname, basename): """Return (filename, archivename) for the path. Given a module name path, return the correct file path and archive name, compiling if necessary. For example, given /python/lib/string, return (/python/lib/string.pyc, string). """ file_py = pathname + ".py" file_pyc = pathname + ".pyc" file_pyo = pathname + ".pyo" if os.path.isfile(file_pyo) and \ os.stat(file_pyo).st_mtime >= os.stat(file_py).st_mtime: fname = file_pyo # Use .pyo file elif not os.path.isfile(file_pyc) or \ os.stat(file_pyc).st_mtime < os.stat(file_py).st_mtime: import py_compile if self.debug: print "Compiling", file_py try: py_compile.compile(file_py, file_pyc, None, True) except py_compile.PyCompileError,err: print err.msg fname = file_pyc else: fname = file_pyc archivename = os.path.split(fname)[1] if basename: archivename = "%s/%s" % (basename, archivename) return (fname, archivename)
Python
"""An extensible library for opening URLs using a variety of protocols The simplest way to use this module is to call the urlopen function, which accepts a string containing a URL or a Request object (described below). It opens the URL and returns the results as file-like object; the returned object has some extra methods described below. The OpenerDirector manages a collection of Handler objects that do all the actual work. Each Handler implements a particular protocol or option. The OpenerDirector is a composite object that invokes the Handlers needed to open the requested URL. For example, the HTTPHandler performs HTTP GET and POST requests and deals with non-error returns. The HTTPRedirectHandler automatically deals with HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler deals with digest authentication. urlopen(url, data=None) -- basic usage is that same as original urllib. pass the url and optionally data to post to an HTTP URL, and get a file-like object back. One difference is that you can also pass a Request instance instead of URL. Raises a URLError (subclass of IOError); for HTTP errors, raises an HTTPError, which can also be treated as a valid response. build_opener -- function that creates a new OpenerDirector instance. will install the default handlers. accepts one or more Handlers as arguments, either instances or Handler classes that it will instantiate. if one of the argument is a subclass of the default handler, the argument will be installed instead of the default. install_opener -- installs a new opener as the default opener. objects of interest: OpenerDirector -- Request -- an object that encapsulates the state of a request. the state can be a simple as the URL. it can also include extra HTTP headers, e.g. a User-Agent. BaseHandler -- exceptions: URLError-- a subclass of IOError, individual protocols have their own specific subclass HTTPError-- also a valid HTTP response, so you can treat an HTTP error as an exceptional event or valid response internals: BaseHandler and parent _call_chain conventions Example usage: import urllib2 # set up authentication info authinfo = urllib2.HTTPBasicAuthHandler() authinfo.add_password('realm', 'host', 'username', 'password') proxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"}) # build a new opener that adds authentication and caching FTP handlers opener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler) # install it urllib2.install_opener(opener) f = urllib2.urlopen('http://www.python.org/') """ # XXX issues: # If an authentication error handler that tries to perform # authentication for some reason but fails, how should the error be # signalled? The client needs to know the HTTP error code. But if # the handler knows that the problem was, e.g., that it didn't know # that hash algo that requested in the challenge, it would be good to # pass that information along to the client, too. # XXX to do: # name! # documentation (getting there) # complex proxies # abstract factory for opener # ftp errors aren't handled cleanly # gopher can return a socket.error # check digest against correct (i.e. non-apache) implementation import base64 import ftplib import gopherlib import httplib import inspect import md5 import mimetypes import mimetools import os import posixpath import random import re import sha import socket import sys import time import urlparse import bisect import cookielib try: from cStringIO import StringIO except ImportError: from StringIO import StringIO # not sure how many of these need to be gotten rid of from urllib import (unwrap, unquote, splittype, splithost, addinfourl, splitport, splitgophertype, splitquery, splitattr, ftpwrapper, noheaders, splituser, splitpasswd, splitvalue) # support for FileHandler, proxies via environment variables from urllib import localhost, url2pathname, getproxies __version__ = "2.4" _opener = None def urlopen(url, data=None): global _opener if _opener is None: _opener = build_opener() return _opener.open(url, data) def install_opener(opener): global _opener _opener = opener # do these error classes make sense? # make sure all of the IOError stuff is overridden. we just want to be # subtypes. class URLError(IOError): # URLError is a sub-type of IOError, but it doesn't share any of # the implementation. need to override __init__ and __str__. # It sets self.args for compatibility with other EnvironmentError # subclasses, but args doesn't have the typical format with errno in # slot 0 and strerror in slot 1. This may be better than nothing. def __init__(self, reason): self.args = reason, self.reason = reason def __str__(self): return '<urlopen error %s>' % self.reason class HTTPError(URLError, addinfourl): """Raised when HTTP error occurs, but also acts like non-error return""" __super_init = addinfourl.__init__ def __init__(self, url, code, msg, hdrs, fp): self.code = code self.msg = msg self.hdrs = hdrs self.fp = fp self.filename = url # The addinfourl classes depend on fp being a valid file # object. In some cases, the HTTPError may not have a valid # file object. If this happens, the simplest workaround is to # not initialize the base classes. if fp is not None: self.__super_init(fp, hdrs, url) def __str__(self): return 'HTTP Error %s: %s' % (self.code, self.msg) class GopherError(URLError): pass class Request: def __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False): # unwrap('<URL:type://host/path>') --> 'type://host/path' self.__original = unwrap(url) self.type = None # self.__r_type is what's left after doing the splittype self.host = None self.port = None self.data = data self.headers = {} for key, value in headers.items(): self.add_header(key, value) self.unredirected_hdrs = {} if origin_req_host is None: origin_req_host = cookielib.request_host(self) self.origin_req_host = origin_req_host self.unverifiable = unverifiable def __getattr__(self, attr): # XXX this is a fallback mechanism to guard against these # methods getting called in a non-standard order. this may be # too complicated and/or unnecessary. # XXX should the __r_XXX attributes be public? if attr[:12] == '_Request__r_': name = attr[12:] if hasattr(Request, 'get_' + name): getattr(self, 'get_' + name)() return getattr(self, attr) raise AttributeError, attr def get_method(self): if self.has_data(): return "POST" else: return "GET" # XXX these helper methods are lame def add_data(self, data): self.data = data def has_data(self): return self.data is not None def get_data(self): return self.data def get_full_url(self): return self.__original def get_type(self): if self.type is None: self.type, self.__r_type = splittype(self.__original) if self.type is None: raise ValueError, "unknown url type: %s" % self.__original return self.type def get_host(self): if self.host is None: self.host, self.__r_host = splithost(self.__r_type) if self.host: self.host = unquote(self.host) return self.host def get_selector(self): return self.__r_host def set_proxy(self, host, type): self.host, self.type = host, type self.__r_host = self.__original def get_origin_req_host(self): return self.origin_req_host def is_unverifiable(self): return self.unverifiable def add_header(self, key, val): # useful for something like authentication self.headers[key.capitalize()] = val def add_unredirected_header(self, key, val): # will not be added to a redirected request self.unredirected_hdrs[key.capitalize()] = val def has_header(self, header_name): return (header_name in self.headers or header_name in self.unredirected_hdrs) def get_header(self, header_name, default=None): return self.headers.get( header_name, self.unredirected_hdrs.get(header_name, default)) def header_items(self): hdrs = self.unredirected_hdrs.copy() hdrs.update(self.headers) return hdrs.items() class OpenerDirector: def __init__(self): server_version = "Python-urllib/%s" % __version__ self.addheaders = [('User-agent', server_version)] # manage the individual handlers self.handlers = [] self.handle_open = {} self.handle_error = {} self.process_response = {} self.process_request = {} def add_handler(self, handler): added = False for meth in dir(handler): i = meth.find("_") protocol = meth[:i] condition = meth[i+1:] if condition.startswith("error"): j = condition.find("_") + i + 1 kind = meth[j+1:] try: kind = int(kind) except ValueError: pass lookup = self.handle_error.get(protocol, {}) self.handle_error[protocol] = lookup elif condition == "open": kind = protocol lookup = getattr(self, "handle_"+condition) elif condition in ["response", "request"]: kind = protocol lookup = getattr(self, "process_"+condition) else: continue handlers = lookup.setdefault(kind, []) if handlers: bisect.insort(handlers, handler) else: handlers.append(handler) added = True if added: # XXX why does self.handlers need to be sorted? bisect.insort(self.handlers, handler) handler.add_parent(self) def close(self): # Only exists for backwards compatibility. pass def _call_chain(self, chain, kind, meth_name, *args): # XXX raise an exception if no one else should try to handle # this url. return None if you can't but someone else could. handlers = chain.get(kind, ()) for handler in handlers: func = getattr(handler, meth_name) result = func(*args) if result is not None: return result def open(self, fullurl, data=None): # accept a URL or a Request object if isinstance(fullurl, basestring): req = Request(fullurl, data) else: req = fullurl if data is not None: req.add_data(data) protocol = req.get_type() # pre-process request meth_name = protocol+"_request" for processor in self.process_request.get(protocol, []): meth = getattr(processor, meth_name) req = meth(req) response = self._open(req, data) # post-process response meth_name = protocol+"_response" for processor in self.process_response.get(protocol, []): meth = getattr(processor, meth_name) response = meth(req, response) return response def _open(self, req, data=None): result = self._call_chain(self.handle_open, 'default', 'default_open', req) if result: return result protocol = req.get_type() result = self._call_chain(self.handle_open, protocol, protocol + '_open', req) if result: return result return self._call_chain(self.handle_open, 'unknown', 'unknown_open', req) def error(self, proto, *args): if proto in ['http', 'https']: # XXX http[s] protocols are special-cased dict = self.handle_error['http'] # https is not different than http proto = args[2] # YUCK! meth_name = 'http_error_%s' % proto http_err = 1 orig_args = args else: dict = self.handle_error meth_name = proto + '_error' http_err = 0 args = (dict, proto, meth_name) + args result = self._call_chain(*args) if result: return result if http_err: args = (dict, 'default', 'http_error_default') + orig_args return self._call_chain(*args) # XXX probably also want an abstract factory that knows when it makes # sense to skip a superclass in favor of a subclass and when it might # make sense to include both def build_opener(*handlers): """Create an opener object from a list of handlers. The opener will use several default handlers, including support for HTTP and FTP. If any of the handlers passed as arguments are subclasses of the default handlers, the default handlers will not be used. """ opener = OpenerDirector() default_classes = [ProxyHandler, UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, HTTPErrorProcessor] if hasattr(httplib, 'HTTPS'): default_classes.append(HTTPSHandler) skip = [] for klass in default_classes: for check in handlers: if inspect.isclass(check): if issubclass(check, klass): skip.append(klass) elif isinstance(check, klass): skip.append(klass) for klass in skip: default_classes.remove(klass) for klass in default_classes: opener.add_handler(klass()) for h in handlers: if inspect.isclass(h): h = h() opener.add_handler(h) return opener class BaseHandler: handler_order = 500 def add_parent(self, parent): self.parent = parent def close(self): # Only exists for backwards compatibility pass def __lt__(self, other): if not hasattr(other, "handler_order"): # Try to preserve the old behavior of having custom classes # inserted after default ones (works only for custom user # classes which are not aware of handler_order). return True return self.handler_order < other.handler_order class HTTPErrorProcessor(BaseHandler): """Process HTTP error responses.""" handler_order = 1000 # after all other processing def http_response(self, request, response): code, msg, hdrs = response.code, response.msg, response.info() if code not in (200, 206): response = self.parent.error( 'http', request, response, code, msg, hdrs) return response https_response = http_response class HTTPDefaultErrorHandler(BaseHandler): def http_error_default(self, req, fp, code, msg, hdrs): raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) class HTTPRedirectHandler(BaseHandler): # maximum number of redirections to any single URL # this is needed because of the state that cookies introduce max_repeats = 4 # maximum total number of redirections (regardless of URL) before # assuming we're in a loop max_redirections = 10 def redirect_request(self, req, fp, code, msg, headers, newurl): """Return a Request or None in response to a redirect. This is called by the http_error_30x methods when a redirection response is received. If a redirection should take place, return a new Request to allow http_error_30x to perform the redirect. Otherwise, raise HTTPError if no-one else should try to handle this url. Return None if you can't but another Handler might. """ m = req.get_method() if (code in (301, 302, 303, 307) and m in ("GET", "HEAD") or code in (301, 302, 303) and m == "POST"): # Strictly (according to RFC 2616), 301 or 302 in response # to a POST MUST NOT cause a redirection without confirmation # from the user (of urllib2, in this case). In practice, # essentially all clients do redirect in this case, so we # do the same. return Request(newurl, headers=req.headers, origin_req_host=req.get_origin_req_host(), unverifiable=True) else: raise HTTPError(req.get_full_url(), code, msg, headers, fp) # Implementation note: To avoid the server sending us into an # infinite loop, the request object needs to track what URLs we # have already seen. Do this by adding a handler-specific # attribute to the Request object. def http_error_302(self, req, fp, code, msg, headers): # Some servers (incorrectly) return multiple Location headers # (so probably same goes for URI). Use first header. if 'location' in headers: newurl = headers.getheaders('location')[0] elif 'uri' in headers: newurl = headers.getheaders('uri')[0] else: return newurl = urlparse.urljoin(req.get_full_url(), newurl) # XXX Probably want to forget about the state of the current # request, although that might interact poorly with other # handlers that also use handler-specific request attributes new = self.redirect_request(req, fp, code, msg, headers, newurl) if new is None: return # loop detection # .redirect_dict has a key url if url was previously visited. if hasattr(req, 'redirect_dict'): visited = new.redirect_dict = req.redirect_dict if (visited.get(newurl, 0) >= self.max_repeats or len(visited) >= self.max_redirections): raise HTTPError(req.get_full_url(), code, self.inf_msg + msg, headers, fp) else: visited = new.redirect_dict = req.redirect_dict = {} visited[newurl] = visited.get(newurl, 0) + 1 # Don't close the fp until we are sure that we won't use it # with HTTPError. fp.read() fp.close() return self.parent.open(new) http_error_301 = http_error_303 = http_error_307 = http_error_302 inf_msg = "The HTTP server returned a redirect error that would " \ "lead to an infinite loop.\n" \ "The last 30x error message was:\n" class ProxyHandler(BaseHandler): # Proxies must be in front handler_order = 100 def __init__(self, proxies=None): if proxies is None: proxies = getproxies() assert hasattr(proxies, 'has_key'), "proxies must be a mapping" self.proxies = proxies for type, url in proxies.items(): setattr(self, '%s_open' % type, lambda r, proxy=url, type=type, meth=self.proxy_open: \ meth(r, proxy, type)) def proxy_open(self, req, proxy, type): orig_type = req.get_type() type, r_type = splittype(proxy) host, XXX = splithost(r_type) if '@' in host: user_pass, host = host.split('@', 1) if ':' in user_pass: user, password = user_pass.split(':', 1) user_pass = base64.encodestring('%s:%s' % (unquote(user), unquote(password))) req.add_header('Proxy-authorization', 'Basic ' + user_pass) host = unquote(host) req.set_proxy(host, type) if orig_type == type: # let other handlers take care of it # XXX this only makes sense if the proxy is before the # other handlers return None else: # need to start over, because the other handlers don't # grok the proxy's URL type return self.parent.open(req) # feature suggested by Duncan Booth # XXX custom is not a good name class CustomProxy: # either pass a function to the constructor or override handle def __init__(self, proto, func=None, proxy_addr=None): self.proto = proto self.func = func self.addr = proxy_addr def handle(self, req): if self.func and self.func(req): return 1 def get_proxy(self): return self.addr class CustomProxyHandler(BaseHandler): # Proxies must be in front handler_order = 100 def __init__(self, *proxies): self.proxies = {} def proxy_open(self, req): proto = req.get_type() try: proxies = self.proxies[proto] except KeyError: return None for p in proxies: if p.handle(req): req.set_proxy(p.get_proxy()) return self.parent.open(req) return None def do_proxy(self, p, req): return self.parent.open(req) def add_proxy(self, cpo): if cpo.proto in self.proxies: self.proxies[cpo.proto].append(cpo) else: self.proxies[cpo.proto] = [cpo] class HTTPPasswordMgr: def __init__(self): self.passwd = {} def add_password(self, realm, uri, user, passwd): # uri could be a single URI or a sequence if isinstance(uri, basestring): uri = [uri] uri = tuple(map(self.reduce_uri, uri)) if not realm in self.passwd: self.passwd[realm] = {} self.passwd[realm][uri] = (user, passwd) def find_user_password(self, realm, authuri): domains = self.passwd.get(realm, {}) authuri = self.reduce_uri(authuri) for uris, authinfo in domains.iteritems(): for uri in uris: if self.is_suburi(uri, authuri): return authinfo return None, None def reduce_uri(self, uri): """Accept netloc or URI and extract only the netloc and path""" parts = urlparse.urlparse(uri) if parts[1]: return parts[1], parts[2] or '/' else: return parts[2], '/' def is_suburi(self, base, test): """Check if test is below base in a URI tree Both args must be URIs in reduced form. """ if base == test: return True if base[0] != test[0]: return False common = posixpath.commonprefix((base[1], test[1])) if len(common) == len(base[1]): return True return False class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): def find_user_password(self, realm, authuri): user, password = HTTPPasswordMgr.find_user_password(self, realm, authuri) if user is not None: return user, password return HTTPPasswordMgr.find_user_password(self, None, authuri) class AbstractBasicAuthHandler: rx = re.compile('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', re.I) # XXX there can actually be multiple auth-schemes in a # www-authenticate header. should probably be a lot more careful # in parsing them to extract multiple alternatives def __init__(self, password_mgr=None): if password_mgr is None: password_mgr = HTTPPasswordMgr() self.passwd = password_mgr self.add_password = self.passwd.add_password def http_error_auth_reqed(self, authreq, host, req, headers): # XXX could be multiple headers authreq = headers.get(authreq, None) if authreq: mo = AbstractBasicAuthHandler.rx.search(authreq) if mo: scheme, realm = mo.groups() if scheme.lower() == 'basic': return self.retry_http_basic_auth(host, req, realm) def retry_http_basic_auth(self, host, req, realm): user,pw = self.passwd.find_user_password(realm, host) if pw is not None: raw = "%s:%s" % (user, pw) auth = 'Basic %s' % base64.encodestring(raw).strip() if req.headers.get(self.auth_header, None) == auth: return None req.add_header(self.auth_header, auth) return self.parent.open(req) else: return None class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): auth_header = 'Authorization' def http_error_401(self, req, fp, code, msg, headers): host = urlparse.urlparse(req.get_full_url())[1] return self.http_error_auth_reqed('www-authenticate', host, req, headers) class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): auth_header = 'Proxy-authorization' def http_error_407(self, req, fp, code, msg, headers): host = req.get_host() return self.http_error_auth_reqed('proxy-authenticate', host, req, headers) def randombytes(n): """Return n random bytes.""" # Use /dev/urandom if it is available. Fall back to random module # if not. It might be worthwhile to extend this function to use # other platform-specific mechanisms for getting random bytes. if os.path.exists("/dev/urandom"): f = open("/dev/urandom") s = f.read(n) f.close() return s else: L = [chr(random.randrange(0, 256)) for i in range(n)] return "".join(L) class AbstractDigestAuthHandler: # Digest authentication is specified in RFC 2617. # XXX The client does not inspect the Authentication-Info header # in a successful response. # XXX It should be possible to test this implementation against # a mock server that just generates a static set of challenges. # XXX qop="auth-int" supports is shaky def __init__(self, passwd=None): if passwd is None: passwd = HTTPPasswordMgr() self.passwd = passwd self.add_password = self.passwd.add_password self.retried = 0 self.nonce_count = 0 def reset_retry_count(self): self.retried = 0 def http_error_auth_reqed(self, auth_header, host, req, headers): authreq = headers.get(auth_header, None) if self.retried > 5: # Don't fail endlessly - if we failed once, we'll probably # fail a second time. Hm. Unless the Password Manager is # prompting for the information. Crap. This isn't great # but it's better than the current 'repeat until recursion # depth exceeded' approach <wink> raise HTTPError(req.get_full_url(), 401, "digest auth failed", headers, None) else: self.retried += 1 if authreq: scheme = authreq.split()[0] if scheme.lower() == 'digest': return self.retry_http_digest_auth(req, authreq) else: raise ValueError("AbstractDigestAuthHandler doesn't know " "about %s"%(scheme)) def retry_http_digest_auth(self, req, auth): token, challenge = auth.split(' ', 1) chal = parse_keqv_list(parse_http_list(challenge)) auth = self.get_authorization(req, chal) if auth: auth_val = 'Digest %s' % auth if req.headers.get(self.auth_header, None) == auth_val: return None req.add_header(self.auth_header, auth_val) resp = self.parent.open(req) return resp def get_cnonce(self, nonce): # The cnonce-value is an opaque # quoted string value provided by the client and used by both client # and server to avoid chosen plaintext attacks, to provide mutual # authentication, and to provide some message integrity protection. # This isn't a fabulous effort, but it's probably Good Enough. dig = sha.new("%s:%s:%s:%s" % (self.nonce_count, nonce, time.ctime(), randombytes(8))).hexdigest() return dig[:16] def get_authorization(self, req, chal): try: realm = chal['realm'] nonce = chal['nonce'] qop = chal.get('qop') algorithm = chal.get('algorithm', 'MD5') # mod_digest doesn't send an opaque, even though it isn't # supposed to be optional opaque = chal.get('opaque', None) except KeyError: return None H, KD = self.get_algorithm_impls(algorithm) if H is None: return None user, pw = self.passwd.find_user_password(realm, req.get_full_url()) if user is None: return None # XXX not implemented yet if req.has_data(): entdig = self.get_entity_digest(req.get_data(), chal) else: entdig = None A1 = "%s:%s:%s" % (user, realm, pw) A2 = "%s:%s" % (req.get_method(), # XXX selector: what about proxies and full urls req.get_selector()) if qop == 'auth': self.nonce_count += 1 ncvalue = '%08x' % self.nonce_count cnonce = self.get_cnonce(nonce) noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2)) respdig = KD(H(A1), noncebit) elif qop is None: respdig = KD(H(A1), "%s:%s" % (nonce, H(A2))) else: # XXX handle auth-int. pass # XXX should the partial digests be encoded too? base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \ 'response="%s"' % (user, realm, nonce, req.get_selector(), respdig) if opaque: base = base + ', opaque="%s"' % opaque if entdig: base = base + ', digest="%s"' % entdig if algorithm != 'MD5': base = base + ', algorithm="%s"' % algorithm if qop: base = base + ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce) return base def get_algorithm_impls(self, algorithm): # lambdas assume digest modules are imported at the top level if algorithm == 'MD5': H = lambda x: md5.new(x).hexdigest() elif algorithm == 'SHA': H = lambda x: sha.new(x).hexdigest() # XXX MD5-sess KD = lambda s, d: H("%s:%s" % (s, d)) return H, KD def get_entity_digest(self, data, chal): # XXX not implemented yet return None class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): """An authentication protocol defined by RFC 2069 Digest authentication improves on basic authentication because it does not transmit passwords in the clear. """ auth_header = 'Authorization' def http_error_401(self, req, fp, code, msg, headers): host = urlparse.urlparse(req.get_full_url())[1] retry = self.http_error_auth_reqed('www-authenticate', host, req, headers) self.reset_retry_count() return retry class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): auth_header = 'Proxy-Authorization' def http_error_407(self, req, fp, code, msg, headers): host = req.get_host() retry = self.http_error_auth_reqed('proxy-authenticate', host, req, headers) self.reset_retry_count() return retry class AbstractHTTPHandler(BaseHandler): def __init__(self, debuglevel=0): self._debuglevel = debuglevel def set_http_debuglevel(self, level): self._debuglevel = level def do_request_(self, request): host = request.get_host() if not host: raise URLError('no host given') if request.has_data(): # POST data = request.get_data() if not request.has_header('Content-type'): request.add_unredirected_header( 'Content-type', 'application/x-www-form-urlencoded') if not request.has_header('Content-length'): request.add_unredirected_header( 'Content-length', '%d' % len(data)) scheme, sel = splittype(request.get_selector()) sel_host, sel_path = splithost(sel) if not request.has_header('Host'): request.add_unredirected_header('Host', sel_host or host) for name, value in self.parent.addheaders: name = name.capitalize() if not request.has_header(name): request.add_unredirected_header(name, value) return request def do_open(self, http_class, req): """Return an addinfourl object for the request, using http_class. http_class must implement the HTTPConnection API from httplib. The addinfourl return value is a file-like object. It also has methods and attributes including: - info(): return a mimetools.Message object for the headers - geturl(): return the original request URL - code: HTTP status code """ host = req.get_host() if not host: raise URLError('no host given') h = http_class(host) # will parse host:port h.set_debuglevel(self._debuglevel) headers = dict(req.headers) headers.update(req.unredirected_hdrs) # We want to make an HTTP/1.1 request, but the addinfourl # class isn't prepared to deal with a persistent connection. # It will try to read all remaining data from the socket, # which will block while the server waits for the next request. # So make sure the connection gets closed after the (only) # request. headers["Connection"] = "close" try: h.request(req.get_method(), req.get_selector(), req.data, headers) r = h.getresponse() except socket.error, err: # XXX what error? raise URLError(err) # Pick apart the HTTPResponse object to get the addinfourl # object initialized properly. # Wrap the HTTPResponse object in socket's file object adapter # for Windows. That adapter calls recv(), so delegate recv() # to read(). This weird wrapping allows the returned object to # have readline() and readlines() methods. # XXX It might be better to extract the read buffering code # out of socket._fileobject() and into a base class. r.recv = r.read fp = socket._fileobject(r) resp = addinfourl(fp, r.msg, req.get_full_url()) resp.code = r.status resp.msg = r.reason return resp class HTTPHandler(AbstractHTTPHandler): def http_open(self, req): return self.do_open(httplib.HTTPConnection, req) http_request = AbstractHTTPHandler.do_request_ if hasattr(httplib, 'HTTPS'): class HTTPSHandler(AbstractHTTPHandler): def https_open(self, req): return self.do_open(httplib.HTTPSConnection, req) https_request = AbstractHTTPHandler.do_request_ class HTTPCookieProcessor(BaseHandler): def __init__(self, cookiejar=None): if cookiejar is None: cookiejar = cookielib.CookieJar() self.cookiejar = cookiejar def http_request(self, request): self.cookiejar.add_cookie_header(request) return request def http_response(self, request, response): self.cookiejar.extract_cookies(response, request) return response https_request = http_request https_response = http_response class UnknownHandler(BaseHandler): def unknown_open(self, req): type = req.get_type() raise URLError('unknown url type: %s' % type) def parse_keqv_list(l): """Parse list of key=value strings where keys are not duplicated.""" parsed = {} for elt in l: k, v = elt.split('=', 1) if v[0] == '"' and v[-1] == '"': v = v[1:-1] parsed[k] = v return parsed def parse_http_list(s): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. """ # XXX this function could probably use more testing list = [] end = len(s) i = 0 inquote = 0 start = 0 while i < end: cur = s[i:] c = cur.find(',') q = cur.find('"') if c == -1: list.append(s[start:]) break if q == -1: if inquote: raise ValueError, "unbalanced quotes" else: list.append(s[start:i+c]) i = i + c + 1 continue if inquote: if q < c: list.append(s[start:i+c]) i = i + c + 1 start = i inquote = 0 else: i = i + q else: if c < q: list.append(s[start:i+c]) i = i + c + 1 start = i else: inquote = 1 i = i + q + 1 return map(lambda x: x.strip(), list) class FileHandler(BaseHandler): # Use local file or FTP depending on form of URL def file_open(self, req): url = req.get_selector() if url[:2] == '//' and url[2:3] != '/': req.type = 'ftp' return self.parent.open(req) else: return self.open_local_file(req) # names for the localhost names = None def get_names(self): if FileHandler.names is None: FileHandler.names = (socket.gethostbyname('localhost'), socket.gethostbyname(socket.gethostname())) return FileHandler.names # not entirely sure what the rules are here def open_local_file(self, req): import email.Utils host = req.get_host() file = req.get_selector() localfile = url2pathname(file) stats = os.stat(localfile) size = stats.st_size modified = email.Utils.formatdate(stats.st_mtime, usegmt=True) mtype = mimetypes.guess_type(file)[0] headers = mimetools.Message(StringIO( 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified))) if host: host, port = splitport(host) if not host or \ (not port and socket.gethostbyname(host) in self.get_names()): return addinfourl(open(localfile, 'rb'), headers, 'file:'+file) raise URLError('file not on local host') class FTPHandler(BaseHandler): def ftp_open(self, req): host = req.get_host() if not host: raise IOError, ('ftp error', 'no host given') host, port = splitport(host) if port is None: port = ftplib.FTP_PORT else: port = int(port) # username/password handling user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = unquote(host) user = unquote(user or '') passwd = unquote(passwd or '') try: host = socket.gethostbyname(host) except socket.error, msg: raise URLError(msg) path, attrs = splitattr(req.get_selector()) dirs = path.split('/') dirs = map(unquote, dirs) dirs, file = dirs[:-1], dirs[-1] if dirs and not dirs[0]: dirs = dirs[1:] try: fw = self.connect_ftp(user, passwd, host, port, dirs) type = file and 'I' or 'D' for attr in attrs: attr, value = splitvalue(attr) if attr.lower() == 'type' and \ value in ('a', 'A', 'i', 'I', 'd', 'D'): type = value.upper() fp, retrlen = fw.retrfile(file, type) headers = "" mtype = mimetypes.guess_type(req.get_full_url())[0] if mtype: headers += "Content-type: %s\n" % mtype if retrlen is not None and retrlen >= 0: headers += "Content-length: %d\n" % retrlen sf = StringIO(headers) headers = mimetools.Message(sf) return addinfourl(fp, headers, req.get_full_url()) except ftplib.all_errors, msg: raise IOError, ('ftp error', msg), sys.exc_info()[2] def connect_ftp(self, user, passwd, host, port, dirs): fw = ftpwrapper(user, passwd, host, port, dirs) ## fw.ftp.set_debuglevel(1) return fw class CacheFTPHandler(FTPHandler): # XXX would be nice to have pluggable cache strategies # XXX this stuff is definitely not thread safe def __init__(self): self.cache = {} self.timeout = {} self.soonest = 0 self.delay = 60 self.max_conns = 16 def setTimeout(self, t): self.delay = t def setMaxConns(self, m): self.max_conns = m def connect_ftp(self, user, passwd, host, port, dirs): key = user, host, port, '/'.join(dirs) if key in self.cache: self.timeout[key] = time.time() + self.delay else: self.cache[key] = ftpwrapper(user, passwd, host, port, dirs) self.timeout[key] = time.time() + self.delay self.check_cache() return self.cache[key] def check_cache(self): # first check for old ones t = time.time() if self.soonest <= t: for k, v in self.timeout.items(): if v < t: self.cache[k].close() del self.cache[k] del self.timeout[k] self.soonest = min(self.timeout.values()) # then check the size if len(self.cache) == self.max_conns: for k, v in self.timeout.items(): if v == self.soonest: del self.cache[k] del self.timeout[k] break self.soonest = min(self.timeout.values()) class GopherHandler(BaseHandler): def gopher_open(self, req): host = req.get_host() if not host: raise GopherError('no host given') host = unquote(host) selector = req.get_selector() type, selector = splitgophertype(selector) selector, query = splitquery(selector) selector = unquote(selector) if query: query = unquote(query) fp = gopherlib.send_query(selector, query, host) else: fp = gopherlib.send_selector(selector, host) return addinfourl(fp, noheaders(), req.get_full_url()) #bleck! don't use this yet class OpenerFactory: default_handlers = [UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler] handlers = [] replacement_handlers = [] def add_handler(self, h): self.handlers = self.handlers + [h] def replace_handler(self, h): pass def build_opener(self): opener = OpenerDirector() for ph in self.default_handlers: if inspect.isclass(ph): ph = ph() opener.add_handler(ph)
Python
# This file exists as a helper for the test.test_frozen module.
Python
"""A multi-producer, multi-consumer queue.""" from time import time as _time from collections import deque __all__ = ['Empty', 'Full', 'Queue'] class Empty(Exception): "Exception raised by Queue.get(block=0)/get_nowait()." pass class Full(Exception): "Exception raised by Queue.put(block=0)/put_nowait()." pass class Queue: def __init__(self, maxsize=0): """Initialize a queue object with a given maximum size. If maxsize is <= 0, the queue size is infinite. """ try: import threading except ImportError: import dummy_threading as threading self._init(maxsize) # mutex must be held whenever the queue is mutating. All methods # that acquire mutex must release it before returning. mutex # is shared between the two conditions, so acquiring and # releasing the conditions also acquires and releases mutex. self.mutex = threading.Lock() # Notify not_empty whenever an item is added to the queue; a # thread waiting to get is notified then. self.not_empty = threading.Condition(self.mutex) # Notify not_full whenever an item is removed from the queue; # a thread waiting to put is notified then. self.not_full = threading.Condition(self.mutex) def qsize(self): """Return the approximate size of the queue (not reliable!).""" self.mutex.acquire() n = self._qsize() self.mutex.release() return n def empty(self): """Return True if the queue is empty, False otherwise (not reliable!).""" self.mutex.acquire() n = self._empty() self.mutex.release() return n def full(self): """Return True if the queue is full, False otherwise (not reliable!).""" self.mutex.acquire() n = self._full() self.mutex.release() return n def put(self, item, block=True, timeout=None): """Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Full exception if no free slot was available within that time. Otherwise ('block' is false), put an item on the queue if a free slot is immediately available, else raise the Full exception ('timeout' is ignored in that case). """ self.not_full.acquire() try: if not block: if self._full(): raise Full elif timeout is None: while self._full(): self.not_full.wait() else: if timeout < 0: raise ValueError("'timeout' must be a positive number") endtime = _time() + timeout while self._full(): remaining = endtime - _time() if remaining <= 0.0: raise Full self.not_full.wait(remaining) self._put(item) self.not_empty.notify() finally: self.not_full.release() def put_nowait(self, item): """Put an item into the queue without blocking. Only enqueue the item if a free slot is immediately available. Otherwise raise the Full exception. """ return self.put(item, False) def get(self, block=True, timeout=None): """Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Empty exception if no item was available within that time. Otherwise ('block' is false), return an item if one is immediately available, else raise the Empty exception ('timeout' is ignored in that case). """ self.not_empty.acquire() try: if not block: if self._empty(): raise Empty elif timeout is None: while self._empty(): self.not_empty.wait() else: if timeout < 0: raise ValueError("'timeout' must be a positive number") endtime = _time() + timeout while self._empty(): remaining = endtime - _time() if remaining <= 0.0: raise Empty self.not_empty.wait(remaining) item = self._get() self.not_full.notify() return item finally: self.not_empty.release() def get_nowait(self): """Remove and return an item from the queue without blocking. Only get an item if one is immediately available. Otherwise raise the Empty exception. """ return self.get(False) # Override these methods to implement other queue organizations # (e.g. stack or priority queue). # These will only be called with appropriate locks held # Initialize the queue representation def _init(self, maxsize): self.maxsize = maxsize self.queue = deque() def _qsize(self): return len(self.queue) # Check whether the queue is empty def _empty(self): return not self.queue # Check whether the queue is full def _full(self): return self.maxsize > 0 and len(self.queue) == self.maxsize # Put a new item in the queue def _put(self, item): self.queue.append(item) # Get an item from the queue def _get(self): return self.queue.popleft()
Python
"""Classes for manipulating audio devices (currently only for Sun and SGI)""" __all__ = ["error","AudioDev"] class error(Exception): pass class Play_Audio_sgi: # Private instance variables ## if 0: access frameratelist, nchannelslist, sampwidthlist, oldparams, \ ## params, config, inited_outrate, inited_width, \ ## inited_nchannels, port, converter, classinited: private classinited = 0 frameratelist = nchannelslist = sampwidthlist = None def initclass(self): import AL self.frameratelist = [ (48000, AL.RATE_48000), (44100, AL.RATE_44100), (32000, AL.RATE_32000), (22050, AL.RATE_22050), (16000, AL.RATE_16000), (11025, AL.RATE_11025), ( 8000, AL.RATE_8000), ] self.nchannelslist = [ (1, AL.MONO), (2, AL.STEREO), (4, AL.QUADRO), ] self.sampwidthlist = [ (1, AL.SAMPLE_8), (2, AL.SAMPLE_16), (3, AL.SAMPLE_24), ] self.classinited = 1 def __init__(self): import al, AL if not self.classinited: self.initclass() self.oldparams = [] self.params = [AL.OUTPUT_RATE, 0] self.config = al.newconfig() self.inited_outrate = 0 self.inited_width = 0 self.inited_nchannels = 0 self.converter = None self.port = None return def __del__(self): if self.port: self.stop() if self.oldparams: import al, AL al.setparams(AL.DEFAULT_DEVICE, self.oldparams) self.oldparams = [] def wait(self): if not self.port: return import time while self.port.getfilled() > 0: time.sleep(0.1) self.stop() def stop(self): if self.port: self.port.closeport() self.port = None if self.oldparams: import al, AL al.setparams(AL.DEFAULT_DEVICE, self.oldparams) self.oldparams = [] def setoutrate(self, rate): for (raw, cooked) in self.frameratelist: if rate == raw: self.params[1] = cooked self.inited_outrate = 1 break else: raise error, 'bad output rate' def setsampwidth(self, width): for (raw, cooked) in self.sampwidthlist: if width == raw: self.config.setwidth(cooked) self.inited_width = 1 break else: if width == 0: import AL self.inited_width = 0 self.config.setwidth(AL.SAMPLE_16) self.converter = self.ulaw2lin else: raise error, 'bad sample width' def setnchannels(self, nchannels): for (raw, cooked) in self.nchannelslist: if nchannels == raw: self.config.setchannels(cooked) self.inited_nchannels = 1 break else: raise error, 'bad # of channels' def writeframes(self, data): if not (self.inited_outrate and self.inited_nchannels): raise error, 'params not specified' if not self.port: import al, AL self.port = al.openport('Python', 'w', self.config) self.oldparams = self.params[:] al.getparams(AL.DEFAULT_DEVICE, self.oldparams) al.setparams(AL.DEFAULT_DEVICE, self.params) if self.converter: data = self.converter(data) self.port.writesamps(data) def getfilled(self): if self.port: return self.port.getfilled() else: return 0 def getfillable(self): if self.port: return self.port.getfillable() else: return self.config.getqueuesize() # private methods ## if 0: access *: private def ulaw2lin(self, data): import audioop return audioop.ulaw2lin(data, 2) class Play_Audio_sun: ## if 0: access outrate, sampwidth, nchannels, inited_outrate, inited_width, \ ## inited_nchannels, converter: private def __init__(self): self.outrate = 0 self.sampwidth = 0 self.nchannels = 0 self.inited_outrate = 0 self.inited_width = 0 self.inited_nchannels = 0 self.converter = None self.port = None return def __del__(self): self.stop() def setoutrate(self, rate): self.outrate = rate self.inited_outrate = 1 def setsampwidth(self, width): self.sampwidth = width self.inited_width = 1 def setnchannels(self, nchannels): self.nchannels = nchannels self.inited_nchannels = 1 def writeframes(self, data): if not (self.inited_outrate and self.inited_width and self.inited_nchannels): raise error, 'params not specified' if not self.port: import sunaudiodev, SUNAUDIODEV self.port = sunaudiodev.open('w') info = self.port.getinfo() info.o_sample_rate = self.outrate info.o_channels = self.nchannels if self.sampwidth == 0: info.o_precision = 8 self.o_encoding = SUNAUDIODEV.ENCODING_ULAW # XXX Hack, hack -- leave defaults else: info.o_precision = 8 * self.sampwidth info.o_encoding = SUNAUDIODEV.ENCODING_LINEAR self.port.setinfo(info) if self.converter: data = self.converter(data) self.port.write(data) def wait(self): if not self.port: return self.port.drain() self.stop() def stop(self): if self.port: self.port.flush() self.port.close() self.port = None def getfilled(self): if self.port: return self.port.obufcount() else: return 0 ## # Nobody remembers what this method does, and it's broken. :-( ## def getfillable(self): ## return BUFFERSIZE - self.getfilled() def AudioDev(): # Dynamically try to import and use a platform specific module. try: import al except ImportError: try: import sunaudiodev return Play_Audio_sun() except ImportError: try: import Audio_mac except ImportError: raise error, 'no audio device' else: return Audio_mac.Play_Audio_mac() else: return Play_Audio_sgi() def test(fn = None): import sys if sys.argv[1:]: fn = sys.argv[1] else: fn = 'f:just samples:just.aif' import aifc af = aifc.open(fn, 'r') print fn, af.getparams() p = AudioDev() p.setoutrate(af.getframerate()) p.setsampwidth(af.getsampwidth()) p.setnchannels(af.getnchannels()) BUFSIZ = af.getframerate()/af.getsampwidth()/af.getnchannels() while 1: data = af.readframes(BUFSIZ) if not data: break print len(data) p.writeframes(data) p.wait() if __name__ == '__main__': test()
Python
"""Create new objects of various types. Deprecated. This module is no longer required except for backward compatibility. Objects of most types can now be created by calling the type object. """ from types import ClassType as classobj from types import FunctionType as function from types import InstanceType as instance from types import MethodType as instancemethod from types import ModuleType as module # CodeType is not accessible in restricted execution mode try: from types import CodeType as code except ImportError: pass
Python
"""Faux ``threading`` version using ``dummy_thread`` instead of ``thread``. The module ``_dummy_threading`` is added to ``sys.modules`` in order to not have ``threading`` considered imported. Had ``threading`` been directly imported it would have made all subsequent imports succeed regardless of whether ``thread`` was available which is not desired. :Author: Brett Cannon :Contact: brett@python.org XXX: Try to get rid of ``_dummy_threading``. """ from sys import modules as sys_modules import dummy_thread # Declaring now so as to not have to nest ``try``s to get proper clean-up. holding_thread = False holding_threading = False holding__threading_local = False try: # Could have checked if ``thread`` was not in sys.modules and gone # a different route, but decided to mirror technique used with # ``threading`` below. if 'thread' in sys_modules: held_thread = sys_modules['thread'] holding_thread = True # Must have some module named ``thread`` that implements its API # in order to initially import ``threading``. sys_modules['thread'] = sys_modules['dummy_thread'] if 'threading' in sys_modules: # If ``threading`` is already imported, might as well prevent # trying to import it more than needed by saving it if it is # already imported before deleting it. held_threading = sys_modules['threading'] holding_threading = True del sys_modules['threading'] if '_threading_local' in sys_modules: # If ``_threading_local`` is already imported, might as well prevent # trying to import it more than needed by saving it if it is # already imported before deleting it. held__threading_local = sys_modules['_threading_local'] holding__threading_local = True del sys_modules['_threading_local'] import threading # Need a copy of the code kept somewhere... sys_modules['_dummy_threading'] = sys_modules['threading'] del sys_modules['threading'] sys_modules['_dummy__threading_local'] = sys_modules['_threading_local'] del sys_modules['_threading_local'] from _dummy_threading import * from _dummy_threading import __all__ finally: # Put back ``threading`` if we overwrote earlier if holding_threading: sys_modules['threading'] = held_threading del held_threading del holding_threading # Put back ``_threading_local`` if we overwrote earlier if holding__threading_local: sys_modules['_threading_local'] = held__threading_local del held__threading_local del holding__threading_local # Put back ``thread`` if we overwrote, else del the entry we made if holding_thread: sys_modules['thread'] = held_thread del held_thread else: del sys_modules['thread'] del holding_thread del dummy_thread del sys_modules
Python
"""Thread-local objects (Note that this module provides a Python version of thread threading.local class. Depending on the version of Python you're using, there may be a faster one available. You should always import the local class from threading.) Thread-local objects support the management of thread-local data. If you have data that you want to be local to a thread, simply create a thread-local object and use its attributes: >>> mydata = local() >>> mydata.number = 42 >>> mydata.number 42 You can also access the local-object's dictionary: >>> mydata.__dict__ {'number': 42} >>> mydata.__dict__.setdefault('widgets', []) [] >>> mydata.widgets [] What's important about thread-local objects is that their data are local to a thread. If we access the data in a different thread: >>> log = [] >>> def f(): ... items = mydata.__dict__.items() ... items.sort() ... log.append(items) ... mydata.number = 11 ... log.append(mydata.number) >>> import threading >>> thread = threading.Thread(target=f) >>> thread.start() >>> thread.join() >>> log [[], 11] we get different data. Furthermore, changes made in the other thread don't affect data seen in this thread: >>> mydata.number 42 Of course, values you get from a local object, including a __dict__ attribute, are for whatever thread was current at the time the attribute was read. For that reason, you generally don't want to save these values across threads, as they apply only to the thread they came from. You can create custom local objects by subclassing the local class: >>> class MyLocal(local): ... number = 2 ... initialized = False ... def __init__(self, **kw): ... if self.initialized: ... raise SystemError('__init__ called too many times') ... self.initialized = True ... self.__dict__.update(kw) ... def squared(self): ... return self.number ** 2 This can be useful to support default values, methods and initialization. Note that if you define an __init__ method, it will be called each time the local object is used in a separate thread. This is necessary to initialize each thread's dictionary. Now if we create a local object: >>> mydata = MyLocal(color='red') Now we have a default number: >>> mydata.number 2 an initial color: >>> mydata.color 'red' >>> del mydata.color And a method that operates on the data: >>> mydata.squared() 4 As before, we can access the data in a separate thread: >>> log = [] >>> thread = threading.Thread(target=f) >>> thread.start() >>> thread.join() >>> log [[('color', 'red'), ('initialized', True)], 11] without affecting this thread's data: >>> mydata.number 2 >>> mydata.color Traceback (most recent call last): ... AttributeError: 'MyLocal' object has no attribute 'color' Note that subclasses can define slots, but they are not thread local. They are shared across threads: >>> class MyLocal(local): ... __slots__ = 'number' >>> mydata = MyLocal() >>> mydata.number = 42 >>> mydata.color = 'red' So, the separate thread: >>> thread = threading.Thread(target=f) >>> thread.start() >>> thread.join() affects what we see: >>> mydata.number 11 >>> del mydata """ # Threading import is at end class _localbase(object): __slots__ = '_local__key', '_local__args', '_local__lock' def __new__(cls, *args, **kw): self = object.__new__(cls) key = '_local__key', 'thread.local.' + str(id(self)) object.__setattr__(self, '_local__key', key) object.__setattr__(self, '_local__args', (args, kw)) object.__setattr__(self, '_local__lock', RLock()) if args or kw and (cls.__init__ is object.__init__): raise TypeError("Initialization arguments are not supported") # We need to create the thread dict in anticipation of # __init__ being called, to make sire we don't cal it # again ourselves. dict = object.__getattribute__(self, '__dict__') currentThread().__dict__[key] = dict return self def _patch(self): key = object.__getattribute__(self, '_local__key') d = currentThread().__dict__.get(key) if d is None: d = {} currentThread().__dict__[key] = d object.__setattr__(self, '__dict__', d) # we have a new instance dict, so call out __init__ if we have # one cls = type(self) if cls.__init__ is not object.__init__: args, kw = object.__getattribute__(self, '_local__args') cls.__init__(self, *args, **kw) else: object.__setattr__(self, '__dict__', d) class local(_localbase): def __getattribute__(self, name): lock = object.__getattribute__(self, '_local__lock') lock.acquire() try: _patch(self) return object.__getattribute__(self, name) finally: lock.release() def __setattr__(self, name, value): lock = object.__getattribute__(self, '_local__lock') lock.acquire() try: _patch(self) return object.__setattr__(self, name, value) finally: lock.release() def __delattr__(self, name): lock = object.__getattribute__(self, '_local__lock') lock.acquire() try: _patch(self) return object.__delattr__(self, name) finally: lock.release() def __del__(): threading_enumerate = enumerate __getattribute__ = object.__getattribute__ def __del__(self): key = __getattribute__(self, '_local__key') try: threads = list(threading_enumerate()) except: # if enumerate fails, as it seems to do during # shutdown, we'll skip cleanup under the assumption # that there is nothing to clean up return for thread in threads: try: __dict__ = thread.__dict__ except AttributeError: # Thread is dying, rest in peace continue if key in __dict__: try: del __dict__[key] except KeyError: pass # didn't have anything in this thread return __del__ __del__ = __del__() from threading import currentThread, enumerate, RLock
Python
"""Bisection algorithms.""" def insort_right(a, x, lo=0, hi=None): """Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the right of the rightmost x. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. """ if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 if x < a[mid]: hi = mid else: lo = mid+1 a.insert(lo, x) insort = insort_right # backward compatibility def bisect_right(a, x, lo=0, hi=None): """Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e <= x, and all e in a[i:] have e > x. So if x already appears in the list, i points just beyond the rightmost x already there. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. """ if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 if x < a[mid]: hi = mid else: lo = mid+1 return lo bisect = bisect_right # backward compatibility def insort_left(a, x, lo=0, hi=None): """Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the left of the leftmost x. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. """ if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 if a[mid] < x: lo = mid+1 else: hi = mid a.insert(lo, x) def bisect_left(a, x, lo=0, hi=None): """Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e < x, and all e in a[i:] have e >= x. So if x already appears in the list, i points just before the leftmost x already there. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. """ if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 if a[mid] < x: lo = mid+1 else: hi = mid return lo # Overwrite above definitions with a fast C implementation try: from _bisect import bisect_right, bisect_left, insort_left, insort_right, insort, bisect except ImportError: pass
Python
"""Stuff to parse WAVE files. Usage. Reading WAVE files: f = wave.open(file, 'r') where file is either the name of a file or an open file pointer. The open file pointer must have methods read(), seek(), and close(). When the setpos() and rewind() methods are not used, the seek() method is not necessary. This returns an instance of a class with the following public methods: getnchannels() -- returns number of audio channels (1 for mono, 2 for stereo) getsampwidth() -- returns sample width in bytes getframerate() -- returns sampling frequency getnframes() -- returns number of audio frames getcomptype() -- returns compression type ('NONE' for linear samples) getcompname() -- returns human-readable version of compression type ('not compressed' linear samples) getparams() -- returns a tuple consisting of all of the above in the above order getmarkers() -- returns None (for compatibility with the aifc module) getmark(id) -- raises an error since the mark does not exist (for compatibility with the aifc module) readframes(n) -- returns at most n frames of audio rewind() -- rewind to the beginning of the audio stream setpos(pos) -- seek to the specified position tell() -- return the current position close() -- close the instance (make it unusable) The position returned by tell() and the position given to setpos() are compatible and have nothing to do with the actual position in the file. The close() method is called automatically when the class instance is destroyed. Writing WAVE files: f = wave.open(file, 'w') where file is either the name of a file or an open file pointer. The open file pointer must have methods write(), tell(), seek(), and close(). This returns an instance of a class with the following public methods: setnchannels(n) -- set the number of channels setsampwidth(n) -- set the sample width setframerate(n) -- set the frame rate setnframes(n) -- set the number of frames setcomptype(type, name) -- set the compression type and the human-readable compression type setparams(tuple) -- set all parameters at once tell() -- return current position in output file writeframesraw(data) -- write audio frames without pathing up the file header writeframes(data) -- write audio frames and patch up the file header close() -- patch up the file header and close the output file You should set the parameters before the first writeframesraw or writeframes. The total number of frames does not need to be set, but when it is set to the correct value, the header does not have to be patched up. It is best to first set all parameters, perhaps possibly the compression type, and then write audio frames using writeframesraw. When all frames have been written, either call writeframes('') or close() to patch up the sizes in the header. The close() method is called automatically when the class instance is destroyed. """ import __builtin__ __all__ = ["open", "openfp", "Error"] class Error(Exception): pass WAVE_FORMAT_PCM = 0x0001 _array_fmts = None, 'b', 'h', None, 'l' # Determine endian-ness import struct if struct.pack("h", 1) == "\000\001": big_endian = 1 else: big_endian = 0 from chunk import Chunk class Wave_read: """Variables used in this class: These variables are available to the user though appropriate methods of this class: _file -- the open file with methods read(), close(), and seek() set through the __init__() method _nchannels -- the number of audio channels available through the getnchannels() method _nframes -- the number of audio frames available through the getnframes() method _sampwidth -- the number of bytes per audio sample available through the getsampwidth() method _framerate -- the sampling frequency available through the getframerate() method _comptype -- the AIFF-C compression type ('NONE' if AIFF) available through the getcomptype() method _compname -- the human-readable AIFF-C compression type available through the getcomptype() method _soundpos -- the position in the audio stream available through the tell() method, set through the setpos() method These variables are used internally only: _fmt_chunk_read -- 1 iff the FMT chunk has been read _data_seek_needed -- 1 iff positioned correctly in audio file for readframes() _data_chunk -- instantiation of a chunk class for the DATA chunk _framesize -- size of one frame in the file """ def initfp(self, file): self._convert = None self._soundpos = 0 self._file = Chunk(file, bigendian = 0) if self._file.getname() != 'RIFF': raise Error, 'file does not start with RIFF id' if self._file.read(4) != 'WAVE': raise Error, 'not a WAVE file' self._fmt_chunk_read = 0 self._data_chunk = None while 1: self._data_seek_needed = 1 try: chunk = Chunk(self._file, bigendian = 0) except EOFError: break chunkname = chunk.getname() if chunkname == 'fmt ': self._read_fmt_chunk(chunk) self._fmt_chunk_read = 1 elif chunkname == 'data': if not self._fmt_chunk_read: raise Error, 'data chunk before fmt chunk' self._data_chunk = chunk self._nframes = chunk.chunksize // self._framesize self._data_seek_needed = 0 break chunk.skip() if not self._fmt_chunk_read or not self._data_chunk: raise Error, 'fmt chunk and/or data chunk missing' def __init__(self, f): self._i_opened_the_file = None if isinstance(f, basestring): f = __builtin__.open(f, 'rb') self._i_opened_the_file = f # else, assume it is an open file object already self.initfp(f) def __del__(self): self.close() # # User visible methods. # def getfp(self): return self._file def rewind(self): self._data_seek_needed = 1 self._soundpos = 0 def close(self): if self._i_opened_the_file: self._i_opened_the_file.close() self._i_opened_the_file = None self._file = None def tell(self): return self._soundpos def getnchannels(self): return self._nchannels def getnframes(self): return self._nframes def getsampwidth(self): return self._sampwidth def getframerate(self): return self._framerate def getcomptype(self): return self._comptype def getcompname(self): return self._compname def getparams(self): return self.getnchannels(), self.getsampwidth(), \ self.getframerate(), self.getnframes(), \ self.getcomptype(), self.getcompname() def getmarkers(self): return None def getmark(self, id): raise Error, 'no marks' def setpos(self, pos): if pos < 0 or pos > self._nframes: raise Error, 'position not in range' self._soundpos = pos self._data_seek_needed = 1 def readframes(self, nframes): if self._data_seek_needed: self._data_chunk.seek(0, 0) pos = self._soundpos * self._framesize if pos: self._data_chunk.seek(pos, 0) self._data_seek_needed = 0 if nframes == 0: return '' if self._sampwidth > 1 and big_endian: # unfortunately the fromfile() method does not take # something that only looks like a file object, so # we have to reach into the innards of the chunk object import array chunk = self._data_chunk data = array.array(_array_fmts[self._sampwidth]) nitems = nframes * self._nchannels if nitems * self._sampwidth > chunk.chunksize - chunk.size_read: nitems = (chunk.chunksize - chunk.size_read) / self._sampwidth data.fromfile(chunk.file.file, nitems) # "tell" data chunk how much was read chunk.size_read = chunk.size_read + nitems * self._sampwidth # do the same for the outermost chunk chunk = chunk.file chunk.size_read = chunk.size_read + nitems * self._sampwidth data.byteswap() data = data.tostring() else: data = self._data_chunk.read(nframes * self._framesize) if self._convert and data: data = self._convert(data) self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth) return data # # Internal methods. # def _read_fmt_chunk(self, chunk): wFormatTag, self._nchannels, self._framerate, dwAvgBytesPerSec, wBlockAlign = struct.unpack('<hhllh', chunk.read(14)) if wFormatTag == WAVE_FORMAT_PCM: sampwidth = struct.unpack('<h', chunk.read(2))[0] self._sampwidth = (sampwidth + 7) // 8 else: raise Error, 'unknown format: %r' % (wFormatTag,) self._framesize = self._nchannels * self._sampwidth self._comptype = 'NONE' self._compname = 'not compressed' class Wave_write: """Variables used in this class: These variables are user settable through appropriate methods of this class: _file -- the open file with methods write(), close(), tell(), seek() set through the __init__() method _comptype -- the AIFF-C compression type ('NONE' in AIFF) set through the setcomptype() or setparams() method _compname -- the human-readable AIFF-C compression type set through the setcomptype() or setparams() method _nchannels -- the number of audio channels set through the setnchannels() or setparams() method _sampwidth -- the number of bytes per audio sample set through the setsampwidth() or setparams() method _framerate -- the sampling frequency set through the setframerate() or setparams() method _nframes -- the number of audio frames written to the header set through the setnframes() or setparams() method These variables are used internally only: _datalength -- the size of the audio samples written to the header _nframeswritten -- the number of frames actually written _datawritten -- the size of the audio samples actually written """ def __init__(self, f): self._i_opened_the_file = None if isinstance(f, basestring): f = __builtin__.open(f, 'wb') self._i_opened_the_file = f self.initfp(f) def initfp(self, file): self._file = file self._convert = None self._nchannels = 0 self._sampwidth = 0 self._framerate = 0 self._nframes = 0 self._nframeswritten = 0 self._datawritten = 0 self._datalength = 0 def __del__(self): self.close() # # User visible methods. # def setnchannels(self, nchannels): if self._datawritten: raise Error, 'cannot change parameters after starting to write' if nchannels < 1: raise Error, 'bad # of channels' self._nchannels = nchannels def getnchannels(self): if not self._nchannels: raise Error, 'number of channels not set' return self._nchannels def setsampwidth(self, sampwidth): if self._datawritten: raise Error, 'cannot change parameters after starting to write' if sampwidth < 1 or sampwidth > 4: raise Error, 'bad sample width' self._sampwidth = sampwidth def getsampwidth(self): if not self._sampwidth: raise Error, 'sample width not set' return self._sampwidth def setframerate(self, framerate): if self._datawritten: raise Error, 'cannot change parameters after starting to write' if framerate <= 0: raise Error, 'bad frame rate' self._framerate = framerate def getframerate(self): if not self._framerate: raise Error, 'frame rate not set' return self._framerate def setnframes(self, nframes): if self._datawritten: raise Error, 'cannot change parameters after starting to write' self._nframes = nframes def getnframes(self): return self._nframeswritten def setcomptype(self, comptype, compname): if self._datawritten: raise Error, 'cannot change parameters after starting to write' if comptype not in ('NONE',): raise Error, 'unsupported compression type' self._comptype = comptype self._compname = compname def getcomptype(self): return self._comptype def getcompname(self): return self._compname def setparams(self, (nchannels, sampwidth, framerate, nframes, comptype, compname)): if self._datawritten: raise Error, 'cannot change parameters after starting to write' self.setnchannels(nchannels) self.setsampwidth(sampwidth) self.setframerate(framerate) self.setnframes(nframes) self.setcomptype(comptype, compname) def getparams(self): if not self._nchannels or not self._sampwidth or not self._framerate: raise Error, 'not all parameters set' return self._nchannels, self._sampwidth, self._framerate, \ self._nframes, self._comptype, self._compname def setmark(self, id, pos, name): raise Error, 'setmark() not supported' def getmark(self, id): raise Error, 'no marks' def getmarkers(self): return None def tell(self): return self._nframeswritten def writeframesraw(self, data): self._ensure_header_written(len(data)) nframes = len(data) // (self._sampwidth * self._nchannels) if self._convert: data = self._convert(data) if self._sampwidth > 1 and big_endian: import array data = array.array(_array_fmts[self._sampwidth], data) data.byteswap() data.tofile(self._file) self._datawritten = self._datawritten + len(data) * self._sampwidth else: self._file.write(data) self._datawritten = self._datawritten + len(data) self._nframeswritten = self._nframeswritten + nframes def writeframes(self, data): self.writeframesraw(data) if self._datalength != self._datawritten: self._patchheader() def close(self): if self._file: self._ensure_header_written(0) if self._datalength != self._datawritten: self._patchheader() self._file.flush() self._file = None if self._i_opened_the_file: self._i_opened_the_file.close() self._i_opened_the_file = None # # Internal methods. # def _ensure_header_written(self, datasize): if not self._datawritten: if not self._nchannels: raise Error, '# channels not specified' if not self._sampwidth: raise Error, 'sample width not specified' if not self._framerate: raise Error, 'sampling rate not specified' self._write_header(datasize) def _write_header(self, initlength): self._file.write('RIFF') if not self._nframes: self._nframes = initlength / (self._nchannels * self._sampwidth) self._datalength = self._nframes * self._nchannels * self._sampwidth self._form_length_pos = self._file.tell() self._file.write(struct.pack('<l4s4slhhllhh4s', 36 + self._datalength, 'WAVE', 'fmt ', 16, WAVE_FORMAT_PCM, self._nchannels, self._framerate, self._nchannels * self._framerate * self._sampwidth, self._nchannels * self._sampwidth, self._sampwidth * 8, 'data')) self._data_length_pos = self._file.tell() self._file.write(struct.pack('<l', self._datalength)) def _patchheader(self): if self._datawritten == self._datalength: return curpos = self._file.tell() self._file.seek(self._form_length_pos, 0) self._file.write(struct.pack('<l', 36 + self._datawritten)) self._file.seek(self._data_length_pos, 0) self._file.write(struct.pack('<l', self._datawritten)) self._file.seek(curpos, 0) self._datalength = self._datawritten def open(f, mode=None): if mode is None: if hasattr(f, 'mode'): mode = f.mode else: mode = 'rb' if mode in ('r', 'rb'): return Wave_read(f) elif mode in ('w', 'wb'): return Wave_write(f) else: raise Error, "mode must be 'r', 'rb', 'w', or 'wb'" openfp = open # B/W compatibility
Python
"""Define names for all type symbols known in the standard interpreter. Types that are part of optional modules (e.g. array) are not listed. """ import sys # Iterators in Python aren't a matter of type but of protocol. A large # and changing number of builtin types implement *some* flavor of # iterator. Don't check the type! Use hasattr to check for both # "__iter__" and "next" attributes instead. NoneType = type(None) TypeType = type ObjectType = object IntType = int LongType = long FloatType = float BooleanType = bool try: ComplexType = complex except NameError: pass StringType = str # StringTypes is already outdated. Instead of writing "type(x) in # types.StringTypes", you should use "isinstance(x, basestring)". But # we keep around for compatibility with Python 2.2. try: UnicodeType = unicode StringTypes = (StringType, UnicodeType) except NameError: StringTypes = (StringType,) BufferType = buffer TupleType = tuple ListType = list DictType = DictionaryType = dict def _f(): pass FunctionType = type(_f) LambdaType = type(lambda: None) # Same as FunctionType try: CodeType = type(_f.func_code) except RuntimeError: # Execution in restricted environment pass def _g(): yield 1 GeneratorType = type(_g()) class _C: def _m(self): pass ClassType = type(_C) UnboundMethodType = type(_C._m) # Same as MethodType _x = _C() InstanceType = type(_x) MethodType = type(_x._m) BuiltinFunctionType = type(len) BuiltinMethodType = type([].append) # Same as BuiltinFunctionType ModuleType = type(sys) FileType = file XRangeType = xrange try: raise TypeError except TypeError: try: tb = sys.exc_info()[2] TracebackType = type(tb) FrameType = type(tb.tb_frame) except AttributeError: # In the restricted environment, exc_info returns (None, None, # None) Then, tb.tb_frame gives an attribute error pass tb = None; del tb SliceType = slice EllipsisType = type(Ellipsis) DictProxyType = type(TypeType.__dict__) NotImplementedType = type(NotImplemented) del sys, _f, _g, _C, _x # Not for export
Python
"""An NNTP client class based on RFC 977: Network News Transfer Protocol. Example: >>> from nntplib import NNTP >>> s = NNTP('news') >>> resp, count, first, last, name = s.group('comp.lang.python') >>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last Group comp.lang.python has 51 articles, range 5770 to 5821 >>> resp, subs = s.xhdr('subject', first + '-' + last) >>> resp = s.quit() >>> Here 'resp' is the server response line. Error responses are turned into exceptions. To post an article from a file: >>> f = open(filename, 'r') # file containing article, including header >>> resp = s.post(f) >>> For descriptions of all methods, read the comments in the code below. Note that all arguments and return values representing article numbers are strings, not numbers, since they are rarely used for calculations. """ # RFC 977 by Brian Kantor and Phil Lapsley. # xover, xgtitle, xpath, date methods by Kevan Heydon # Imports import re import socket __all__ = ["NNTP","NNTPReplyError","NNTPTemporaryError", "NNTPPermanentError","NNTPProtocolError","NNTPDataError", "error_reply","error_temp","error_perm","error_proto", "error_data",] # Exceptions raised when an error or invalid response is received class NNTPError(Exception): """Base class for all nntplib exceptions""" def __init__(self, *args): Exception.__init__(self, *args) try: self.response = args[0] except IndexError: self.response = 'No response given' class NNTPReplyError(NNTPError): """Unexpected [123]xx reply""" pass class NNTPTemporaryError(NNTPError): """4xx errors""" pass class NNTPPermanentError(NNTPError): """5xx errors""" pass class NNTPProtocolError(NNTPError): """Response does not begin with [1-5]""" pass class NNTPDataError(NNTPError): """Error in response data""" pass # for backwards compatibility error_reply = NNTPReplyError error_temp = NNTPTemporaryError error_perm = NNTPPermanentError error_proto = NNTPProtocolError error_data = NNTPDataError # Standard port used by NNTP servers NNTP_PORT = 119 # Response numbers that are followed by additional text (e.g. article) LONGRESP = ['100', '215', '220', '221', '222', '224', '230', '231', '282'] # Line terminators (we always output CRLF, but accept any of CRLF, CR, LF) CRLF = '\r\n' # The class itself class NNTP: def __init__(self, host, port=NNTP_PORT, user=None, password=None, readermode=None, usenetrc=True): """Initialize an instance. Arguments: - host: hostname to connect to - port: port to connect to (default the standard NNTP port) - user: username to authenticate with - password: password to use with username - readermode: if true, send 'mode reader' command after connecting. readermode is sometimes necessary if you are connecting to an NNTP server on the local machine and intend to call reader-specific comamnds, such as `group'. If you get unexpected NNTPPermanentErrors, you might need to set readermode. """ self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.host, self.port)) self.file = self.sock.makefile('rb') self.debugging = 0 self.welcome = self.getresp() # 'mode reader' is sometimes necessary to enable 'reader' mode. # However, the order in which 'mode reader' and 'authinfo' need to # arrive differs between some NNTP servers. Try to send # 'mode reader', and if it fails with an authorization failed # error, try again after sending authinfo. readermode_afterauth = 0 if readermode: try: self.welcome = self.shortcmd('mode reader') except NNTPPermanentError: # error 500, probably 'not implemented' pass except NNTPTemporaryError, e: if user and e.response[:3] == '480': # Need authorization before 'mode reader' readermode_afterauth = 1 else: raise # If no login/password was specified, try to get them from ~/.netrc # Presume that if .netc has an entry, NNRP authentication is required. try: if usenetrc and not user: import netrc credentials = netrc.netrc() auth = credentials.authenticators(host) if auth: user = auth[0] password = auth[2] except IOError: pass # Perform NNRP authentication if needed. if user: resp = self.shortcmd('authinfo user '+user) if resp[:3] == '381': if not password: raise NNTPReplyError(resp) else: resp = self.shortcmd( 'authinfo pass '+password) if resp[:3] != '281': raise NNTPPermanentError(resp) if readermode_afterauth: try: self.welcome = self.shortcmd('mode reader') except NNTPPermanentError: # error 500, probably 'not implemented' pass # Get the welcome message from the server # (this is read and squirreled away by __init__()). # If the response code is 200, posting is allowed; # if it 201, posting is not allowed def getwelcome(self): """Get the welcome message from the server (this is read and squirreled away by __init__()). If the response code is 200, posting is allowed; if it 201, posting is not allowed.""" if self.debugging: print '*welcome*', repr(self.welcome) return self.welcome def set_debuglevel(self, level): """Set the debugging level. Argument 'level' means: 0: no debugging output (default) 1: print commands and responses but not body text etc. 2: also print raw lines read and sent before stripping CR/LF""" self.debugging = level debug = set_debuglevel def putline(self, line): """Internal: send one line to the server, appending CRLF.""" line = line + CRLF if self.debugging > 1: print '*put*', repr(line) self.sock.sendall(line) def putcmd(self, line): """Internal: send one command to the server (through putline()).""" if self.debugging: print '*cmd*', repr(line) self.putline(line) def getline(self): """Internal: return one line from the server, stripping CRLF. Raise EOFError if the connection is closed.""" line = self.file.readline() if self.debugging > 1: print '*get*', repr(line) if not line: raise EOFError if line[-2:] == CRLF: line = line[:-2] elif line[-1:] in CRLF: line = line[:-1] return line def getresp(self): """Internal: get a response from the server. Raise various errors if the response indicates an error.""" resp = self.getline() if self.debugging: print '*resp*', repr(resp) c = resp[:1] if c == '4': raise NNTPTemporaryError(resp) if c == '5': raise NNTPPermanentError(resp) if c not in '123': raise NNTPProtocolError(resp) return resp def getlongresp(self, file=None): """Internal: get a response plus following text from the server. Raise various errors if the response indicates an error.""" openedFile = None try: # If a string was passed then open a file with that name if isinstance(file, str): openedFile = file = open(file, "w") resp = self.getresp() if resp[:3] not in LONGRESP: raise NNTPReplyError(resp) list = [] while 1: line = self.getline() if line == '.': break if line[:2] == '..': line = line[1:] if file: file.write(line + "\n") else: list.append(line) finally: # If this method created the file, then it must close it if openedFile: openedFile.close() return resp, list def shortcmd(self, line): """Internal: send a command and get the response.""" self.putcmd(line) return self.getresp() def longcmd(self, line, file=None): """Internal: send a command and get the response plus following text.""" self.putcmd(line) return self.getlongresp(file) def newgroups(self, date, time, file=None): """Process a NEWGROUPS command. Arguments: - date: string 'yymmdd' indicating the date - time: string 'hhmmss' indicating the time Return: - resp: server response if successful - list: list of newsgroup names""" return self.longcmd('NEWGROUPS ' + date + ' ' + time, file) def newnews(self, group, date, time, file=None): """Process a NEWNEWS command. Arguments: - group: group name or '*' - date: string 'yymmdd' indicating the date - time: string 'hhmmss' indicating the time Return: - resp: server response if successful - list: list of article ids""" cmd = 'NEWNEWS ' + group + ' ' + date + ' ' + time return self.longcmd(cmd, file) def list(self, file=None): """Process a LIST command. Return: - resp: server response if successful - list: list of (group, last, first, flag) (strings)""" resp, list = self.longcmd('LIST', file) for i in range(len(list)): # Parse lines into "group last first flag" list[i] = tuple(list[i].split()) return resp, list def description(self, group): """Get a description for a single group. If more than one group matches ('group' is a pattern), return the first. If no group matches, return an empty string. This elides the response code from the server, since it can only be '215' or '285' (for xgtitle) anyway. If the response code is needed, use the 'descriptions' method. NOTE: This neither checks for a wildcard in 'group' nor does it check whether the group actually exists.""" resp, lines = self.descriptions(group) if len(lines) == 0: return "" else: return lines[0][1] def descriptions(self, group_pattern): """Get descriptions for a range of groups.""" line_pat = re.compile("^(?P<group>[^ \t]+)[ \t]+(.*)$") # Try the more std (acc. to RFC2980) LIST NEWSGROUPS first resp, raw_lines = self.longcmd('LIST NEWSGROUPS ' + group_pattern) if resp[:3] != "215": # Now the deprecated XGTITLE. This either raises an error # or succeeds with the same output structure as LIST # NEWSGROUPS. resp, raw_lines = self.longcmd('XGTITLE ' + group_pattern) lines = [] for raw_line in raw_lines: match = line_pat.search(raw_line.strip()) if match: lines.append(match.group(1, 2)) return resp, lines def group(self, name): """Process a GROUP command. Argument: - group: the group name Returns: - resp: server response if successful - count: number of articles (string) - first: first article number (string) - last: last article number (string) - name: the group name""" resp = self.shortcmd('GROUP ' + name) if resp[:3] != '211': raise NNTPReplyError(resp) words = resp.split() count = first = last = 0 n = len(words) if n > 1: count = words[1] if n > 2: first = words[2] if n > 3: last = words[3] if n > 4: name = words[4].lower() return resp, count, first, last, name def help(self, file=None): """Process a HELP command. Returns: - resp: server response if successful - list: list of strings""" return self.longcmd('HELP',file) def statparse(self, resp): """Internal: parse the response of a STAT, NEXT or LAST command.""" if resp[:2] != '22': raise NNTPReplyError(resp) words = resp.split() nr = 0 id = '' n = len(words) if n > 1: nr = words[1] if n > 2: id = words[2] return resp, nr, id def statcmd(self, line): """Internal: process a STAT, NEXT or LAST command.""" resp = self.shortcmd(line) return self.statparse(resp) def stat(self, id): """Process a STAT command. Argument: - id: article number or message id Returns: - resp: server response if successful - nr: the article number - id: the article id""" return self.statcmd('STAT ' + id) def next(self): """Process a NEXT command. No arguments. Return as for STAT.""" return self.statcmd('NEXT') def last(self): """Process a LAST command. No arguments. Return as for STAT.""" return self.statcmd('LAST') def artcmd(self, line, file=None): """Internal: process a HEAD, BODY or ARTICLE command.""" resp, list = self.longcmd(line, file) resp, nr, id = self.statparse(resp) return resp, nr, id, list def head(self, id): """Process a HEAD command. Argument: - id: article number or message id Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article's header""" return self.artcmd('HEAD ' + id) def body(self, id, file=None): """Process a BODY command. Argument: - id: article number or message id - file: Filename string or file object to store the article in Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article's body or an empty list if file was used""" return self.artcmd('BODY ' + id, file) def article(self, id): """Process an ARTICLE command. Argument: - id: article number or message id Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article""" return self.artcmd('ARTICLE ' + id) def slave(self): """Process a SLAVE command. Returns: - resp: server response if successful""" return self.shortcmd('SLAVE') def xhdr(self, hdr, str, file=None): """Process an XHDR command (optional server extension). Arguments: - hdr: the header type (e.g. 'subject') - str: an article nr, a message id, or a range nr1-nr2 Returns: - resp: server response if successful - list: list of (nr, value) strings""" pat = re.compile('^([0-9]+) ?(.*)\n?') resp, lines = self.longcmd('XHDR ' + hdr + ' ' + str, file) for i in range(len(lines)): line = lines[i] m = pat.match(line) if m: lines[i] = m.group(1, 2) return resp, lines def xover(self, start, end, file=None): """Process an XOVER command (optional server extension) Arguments: - start: start of range - end: end of range Returns: - resp: server response if successful - list: list of (art-nr, subject, poster, date, id, references, size, lines)""" resp, lines = self.longcmd('XOVER ' + start + '-' + end, file) xover_lines = [] for line in lines: elem = line.split("\t") try: xover_lines.append((elem[0], elem[1], elem[2], elem[3], elem[4], elem[5].split(), elem[6], elem[7])) except IndexError: raise NNTPDataError(line) return resp,xover_lines def xgtitle(self, group, file=None): """Process an XGTITLE command (optional server extension) Arguments: - group: group name wildcard (i.e. news.*) Returns: - resp: server response if successful - list: list of (name,title) strings""" line_pat = re.compile("^([^ \t]+)[ \t]+(.*)$") resp, raw_lines = self.longcmd('XGTITLE ' + group, file) lines = [] for raw_line in raw_lines: match = line_pat.search(raw_line.strip()) if match: lines.append(match.group(1, 2)) return resp, lines def xpath(self,id): """Process an XPATH command (optional server extension) Arguments: - id: Message id of article Returns: resp: server response if successful path: directory path to article""" resp = self.shortcmd("XPATH " + id) if resp[:3] != '223': raise NNTPReplyError(resp) try: [resp_num, path] = resp.split() except ValueError: raise NNTPReplyError(resp) else: return resp, path def date (self): """Process the DATE command. Arguments: None Returns: resp: server response if successful date: Date suitable for newnews/newgroups commands etc. time: Time suitable for newnews/newgroups commands etc.""" resp = self.shortcmd("DATE") if resp[:3] != '111': raise NNTPReplyError(resp) elem = resp.split() if len(elem) != 2: raise NNTPDataError(resp) date = elem[1][2:8] time = elem[1][-6:] if len(date) != 6 or len(time) != 6: raise NNTPDataError(resp) return resp, date, time def post(self, f): """Process a POST command. Arguments: - f: file containing the article Returns: - resp: server response if successful""" resp = self.shortcmd('POST') # Raises error_??? if posting is not allowed if resp[0] != '3': raise NNTPReplyError(resp) while 1: line = f.readline() if not line: break if line[-1] == '\n': line = line[:-1] if line[:1] == '.': line = '.' + line self.putline(line) self.putline('.') return self.getresp() def ihave(self, id, f): """Process an IHAVE command. Arguments: - id: message-id of the article - f: file containing the article Returns: - resp: server response if successful Note that if the server refuses the article an exception is raised.""" resp = self.shortcmd('IHAVE ' + id) # Raises error_??? if the server already has it if resp[0] != '3': raise NNTPReplyError(resp) while 1: line = f.readline() if not line: break if line[-1] == '\n': line = line[:-1] if line[:1] == '.': line = '.' + line self.putline(line) self.putline('.') return self.getresp() def quit(self): """Process a QUIT command and close the socket. Returns: - resp: server response if successful""" resp = self.shortcmd('QUIT') self.file.close() self.sock.close() del self.file, self.sock return resp # Test retrieval when run as a script. # Assumption: if there's a local news server, it's called 'news'. # Assumption: if user queries a remote news server, it's named # in the environment variable NNTPSERVER (used by slrn and kin) # and we want readermode off. if __name__ == '__main__': import os newshost = 'news' and os.environ["NNTPSERVER"] if newshost.find('.') == -1: mode = 'readermode' else: mode = None s = NNTP(newshost, readermode=mode) resp, count, first, last, name = s.group('comp.lang.python') print resp print 'Group', name, 'has', count, 'articles, range', first, 'to', last resp, subs = s.xhdr('subject', first + '-' + last) print resp for item in subs: print "%7s %s" % item resp = s.quit() print resp
Python
#!/usr/bin/env python # -*- coding: Latin-1 -*- """Generate Python documentation in HTML or text for interactive use. In the Python interpreter, do "from pydoc import help" to provide online help. Calling help(thing) on a Python object documents the object. Or, at the shell command line outside of Python: Run "pydoc <name>" to show documentation on something. <name> may be the name of a function, module, package, or a dotted reference to a class or function within a module or module in a package. If the argument contains a path segment delimiter (e.g. slash on Unix, backslash on Windows) it is treated as the path to a Python source file. Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines of all available modules. Run "pydoc -p <port>" to start an HTTP server on a given port on the local machine to generate documentation web pages. For platforms without a command line, "pydoc -g" starts the HTTP server and also pops up a little window for controlling it. Run "pydoc -w <name>" to write out the HTML documentation for a module to a file named "<name>.html". Module docs for core modules are assumed to be in http://www.python.org/doc/current/lib/ This can be overridden by setting the PYTHONDOCS environment variable to a different URL or to a local directory containing the Library Reference Manual pages. """ __author__ = "Ka-Ping Yee <ping@lfw.org>" __date__ = "26 February 2001" __version__ = "$Revision: 1.100.2.2 $" __credits__ = """Guido van Rossum, for an excellent programming language. Tommy Burnette, the original creator of manpy. Paul Prescod, for all his work on onlinehelp. Richard Chamberlain, for the first implementation of textdoc. """ # Known bugs that can't be fixed here: # - imp.load_module() cannot be prevented from clobbering existing # loaded modules, so calling synopsis() on a binary module file # changes the contents of any existing module with the same name. # - If the __file__ attribute on a module is a relative path and # the current directory is changed with os.chdir(), an incorrect # path will be displayed. import sys, imp, os, re, types, inspect, __builtin__ from repr import Repr from string import expandtabs, find, join, lower, split, strip, rfind, rstrip from collections import deque # --------------------------------------------------------- common routines def pathdirs(): """Convert sys.path into a list of absolute, existing, unique paths.""" dirs = [] normdirs = [] for dir in sys.path: dir = os.path.abspath(dir or '.') normdir = os.path.normcase(dir) if normdir not in normdirs and os.path.isdir(dir): dirs.append(dir) normdirs.append(normdir) return dirs def getdoc(object): """Get the doc string or comments for an object.""" result = inspect.getdoc(object) or inspect.getcomments(object) return result and re.sub('^ *\n', '', rstrip(result)) or '' def splitdoc(doc): """Split a doc string into a synopsis line (if any) and the rest.""" lines = split(strip(doc), '\n') if len(lines) == 1: return lines[0], '' elif len(lines) >= 2 and not rstrip(lines[1]): return lines[0], join(lines[2:], '\n') return '', join(lines, '\n') def classname(object, modname): """Get a class name and qualify it with a module name if necessary.""" name = object.__name__ if object.__module__ != modname: name = object.__module__ + '.' + name return name def isdata(object): """Check if an object is of a type that probably means it's data.""" return not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isframe(object) or inspect.istraceback(object) or inspect.iscode(object)) def replace(text, *pairs): """Do a series of global replacements on a string.""" while pairs: text = join(split(text, pairs[0]), pairs[1]) pairs = pairs[2:] return text def cram(text, maxlen): """Omit part of a string if needed to make it fit in a maximum length.""" if len(text) > maxlen: pre = max(0, (maxlen-3)//2) post = max(0, maxlen-3-pre) return text[:pre] + '...' + text[len(text)-post:] return text _re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE) def stripid(text): """Remove the hexadecimal id from a Python object representation.""" # The behaviour of %p is implementation-dependent in terms of case. if _re_stripid.search(repr(Exception)): return _re_stripid.sub(r'\1', text) return text def _is_some_method(obj): return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj) def allmethods(cl): methods = {} for key, value in inspect.getmembers(cl, _is_some_method): methods[key] = 1 for base in cl.__bases__: methods.update(allmethods(base)) # all your base are belong to us for key in methods.keys(): methods[key] = getattr(cl, key) return methods def _split_list(s, predicate): """Split sequence s via predicate, and return pair ([true], [false]). The return value is a 2-tuple of lists, ([x for x in s if predicate(x)], [x for x in s if not predicate(x)]) """ yes = [] no = [] for x in s: if predicate(x): yes.append(x) else: no.append(x) return yes, no def visiblename(name, all=None): """Decide whether to show documentation on a variable.""" # Certain special names are redundant. if name in ['__builtins__', '__doc__', '__file__', '__path__', '__module__', '__name__']: return 0 # Private names are hidden, but special names are displayed. if name.startswith('__') and name.endswith('__'): return 1 if all is not None: # only document that which the programmer exported in __all__ return name in all else: return not name.startswith('_') # ----------------------------------------------------- module manipulation def ispackage(path): """Guess whether a path refers to a package directory.""" if os.path.isdir(path): for ext in ['.py', '.pyc', '.pyo']: if os.path.isfile(os.path.join(path, '__init__' + ext)): return True return False def synopsis(filename, cache={}): """Get the one-line summary out of a module file.""" mtime = os.stat(filename).st_mtime lastupdate, result = cache.get(filename, (0, None)) if lastupdate < mtime: info = inspect.getmoduleinfo(filename) file = open(filename) if info and 'b' in info[2]: # binary modules have to be imported try: module = imp.load_module('__temp__', file, filename, info[1:]) except: return None result = split(module.__doc__ or '', '\n')[0] del sys.modules['__temp__'] else: # text modules can be directly examined line = file.readline() while line[:1] == '#' or not strip(line): line = file.readline() if not line: break line = strip(line) if line[:4] == 'r"""': line = line[1:] if line[:3] == '"""': line = line[3:] if line[-1:] == '\\': line = line[:-1] while not strip(line): line = file.readline() if not line: break result = strip(split(line, '"""')[0]) else: result = None file.close() cache[filename] = (mtime, result) return result class ErrorDuringImport(Exception): """Errors that occurred while trying to import something to document it.""" def __init__(self, filename, (exc, value, tb)): self.filename = filename self.exc = exc self.value = value self.tb = tb def __str__(self): exc = self.exc if type(exc) is types.ClassType: exc = exc.__name__ return 'problem in %s - %s: %s' % (self.filename, exc, self.value) def importfile(path): """Import a Python source file or compiled file given its path.""" magic = imp.get_magic() file = open(path, 'r') if file.read(len(magic)) == magic: kind = imp.PY_COMPILED else: kind = imp.PY_SOURCE file.close() filename = os.path.basename(path) name, ext = os.path.splitext(filename) file = open(path, 'r') try: module = imp.load_module(name, file, path, (ext, 'r', kind)) except: raise ErrorDuringImport(path, sys.exc_info()) file.close() return module def safeimport(path, forceload=0, cache={}): """Import a module; handle errors; return None if the module isn't found. If the module *is* found but an exception occurs, it's wrapped in an ErrorDuringImport exception and reraised. Unlike __import__, if a package path is specified, the module at the end of the path is returned, not the package at the beginning. If the optional 'forceload' argument is 1, we reload the module from disk (unless it's a dynamic extension).""" if forceload and path in sys.modules: # This is the only way to be sure. Checking the mtime of the file # isn't good enough (e.g. what if the module contains a class that # inherits from another module that has changed?). if path not in sys.builtin_module_names: # Python never loads a dynamic extension a second time from the # same path, even if the file is changed or missing. Deleting # the entry in sys.modules doesn't help for dynamic extensions, # so we're not even going to try to keep them up to date. info = inspect.getmoduleinfo(sys.modules[path].__file__) if info[3] != imp.C_EXTENSION: cache[path] = sys.modules[path] # prevent module from clearing del sys.modules[path] try: module = __import__(path) except: # Did the error occur before or after the module was found? (exc, value, tb) = info = sys.exc_info() if path in sys.modules: # An error occured while executing the imported module. raise ErrorDuringImport(sys.modules[path].__file__, info) elif exc is SyntaxError: # A SyntaxError occurred before we could execute the module. raise ErrorDuringImport(value.filename, info) elif exc is ImportError and \ split(lower(str(value)))[:2] == ['no', 'module']: # The module was not found. return None else: # Some other error occurred during the importing process. raise ErrorDuringImport(path, sys.exc_info()) for part in split(path, '.')[1:]: try: module = getattr(module, part) except AttributeError: return None return module # ---------------------------------------------------- formatter base class class Doc: def document(self, object, name=None, *args): """Generate documentation for an object.""" args = (object, name) + args # 'try' clause is to attempt to handle the possibility that inspect # identifies something in a way that pydoc itself has issues handling; # think 'super' and how it is a descriptor (which raises the exception # by lacking a __name__ attribute) and an instance. try: if inspect.ismodule(object): return self.docmodule(*args) if inspect.isclass(object): return self.docclass(*args) if inspect.isroutine(object): return self.docroutine(*args) except AttributeError: pass if isinstance(object, property): return self.docproperty(*args) return self.docother(*args) def fail(self, object, name=None, *args): """Raise an exception for unimplemented types.""" message = "don't know how to document object%s of type %s" % ( name and ' ' + repr(name), type(object).__name__) raise TypeError, message docmodule = docclass = docroutine = docother = fail def getdocloc(self, object): """Return the location of module docs or None""" try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' docloc = os.environ.get("PYTHONDOCS", "http://www.python.org/doc/current/lib") basedir = os.path.join(sys.exec_prefix, "lib", "python"+sys.version[0:3]) if (isinstance(object, type(os)) and (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'signal', 'sys', 'thread', 'zipimport') or (file.startswith(basedir) and not file.startswith(os.path.join(basedir, 'site-packages'))))): htmlfile = "module-%s.html" % object.__name__ if docloc.startswith("http://"): docloc = "%s/%s" % (docloc.rstrip("/"), htmlfile) else: docloc = os.path.join(docloc, htmlfile) else: docloc = None return docloc # -------------------------------------------- HTML documentation generator class HTMLRepr(Repr): """Class for safely making an HTML representation of a Python object.""" def __init__(self): Repr.__init__(self) self.maxlist = self.maxtuple = 20 self.maxdict = 10 self.maxstring = self.maxother = 100 def escape(self, text): return replace(text, '&', '&amp;', '<', '&lt;', '>', '&gt;') def repr(self, object): return Repr.repr(self, object) def repr1(self, x, level): if hasattr(type(x), '__name__'): methodname = 'repr_' + join(split(type(x).__name__), '_') if hasattr(self, methodname): return getattr(self, methodname)(x, level) return self.escape(cram(stripid(repr(x)), self.maxother)) def repr_string(self, x, level): test = cram(x, self.maxstring) testrepr = repr(test) if '\\' in test and '\\' not in replace(testrepr, r'\\', ''): # Backslashes are only literal in the string and are never # needed to make any special characters, so show a raw string. return 'r' + testrepr[0] + self.escape(test) + testrepr[0] return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)', r'<font color="#c040c0">\1</font>', self.escape(testrepr)) repr_str = repr_string def repr_instance(self, x, level): try: return self.escape(cram(stripid(repr(x)), self.maxstring)) except: return self.escape('<%s instance>' % x.__class__.__name__) repr_unicode = repr_string class HTMLDoc(Doc): """Formatter class for HTML documentation.""" # ------------------------------------------- HTML formatting utilities _repr_instance = HTMLRepr() repr = _repr_instance.repr escape = _repr_instance.escape def page(self, title, contents): """Format an HTML page.""" return ''' <!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html><head><title>Python: %s</title> </head><body bgcolor="#f0f0f8"> %s </body></html>''' % (title, contents) def heading(self, title, fgcol, bgcol, extras=''): """Format a page heading.""" return ''' <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading"> <tr bgcolor="%s"> <td valign=bottom>&nbsp;<br> <font color="%s" face="helvetica, arial">&nbsp;<br>%s</font></td ><td align=right valign=bottom ><font color="%s" face="helvetica, arial">%s</font></td></tr></table> ''' % (bgcol, fgcol, title, fgcol, extras or '&nbsp;') def section(self, title, fgcol, bgcol, contents, width=6, prelude='', marginalia=None, gap='&nbsp;'): """Format a section with a heading.""" if marginalia is None: marginalia = '<tt>' + '&nbsp;' * width + '</tt>' result = '''<p> <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="%s"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="%s" face="helvetica, arial">%s</font></td></tr> ''' % (bgcol, fgcol, title) if prelude: result = result + ''' <tr bgcolor="%s"><td rowspan=2>%s</td> <td colspan=2>%s</td></tr> <tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap) else: result = result + ''' <tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap) return result + '\n<td width="100%%">%s</td></tr></table>' % contents def bigsection(self, title, *args): """Format a section with a big heading.""" title = '<big><strong>%s</strong></big>' % title return self.section(title, *args) def preformat(self, text): """Format literal preformatted text.""" text = self.escape(expandtabs(text)) return replace(text, '\n\n', '\n \n', '\n\n', '\n \n', ' ', '&nbsp;', '\n', '<br>\n') def multicolumn(self, list, format, cols=4): """Format a list of items into a multi-column list.""" result = '' rows = (len(list)+cols-1)/cols for col in range(cols): result = result + '<td width="%d%%" valign=top>' % (100/cols) for i in range(rows*col, rows*col+rows): if i < len(list): result = result + format(list[i]) + '<br>\n' result = result + '</td>' return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result def grey(self, text): return '<font color="#909090">%s</font>' % text def namelink(self, name, *dicts): """Make a link for an identifier, given name-to-URL mappings.""" for dict in dicts: if name in dict: return '<a href="%s">%s</a>' % (dict[name], name) return name def classlink(self, object, modname): """Make a link for a class.""" name, module = object.__name__, sys.modules.get(object.__module__) if hasattr(module, name) and getattr(module, name) is object: return '<a href="%s.html#%s">%s</a>' % ( module.__name__, name, classname(object, modname)) return classname(object, modname) def modulelink(self, object): """Make a link for a module.""" return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__) def modpkglink(self, (name, path, ispackage, shadowed)): """Make a link for a module or package to display in an index.""" if shadowed: return self.grey(name) if path: url = '%s.%s.html' % (path, name) else: url = '%s.html' % name if ispackage: text = '<strong>%s</strong>&nbsp;(package)' % name else: text = name return '<a href="%s">%s</a>' % (url, text) def markup(self, text, escape=None, funcs={}, classes={}, methods={}): """Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.""" escape = escape or self.escape results = [] here = 0 pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|' r'RFC[- ]?(\d+)|' r'PEP[- ]?(\d+)|' r'(self\.)?(\w+))') while True: match = pattern.search(text, here) if not match: break start, end = match.span() results.append(escape(text[here:start])) all, scheme, rfc, pep, selfdot, name = match.groups() if scheme: url = escape(all).replace('"', '&quot;') results.append('<a href="%s">%s</a>' % (url, url)) elif rfc: url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif pep: url = 'http://www.python.org/peps/pep-%04d.html' % int(pep) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif text[end:end+1] == '(': results.append(self.namelink(name, methods, funcs, classes)) elif selfdot: results.append('self.<strong>%s</strong>' % name) else: results.append(self.namelink(name, classes)) here = end results.append(escape(text[here:])) return join(results, '') # ---------------------------------------------- type-specific routines def formattree(self, tree, modname, parent=None): """Produce HTML for a class tree as given by inspect.getclasstree().""" result = '' for entry in tree: if type(entry) is type(()): c, bases = entry result = result + '<dt><font face="helvetica, arial">' result = result + self.classlink(c, modname) if bases and bases != (parent,): parents = [] for base in bases: parents.append(self.classlink(base, modname)) result = result + '(' + join(parents, ', ') + ')' result = result + '\n</font></dt>' elif type(entry) is type([]): result = result + '<dd>\n%s</dd>\n' % self.formattree( entry, modname, c) return '<dl>\n%s</dl>\n' % result def docmodule(self, object, name=None, mod=None, *ignored): """Produce HTML documentation for a module object.""" name = object.__name__ # ignore the passed-in name try: all = object.__all__ except AttributeError: all = None parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '.') head = '<big><big><strong>%s</strong></big></big>' % linkedname try: path = inspect.getabsfile(object) url = path if sys.platform == 'win32': import nturl2path url = nturl2path.pathname2url(path) filelink = '<a href="file:%s">%s</a>' % (url, path) except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: head = head + ' (%s)' % join(info, ', ') docloc = self.getdocloc(object) if docloc is not None: docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals() else: docloc = '' result = self.heading( head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink + docloc) modules = inspect.getmembers(object, inspect.ismodule) classes, cdict = [], {} for key, value in inspect.getmembers(object, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or (inspect.getmodule(value) or object) is object): if visiblename(key, all): classes.append((key, value)) cdict[key] = cdict[value] = '#' + key for key, value in classes: for base in value.__bases__: key, modname = base.__name__, base.__module__ module = sys.modules.get(modname) if modname != name and module and hasattr(module, key): if getattr(module, key) is base: if not key in cdict: cdict[key] = cdict[base] = modname + '.html#' + key funcs, fdict = [], {} for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if visiblename(key, all): funcs.append((key, value)) fdict[key] = '#-' + key if inspect.isfunction(value): fdict[value] = fdict[key] data = [] for key, value in inspect.getmembers(object, isdata): if visiblename(key, all): data.append((key, value)) doc = self.markup(getdoc(object), self.preformat, fdict, cdict) doc = doc and '<tt>%s</tt>' % doc result = result + '<p>%s</p>\n' % doc if hasattr(object, '__path__'): modpkgs = [] modnames = [] for file in os.listdir(object.__path__[0]): path = os.path.join(object.__path__[0], file) modname = inspect.getmodulename(file) if modname != '__init__': if modname and modname not in modnames: modpkgs.append((modname, name, 0, 0)) modnames.append(modname) elif ispackage(path): modpkgs.append((file, name, 1, 0)) modpkgs.sort() contents = self.multicolumn(modpkgs, self.modpkglink) result = result + self.bigsection( 'Package Contents', '#ffffff', '#aa55cc', contents) elif modules: contents = self.multicolumn( modules, lambda (key, value), s=self: s.modulelink(value)) result = result + self.bigsection( 'Modules', '#fffff', '#aa55cc', contents) if classes: classlist = map(lambda (key, value): value, classes) contents = [ self.formattree(inspect.getclasstree(classlist, 1), name)] for key, value in classes: contents.append(self.document(value, key, name, fdict, cdict)) result = result + self.bigsection( 'Classes', '#ffffff', '#ee77aa', join(contents)) if funcs: contents = [] for key, value in funcs: contents.append(self.document(value, key, name, fdict, cdict)) result = result + self.bigsection( 'Functions', '#ffffff', '#eeaa77', join(contents)) if data: contents = [] for key, value in data: contents.append(self.document(value, key)) result = result + self.bigsection( 'Data', '#ffffff', '#55aa55', join(contents, '<br>\n')) if hasattr(object, '__author__'): contents = self.markup(str(object.__author__), self.preformat) result = result + self.bigsection( 'Author', '#ffffff', '#7799ee', contents) if hasattr(object, '__credits__'): contents = self.markup(str(object.__credits__), self.preformat) result = result + self.bigsection( 'Credits', '#ffffff', '#7799ee', contents) return result def docclass(self, object, name=None, mod=None, funcs={}, classes={}, *ignored): """Produce HTML documentation for a class object.""" realname = object.__name__ name = name or realname bases = object.__bases__ contents = [] push = contents.append # Cute little class to pump out a horizontal rule between sections. class HorizontalRule: def __init__(self): self.needone = 0 def maybe(self): if self.needone: push('<hr>\n') self.needone = 1 hr = HorizontalRule() # List the mro, if non-trivial. mro = deque(inspect.getmro(object)) if len(mro) > 2: hr.maybe() push('<dl><dt>Method resolution order:</dt>\n') for base in mro: push('<dd>%s</dd>\n' % self.classlink(base, object.__module__)) push('</dl>\n') def spill(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: push(self.document(getattr(object, name), name, mod, funcs, classes, mdict, object)) push('\n') return attrs def spillproperties(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: push(self._docproperty(name, value, mod)) return attrs def spilldata(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: base = self.docother(getattr(object, name), name, mod) if callable(value) or inspect.isdatadescriptor(value): doc = getattr(value, "__doc__", None) else: doc = None if doc is None: push('<dl><dt>%s</dl>\n' % base) else: doc = self.markup(getdoc(value), self.preformat, funcs, classes, mdict) doc = '<dd><tt>%s</tt>' % doc push('<dl><dt>%s%s</dl>\n' % (base, doc)) push('\n') return attrs attrs = filter(lambda (name, kind, cls, value): visiblename(name), inspect.classify_class_attrs(object)) mdict = {} for key, kind, homecls, value in attrs: mdict[key] = anchor = '#' + name + '-' + key value = getattr(object, key) try: # The value may not be hashable (e.g., a data attr with # a dict or list value). mdict[value] = anchor except TypeError: pass while attrs: if mro: thisclass = mro.popleft() else: thisclass = attrs[0][2] attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass) if thisclass is __builtin__.object: attrs = inherited continue elif thisclass is object: tag = 'defined here' else: tag = 'inherited from %s' % self.classlink(thisclass, object.__module__) tag += ':<br>\n' # Sort attrs by name. attrs.sort(key=lambda t: t[0]) # Pump out the attrs, segregated by kind. attrs = spill('Methods %s' % tag, attrs, lambda t: t[1] == 'method') attrs = spill('Class methods %s' % tag, attrs, lambda t: t[1] == 'class method') attrs = spill('Static methods %s' % tag, attrs, lambda t: t[1] == 'static method') attrs = spillproperties('Properties %s' % tag, attrs, lambda t: t[1] == 'property') attrs = spilldata('Data and other attributes %s' % tag, attrs, lambda t: t[1] == 'data') assert attrs == [] attrs = inherited contents = ''.join(contents) if name == realname: title = '<a name="%s">class <strong>%s</strong></a>' % ( name, realname) else: title = '<strong>%s</strong> = <a name="%s">class %s</a>' % ( name, name, realname) if bases: parents = [] for base in bases: parents.append(self.classlink(base, object.__module__)) title = title + '(%s)' % join(parents, ', ') doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict) doc = doc and '<tt>%s<br>&nbsp;</tt>' % doc return self.section(title, '#000000', '#ffc8d8', contents, 3, doc) def formatvalue(self, object): """Format an argument default value as text.""" return self.grey('=' + self.repr(object)) def docroutine(self, object, name=None, mod=None, funcs={}, classes={}, methods={}, cl=None): """Produce HTML documentation for a function or method object.""" realname = object.__name__ name = name or realname anchor = (cl and cl.__name__ or '') + '-' + name note = '' skipdocs = 0 if inspect.ismethod(object): imclass = object.im_class if cl: if imclass is not cl: note = ' from ' + self.classlink(imclass, mod) else: if object.im_self: note = ' method of %s instance' % self.classlink( object.im_self.__class__, mod) else: note = ' unbound %s method' % self.classlink(imclass,mod) object = object.im_func if name == realname: title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname) else: if (cl and realname in cl.__dict__ and cl.__dict__[realname] is object): reallink = '<a href="#%s">%s</a>' % ( cl.__name__ + '-' + realname, realname) skipdocs = 1 else: reallink = realname title = '<a name="%s"><strong>%s</strong></a> = %s' % ( anchor, name, reallink) if inspect.isfunction(object): args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) if realname == '<lambda>': title = '<strong>%s</strong> <em>lambda</em> ' % name argspec = argspec[1:-1] # remove parentheses else: argspec = '(...)' decl = title + argspec + (note and self.grey( '<font face="helvetica, arial">%s</font>' % note)) if skipdocs: return '<dl><dt>%s</dt></dl>\n' % decl else: doc = self.markup( getdoc(object), self.preformat, funcs, classes, methods) doc = doc and '<dd><tt>%s</tt></dd>' % doc return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc) def _docproperty(self, name, value, mod): results = [] push = results.append if name: push('<dl><dt><strong>%s</strong></dt>\n' % name) if value.__doc__ is not None: doc = self.markup(getdoc(value), self.preformat) push('<dd><tt>%s</tt></dd>\n' % doc) for attr, tag in [('fget', '<em>get</em>'), ('fset', '<em>set</em>'), ('fdel', '<em>delete</em>')]: func = getattr(value, attr) if func is not None: base = self.document(func, tag, mod) push('<dd>%s</dd>\n' % base) push('</dl>\n') return ''.join(results) def docproperty(self, object, name=None, mod=None, cl=None): """Produce html documentation for a property.""" return self._docproperty(name, object, mod) def docother(self, object, name=None, mod=None, *ignored): """Produce HTML documentation for a data object.""" lhs = name and '<strong>%s</strong> = ' % name or '' return lhs + self.repr(object) def index(self, dir, shadowed=None): """Generate an HTML index for a directory of modules.""" modpkgs = [] if shadowed is None: shadowed = {} seen = {} files = os.listdir(dir) def found(name, ispackage, modpkgs=modpkgs, shadowed=shadowed, seen=seen): if name not in seen: modpkgs.append((name, '', ispackage, name in shadowed)) seen[name] = 1 shadowed[name] = 1 # Package spam/__init__.py takes precedence over module spam.py. for file in files: path = os.path.join(dir, file) if ispackage(path): found(file, 1) for file in files: path = os.path.join(dir, file) if os.path.isfile(path): modname = inspect.getmodulename(file) if modname: found(modname, 0) modpkgs.sort() contents = self.multicolumn(modpkgs, self.modpkglink) return self.bigsection(dir, '#ffffff', '#ee77aa', contents) # -------------------------------------------- text documentation generator class TextRepr(Repr): """Class for safely making a text representation of a Python object.""" def __init__(self): Repr.__init__(self) self.maxlist = self.maxtuple = 20 self.maxdict = 10 self.maxstring = self.maxother = 100 def repr1(self, x, level): if hasattr(type(x), '__name__'): methodname = 'repr_' + join(split(type(x).__name__), '_') if hasattr(self, methodname): return getattr(self, methodname)(x, level) return cram(stripid(repr(x)), self.maxother) def repr_string(self, x, level): test = cram(x, self.maxstring) testrepr = repr(test) if '\\' in test and '\\' not in replace(testrepr, r'\\', ''): # Backslashes are only literal in the string and are never # needed to make any special characters, so show a raw string. return 'r' + testrepr[0] + test + testrepr[0] return testrepr repr_str = repr_string def repr_instance(self, x, level): try: return cram(stripid(repr(x)), self.maxstring) except: return '<%s instance>' % x.__class__.__name__ class TextDoc(Doc): """Formatter class for text documentation.""" # ------------------------------------------- text formatting utilities _repr_instance = TextRepr() repr = _repr_instance.repr def bold(self, text): """Format a string in bold by overstriking.""" return join(map(lambda ch: ch + '\b' + ch, text), '') def indent(self, text, prefix=' '): """Indent text by prepending a given prefix to each line.""" if not text: return '' lines = split(text, '\n') lines = map(lambda line, prefix=prefix: prefix + line, lines) if lines: lines[-1] = rstrip(lines[-1]) return join(lines, '\n') def section(self, title, contents): """Format a section with a given heading.""" return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n' # ---------------------------------------------- type-specific routines def formattree(self, tree, modname, parent=None, prefix=''): """Render in text a class tree as returned by inspect.getclasstree().""" result = '' for entry in tree: if type(entry) is type(()): c, bases = entry result = result + prefix + classname(c, modname) if bases and bases != (parent,): parents = map(lambda c, m=modname: classname(c, m), bases) result = result + '(%s)' % join(parents, ', ') result = result + '\n' elif type(entry) is type([]): result = result + self.formattree( entry, modname, c, prefix + ' ') return result def docmodule(self, object, name=None, mod=None): """Produce text documentation for a given module object.""" name = object.__name__ # ignore the passed-in name synop, desc = splitdoc(getdoc(object)) result = self.section('NAME', name + (synop and ' - ' + synop)) try: all = object.__all__ except AttributeError: all = None try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' result = result + self.section('FILE', file) docloc = self.getdocloc(object) if docloc is not None: result = result + self.section('MODULE DOCS', docloc) if desc: result = result + self.section('DESCRIPTION', desc) classes = [] for key, value in inspect.getmembers(object, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or (inspect.getmodule(value) or object) is object): if visiblename(key, all): classes.append((key, value)) funcs = [] for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if visiblename(key, all): funcs.append((key, value)) data = [] for key, value in inspect.getmembers(object, isdata): if visiblename(key, all): data.append((key, value)) if hasattr(object, '__path__'): modpkgs = [] for file in os.listdir(object.__path__[0]): path = os.path.join(object.__path__[0], file) modname = inspect.getmodulename(file) if modname != '__init__': if modname and modname not in modpkgs: modpkgs.append(modname) elif ispackage(path): modpkgs.append(file + ' (package)') modpkgs.sort() result = result + self.section( 'PACKAGE CONTENTS', join(modpkgs, '\n')) if classes: classlist = map(lambda (key, value): value, classes) contents = [self.formattree( inspect.getclasstree(classlist, 1), name)] for key, value in classes: contents.append(self.document(value, key, name)) result = result + self.section('CLASSES', join(contents, '\n')) if funcs: contents = [] for key, value in funcs: contents.append(self.document(value, key, name)) result = result + self.section('FUNCTIONS', join(contents, '\n')) if data: contents = [] for key, value in data: contents.append(self.docother(value, key, name, 70)) result = result + self.section('DATA', join(contents, '\n')) if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) result = result + self.section('VERSION', version) if hasattr(object, '__date__'): result = result + self.section('DATE', str(object.__date__)) if hasattr(object, '__author__'): result = result + self.section('AUTHOR', str(object.__author__)) if hasattr(object, '__credits__'): result = result + self.section('CREDITS', str(object.__credits__)) return result def docclass(self, object, name=None, mod=None): """Produce text documentation for a given class object.""" realname = object.__name__ name = name or realname bases = object.__bases__ def makename(c, m=object.__module__): return classname(c, m) if name == realname: title = 'class ' + self.bold(realname) else: title = self.bold(name) + ' = class ' + realname if bases: parents = map(makename, bases) title = title + '(%s)' % join(parents, ', ') doc = getdoc(object) contents = doc and [doc + '\n'] or [] push = contents.append # List the mro, if non-trivial. mro = deque(inspect.getmro(object)) if len(mro) > 2: push("Method resolution order:") for base in mro: push(' ' + makename(base)) push('') # Cute little class to pump out a horizontal rule between sections. class HorizontalRule: def __init__(self): self.needone = 0 def maybe(self): if self.needone: push('-' * 70) self.needone = 1 hr = HorizontalRule() def spill(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: push(self.document(getattr(object, name), name, mod, object)) return attrs def spillproperties(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: push(self._docproperty(name, value, mod)) return attrs def spilldata(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: if callable(value) or inspect.isdatadescriptor(value): doc = getdoc(value) else: doc = None push(self.docother(getattr(object, name), name, mod, 70, doc) + '\n') return attrs attrs = filter(lambda (name, kind, cls, value): visiblename(name), inspect.classify_class_attrs(object)) while attrs: if mro: thisclass = mro.popleft() else: thisclass = attrs[0][2] attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass) if thisclass is __builtin__.object: attrs = inherited continue elif thisclass is object: tag = "defined here" else: tag = "inherited from %s" % classname(thisclass, object.__module__) filter(lambda t: not t[0].startswith('_'), attrs) # Sort attrs by name. attrs.sort() # Pump out the attrs, segregated by kind. attrs = spill("Methods %s:\n" % tag, attrs, lambda t: t[1] == 'method') attrs = spill("Class methods %s:\n" % tag, attrs, lambda t: t[1] == 'class method') attrs = spill("Static methods %s:\n" % tag, attrs, lambda t: t[1] == 'static method') attrs = spillproperties("Properties %s:\n" % tag, attrs, lambda t: t[1] == 'property') attrs = spilldata("Data and other attributes %s:\n" % tag, attrs, lambda t: t[1] == 'data') assert attrs == [] attrs = inherited contents = '\n'.join(contents) if not contents: return title + '\n' return title + '\n' + self.indent(rstrip(contents), ' | ') + '\n' def formatvalue(self, object): """Format an argument default value as text.""" return '=' + self.repr(object) def docroutine(self, object, name=None, mod=None, cl=None): """Produce text documentation for a function or method object.""" realname = object.__name__ name = name or realname note = '' skipdocs = 0 if inspect.ismethod(object): imclass = object.im_class if cl: if imclass is not cl: note = ' from ' + classname(imclass, mod) else: if object.im_self: note = ' method of %s instance' % classname( object.im_self.__class__, mod) else: note = ' unbound %s method' % classname(imclass,mod) object = object.im_func if name == realname: title = self.bold(realname) else: if (cl and realname in cl.__dict__ and cl.__dict__[realname] is object): skipdocs = 1 title = self.bold(name) + ' = ' + realname if inspect.isfunction(object): args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) if realname == '<lambda>': title = 'lambda' argspec = argspec[1:-1] # remove parentheses else: argspec = '(...)' decl = title + argspec + note if skipdocs: return decl + '\n' else: doc = getdoc(object) or '' return decl + '\n' + (doc and rstrip(self.indent(doc)) + '\n') def _docproperty(self, name, value, mod): results = [] push = results.append if name: push(name) need_blank_after_doc = 0 doc = getdoc(value) or '' if doc: push(self.indent(doc)) need_blank_after_doc = 1 for attr, tag in [('fget', '<get>'), ('fset', '<set>'), ('fdel', '<delete>')]: func = getattr(value, attr) if func is not None: if need_blank_after_doc: push('') need_blank_after_doc = 0 base = self.document(func, tag, mod) push(self.indent(base)) return '\n'.join(results) def docproperty(self, object, name=None, mod=None, cl=None): """Produce text documentation for a property.""" return self._docproperty(name, object, mod) def docother(self, object, name=None, mod=None, maxlen=None, doc=None): """Produce text documentation for a data object.""" repr = self.repr(object) if maxlen: line = (name and name + ' = ' or '') + repr chop = maxlen - len(line) if chop < 0: repr = repr[:chop] + '...' line = (name and self.bold(name) + ' = ' or '') + repr if doc is not None: line += '\n' + self.indent(str(doc)) return line # --------------------------------------------------------- user interfaces def pager(text): """The first time this is called, determine what kind of pager to use.""" global pager pager = getpager() pager(text) def getpager(): """Decide what method to use for paging through text.""" if type(sys.stdout) is not types.FileType: return plainpager if not sys.stdin.isatty() or not sys.stdout.isatty(): return plainpager if os.environ.get('TERM') in ['dumb', 'emacs']: return plainpager if 'PAGER' in os.environ: if sys.platform == 'win32': # pipes completely broken in Windows return lambda text: tempfilepager(plain(text), os.environ['PAGER']) elif os.environ.get('TERM') in ['dumb', 'emacs']: return lambda text: pipepager(plain(text), os.environ['PAGER']) else: return lambda text: pipepager(text, os.environ['PAGER']) if sys.platform == 'win32' or sys.platform.startswith('os2'): return lambda text: tempfilepager(plain(text), 'more <') if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0: return lambda text: pipepager(text, 'less') import tempfile (fd, filename) = tempfile.mkstemp() os.close(fd) try: if hasattr(os, 'system') and os.system('more %s' % filename) == 0: return lambda text: pipepager(text, 'more') else: return ttypager finally: os.unlink(filename) def plain(text): """Remove boldface formatting from text.""" return re.sub('.\b', '', text) def pipepager(text, cmd): """Page through text by feeding it to another program.""" pipe = os.popen(cmd, 'w') try: pipe.write(text) pipe.close() except IOError: pass # Ignore broken pipes caused by quitting the pager program. def tempfilepager(text, cmd): """Page through text by invoking a program on a temporary file.""" import tempfile filename = tempfile.mktemp() file = open(filename, 'w') file.write(text) file.close() try: os.system(cmd + ' ' + filename) finally: os.unlink(filename) def ttypager(text): """Page through text on a text terminal.""" lines = split(plain(text), '\n') try: import tty fd = sys.stdin.fileno() old = tty.tcgetattr(fd) tty.setcbreak(fd) getchar = lambda: sys.stdin.read(1) except (ImportError, AttributeError): tty = None getchar = lambda: sys.stdin.readline()[:-1][:1] try: r = inc = os.environ.get('LINES', 25) - 1 sys.stdout.write(join(lines[:inc], '\n') + '\n') while lines[r:]: sys.stdout.write('-- more --') sys.stdout.flush() c = getchar() if c in ['q', 'Q']: sys.stdout.write('\r \r') break elif c in ['\r', '\n']: sys.stdout.write('\r \r' + lines[r] + '\n') r = r + 1 continue if c in ['b', 'B', '\x1b']: r = r - inc - inc if r < 0: r = 0 sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n') r = r + inc finally: if tty: tty.tcsetattr(fd, tty.TCSAFLUSH, old) def plainpager(text): """Simply print unformatted text. This is the ultimate fallback.""" sys.stdout.write(plain(text)) def describe(thing): """Produce a short description of the given thing.""" if inspect.ismodule(thing): if thing.__name__ in sys.builtin_module_names: return 'built-in module ' + thing.__name__ if hasattr(thing, '__path__'): return 'package ' + thing.__name__ else: return 'module ' + thing.__name__ if inspect.isbuiltin(thing): return 'built-in function ' + thing.__name__ if inspect.isclass(thing): return 'class ' + thing.__name__ if inspect.isfunction(thing): return 'function ' + thing.__name__ if inspect.ismethod(thing): return 'method ' + thing.__name__ if type(thing) is types.InstanceType: return 'instance of ' + thing.__class__.__name__ return type(thing).__name__ def locate(path, forceload=0): """Locate an object by name or dotted path, importing as necessary.""" parts = [part for part in split(path, '.') if part] module, n = None, 0 while n < len(parts): nextmodule = safeimport(join(parts[:n+1], '.'), forceload) if nextmodule: module, n = nextmodule, n + 1 else: break if module: object = module for part in parts[n:]: try: object = getattr(object, part) except AttributeError: return None return object else: if hasattr(__builtin__, path): return getattr(__builtin__, path) # --------------------------------------- interactive interpreter interface text = TextDoc() html = HTMLDoc() def resolve(thing, forceload=0): """Given an object or a path to an object, get the object and its name.""" if isinstance(thing, str): object = locate(thing, forceload) if not object: raise ImportError, 'no Python documentation found for %r' % thing return object, thing else: return thing, getattr(thing, '__name__', None) def doc(thing, title='Python Library Documentation: %s', forceload=0): """Display text documentation, given an object or a path to an object.""" try: object, name = resolve(thing, forceload) desc = describe(object) module = inspect.getmodule(object) if name and '.' in name: desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ if not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or isinstance(object, property)): # If the passed object is a piece of data or an instance, # document its available methods instead of its value. object = type(object) desc += ' object' pager(title % desc + '\n\n' + text.document(object, name)) except (ImportError, ErrorDuringImport), value: print value def writedoc(thing, forceload=0): """Write HTML documentation to a file in the current directory.""" try: object, name = resolve(thing, forceload) page = html.page(describe(object), html.document(object, name)) file = open(name + '.html', 'w') file.write(page) file.close() print 'wrote', name + '.html' except (ImportError, ErrorDuringImport), value: print value def writedocs(dir, pkgpath='', done=None): """Write out HTML documentation for all modules in a directory tree.""" if done is None: done = {} for file in os.listdir(dir): path = os.path.join(dir, file) if ispackage(path): writedocs(path, pkgpath + file + '.', done) elif os.path.isfile(path): modname = inspect.getmodulename(path) if modname: if modname == '__init__': modname = pkgpath[:-1] # remove trailing period else: modname = pkgpath + modname if modname not in done: done[modname] = 1 writedoc(modname) class Helper: keywords = { 'and': 'BOOLEAN', 'assert': ('ref/assert', ''), 'break': ('ref/break', 'while for'), 'class': ('ref/class', 'CLASSES SPECIALMETHODS'), 'continue': ('ref/continue', 'while for'), 'def': ('ref/function', ''), 'del': ('ref/del', 'BASICMETHODS'), 'elif': 'if', 'else': ('ref/if', 'while for'), 'except': 'try', 'exec': ('ref/exec', ''), 'finally': 'try', 'for': ('ref/for', 'break continue while'), 'from': 'import', 'global': ('ref/global', 'NAMESPACES'), 'if': ('ref/if', 'TRUTHVALUE'), 'import': ('ref/import', 'MODULES'), 'in': ('ref/comparisons', 'SEQUENCEMETHODS2'), 'is': 'COMPARISON', 'lambda': ('ref/lambdas', 'FUNCTIONS'), 'not': 'BOOLEAN', 'or': 'BOOLEAN', 'pass': ('ref/pass', ''), 'print': ('ref/print', ''), 'raise': ('ref/raise', 'EXCEPTIONS'), 'return': ('ref/return', 'FUNCTIONS'), 'try': ('ref/try', 'EXCEPTIONS'), 'while': ('ref/while', 'break continue if TRUTHVALUE'), 'yield': ('ref/yield', ''), } topics = { 'TYPES': ('ref/types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS FUNCTIONS CLASSES MODULES FILES inspect'), 'STRINGS': ('ref/strings', 'str UNICODE SEQUENCES STRINGMETHODS FORMATTING TYPES'), 'STRINGMETHODS': ('lib/string-methods', 'STRINGS FORMATTING'), 'FORMATTING': ('lib/typesseq-strings', 'OPERATORS'), 'UNICODE': ('ref/strings', 'encodings unicode SEQUENCES STRINGMETHODS FORMATTING TYPES'), 'NUMBERS': ('ref/numbers', 'INTEGER FLOAT COMPLEX TYPES'), 'INTEGER': ('ref/integers', 'int range'), 'FLOAT': ('ref/floating', 'float math'), 'COMPLEX': ('ref/imaginary', 'complex cmath'), 'SEQUENCES': ('lib/typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'), 'MAPPINGS': 'DICTIONARIES', 'FUNCTIONS': ('lib/typesfunctions', 'def TYPES'), 'METHODS': ('lib/typesmethods', 'class def CLASSES TYPES'), 'CODEOBJECTS': ('lib/bltin-code-objects', 'compile FUNCTIONS TYPES'), 'TYPEOBJECTS': ('lib/bltin-type-objects', 'types TYPES'), 'FRAMEOBJECTS': 'TYPES', 'TRACEBACKS': 'TYPES', 'NONE': ('lib/bltin-null-object', ''), 'ELLIPSIS': ('lib/bltin-ellipsis-object', 'SLICINGS'), 'FILES': ('lib/bltin-file-objects', ''), 'SPECIALATTRIBUTES': ('lib/specialattrs', ''), 'CLASSES': ('ref/types', 'class SPECIALMETHODS PRIVATENAMES'), 'MODULES': ('lib/typesmodules', 'import'), 'PACKAGES': 'import', 'EXPRESSIONS': ('ref/summary', 'lambda or and not in is BOOLEAN COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES LISTS DICTIONARIES BACKQUOTES'), 'OPERATORS': 'EXPRESSIONS', 'PRECEDENCE': 'EXPRESSIONS', 'OBJECTS': ('ref/objects', 'TYPES'), 'SPECIALMETHODS': ('ref/specialnames', 'BASICMETHODS ATTRIBUTEMETHODS CALLABLEMETHODS SEQUENCEMETHODS1 MAPPINGMETHODS SEQUENCEMETHODS2 NUMBERMETHODS CLASSES'), 'BASICMETHODS': ('ref/customization', 'cmp hash repr str SPECIALMETHODS'), 'ATTRIBUTEMETHODS': ('ref/attribute-access', 'ATTRIBUTES SPECIALMETHODS'), 'CALLABLEMETHODS': ('ref/callable-types', 'CALLS SPECIALMETHODS'), 'SEQUENCEMETHODS1': ('ref/sequence-types', 'SEQUENCES SEQUENCEMETHODS2 SPECIALMETHODS'), 'SEQUENCEMETHODS2': ('ref/sequence-methods', 'SEQUENCES SEQUENCEMETHODS1 SPECIALMETHODS'), 'MAPPINGMETHODS': ('ref/sequence-types', 'MAPPINGS SPECIALMETHODS'), 'NUMBERMETHODS': ('ref/numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT SPECIALMETHODS'), 'EXECUTION': ('ref/execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'), 'NAMESPACES': ('ref/naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'), 'DYNAMICFEATURES': ('ref/dynamic-features', ''), 'SCOPING': 'NAMESPACES', 'FRAMES': 'NAMESPACES', 'EXCEPTIONS': ('ref/exceptions', 'try except finally raise'), 'COERCIONS': ('ref/coercion-rules','CONVERSIONS'), 'CONVERSIONS': ('ref/conversions', 'COERCIONS'), 'IDENTIFIERS': ('ref/identifiers', 'keywords SPECIALIDENTIFIERS'), 'SPECIALIDENTIFIERS': ('ref/id-classes', ''), 'PRIVATENAMES': ('ref/atom-identifiers', ''), 'LITERALS': ('ref/atom-literals', 'STRINGS BACKQUOTES NUMBERS TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'), 'TUPLES': 'SEQUENCES', 'TUPLELITERALS': ('ref/exprlists', 'TUPLES LITERALS'), 'LISTS': ('lib/typesseq-mutable', 'LISTLITERALS'), 'LISTLITERALS': ('ref/lists', 'LISTS LITERALS'), 'DICTIONARIES': ('lib/typesmapping', 'DICTIONARYLITERALS'), 'DICTIONARYLITERALS': ('ref/dict', 'DICTIONARIES LITERALS'), 'BACKQUOTES': ('ref/string-conversions', 'repr str STRINGS LITERALS'), 'ATTRIBUTES': ('ref/attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'), 'SUBSCRIPTS': ('ref/subscriptions', 'SEQUENCEMETHODS1'), 'SLICINGS': ('ref/slicings', 'SEQUENCEMETHODS2'), 'CALLS': ('ref/calls', 'EXPRESSIONS'), 'POWER': ('ref/power', 'EXPRESSIONS'), 'UNARY': ('ref/unary', 'EXPRESSIONS'), 'BINARY': ('ref/binary', 'EXPRESSIONS'), 'SHIFTING': ('ref/shifting', 'EXPRESSIONS'), 'BITWISE': ('ref/bitwise', 'EXPRESSIONS'), 'COMPARISON': ('ref/comparisons', 'EXPRESSIONS BASICMETHODS'), 'BOOLEAN': ('ref/Booleans', 'EXPRESSIONS TRUTHVALUE'), 'ASSERTION': 'assert', 'ASSIGNMENT': ('ref/assignment', 'AUGMENTEDASSIGNMENT'), 'AUGMENTEDASSIGNMENT': ('ref/augassign', 'NUMBERMETHODS'), 'DELETION': 'del', 'PRINTING': 'print', 'RETURNING': 'return', 'IMPORTING': 'import', 'CONDITIONAL': 'if', 'LOOPING': ('ref/compound', 'for while break continue'), 'TRUTHVALUE': ('lib/truth', 'if while and or not BASICMETHODS'), 'DEBUGGING': ('lib/module-pdb', 'pdb'), } def __init__(self, input, output): self.input = input self.output = output self.docdir = None execdir = os.path.dirname(sys.executable) homedir = os.environ.get('PYTHONHOME') for dir in [os.environ.get('PYTHONDOCS'), homedir and os.path.join(homedir, 'doc'), os.path.join(execdir, 'doc'), '/usr/doc/python-docs-' + split(sys.version)[0], '/usr/doc/python-' + split(sys.version)[0], '/usr/doc/python-docs-' + sys.version[:3], '/usr/doc/python-' + sys.version[:3], os.path.join(sys.prefix, 'Resources/English.lproj/Documentation')]: if dir and os.path.isdir(os.path.join(dir, 'lib')): self.docdir = dir def __repr__(self): if inspect.stack()[1][3] == '?': self() return '' return '<pydoc.Helper instance>' def __call__(self, request=None): if request is not None: self.help(request) else: self.intro() self.interact() self.output.write(''' You are now leaving help and returning to the Python interpreter. If you want to ask for help on a particular object directly from the interpreter, you can type "help(object)". Executing "help('string')" has the same effect as typing a particular string at the help> prompt. ''') def interact(self): self.output.write('\n') while True: try: request = self.getline('help> ') if not request: break except (KeyboardInterrupt, EOFError): break request = strip(replace(request, '"', '', "'", '')) if lower(request) in ['q', 'quit']: break self.help(request) def getline(self, prompt): """Read one line, using raw_input when available.""" if self.input is sys.stdin: return raw_input(prompt) else: self.output.write(prompt) self.output.flush() return self.input.readline() def help(self, request): if type(request) is type(''): if request == 'help': self.intro() elif request == 'keywords': self.listkeywords() elif request == 'topics': self.listtopics() elif request == 'modules': self.listmodules() elif request[:8] == 'modules ': self.listmodules(split(request)[1]) elif request in self.keywords: self.showtopic(request) elif request in self.topics: self.showtopic(request) elif request: doc(request, 'Help on %s:') elif isinstance(request, Helper): self() else: doc(request, 'Help on %s:') self.output.write('\n') def intro(self): self.output.write(''' Welcome to Python %s! This is the online help utility. If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://www.python.org/doc/tut/. Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit". To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as "spam", type "modules spam". ''' % sys.version[:3]) def list(self, items, columns=4, width=80): items = items[:] items.sort() colw = width / columns rows = (len(items) + columns - 1) / columns for row in range(rows): for col in range(columns): i = col * rows + row if i < len(items): self.output.write(items[i]) if col < columns - 1: self.output.write(' ' + ' ' * (colw-1 - len(items[i]))) self.output.write('\n') def listkeywords(self): self.output.write(''' Here is a list of the Python keywords. Enter any keyword to get more help. ''') self.list(self.keywords.keys()) def listtopics(self): self.output.write(''' Here is a list of available topics. Enter any topic name to get more help. ''') self.list(self.topics.keys()) def showtopic(self, topic): if not self.docdir: self.output.write(''' Sorry, topic and keyword documentation is not available because the Python HTML documentation files could not be found. If you have installed them, please set the environment variable PYTHONDOCS to indicate their location. ''') return target = self.topics.get(topic, self.keywords.get(topic)) if not target: self.output.write('no documentation found for %s\n' % repr(topic)) return if type(target) is type(''): return self.showtopic(target) filename, xrefs = target filename = self.docdir + '/' + filename + '.html' try: file = open(filename) except: self.output.write('could not read docs from %s\n' % filename) return divpat = re.compile('<div[^>]*navigat.*?</div.*?>', re.I | re.S) addrpat = re.compile('<address.*?>.*?</address.*?>', re.I | re.S) document = re.sub(addrpat, '', re.sub(divpat, '', file.read())) file.close() import htmllib, formatter, StringIO buffer = StringIO.StringIO() parser = htmllib.HTMLParser( formatter.AbstractFormatter(formatter.DumbWriter(buffer))) parser.start_table = parser.do_p parser.end_table = lambda parser=parser: parser.do_p({}) parser.start_tr = parser.do_br parser.start_td = parser.start_th = lambda a, b=buffer: b.write('\t') parser.feed(document) buffer = replace(buffer.getvalue(), '\xa0', ' ', '\n', '\n ') pager(' ' + strip(buffer) + '\n') if xrefs: buffer = StringIO.StringIO() formatter.DumbWriter(buffer).send_flowing_data( 'Related help topics: ' + join(split(xrefs), ', ') + '\n') self.output.write('\n%s\n' % buffer.getvalue()) def listmodules(self, key=''): if key: self.output.write(''' Here is a list of matching modules. Enter any module name to get more help. ''') apropos(key) else: self.output.write(''' Please wait a moment while I gather a list of all available modules... ''') modules = {} def callback(path, modname, desc, modules=modules): if modname and modname[-9:] == '.__init__': modname = modname[:-9] + ' (package)' if find(modname, '.') < 0: modules[modname] = 1 ModuleScanner().run(callback) self.list(modules.keys()) self.output.write(''' Enter any module name to get more help. Or, type "modules spam" to search for modules whose descriptions contain the word "spam". ''') help = Helper(sys.stdin, sys.stdout) class Scanner: """A generic tree iterator.""" def __init__(self, roots, children, descendp): self.roots = roots[:] self.state = [] self.children = children self.descendp = descendp def next(self): if not self.state: if not self.roots: return None root = self.roots.pop(0) self.state = [(root, self.children(root))] node, children = self.state[-1] if not children: self.state.pop() return self.next() child = children.pop(0) if self.descendp(child): self.state.append((child, self.children(child))) return child class ModuleScanner(Scanner): """An interruptible scanner that searches module synopses.""" def __init__(self): roots = map(lambda dir: (dir, ''), pathdirs()) Scanner.__init__(self, roots, self.submodules, self.isnewpackage) self.inodes = map(lambda (dir, pkg): os.stat(dir).st_ino, roots) def submodules(self, (dir, package)): children = [] for file in os.listdir(dir): path = os.path.join(dir, file) if ispackage(path): children.append((path, package + (package and '.') + file)) else: children.append((path, package)) children.sort() # so that spam.py comes before spam.pyc or spam.pyo return children def isnewpackage(self, (dir, package)): inode = os.path.exists(dir) and os.stat(dir).st_ino if not (os.path.islink(dir) and inode in self.inodes): self.inodes.append(inode) # detect circular symbolic links return ispackage(dir) return False def run(self, callback, key=None, completer=None): if key: key = lower(key) self.quit = False seen = {} for modname in sys.builtin_module_names: if modname != '__main__': seen[modname] = 1 if key is None: callback(None, modname, '') else: desc = split(__import__(modname).__doc__ or '', '\n')[0] if find(lower(modname + ' - ' + desc), key) >= 0: callback(None, modname, desc) while not self.quit: node = self.next() if not node: break path, package = node modname = inspect.getmodulename(path) if os.path.isfile(path) and modname: modname = package + (package and '.') + modname if not modname in seen: seen[modname] = 1 # if we see spam.py, skip spam.pyc if key is None: callback(path, modname, '') else: desc = synopsis(path) or '' if find(lower(modname + ' - ' + desc), key) >= 0: callback(path, modname, desc) if completer: completer() def apropos(key): """Print all the one-line module summaries that contain a substring.""" def callback(path, modname, desc): if modname[-9:] == '.__init__': modname = modname[:-9] + ' (package)' print modname, desc and '- ' + desc try: import warnings except ImportError: pass else: warnings.filterwarnings('ignore') # ignore problems during import ModuleScanner().run(callback, key) # --------------------------------------------------- web browser interface def serve(port, callback=None, completer=None): import BaseHTTPServer, mimetools, select # Patch up mimetools.Message so it doesn't break if rfc822 is reloaded. class Message(mimetools.Message): def __init__(self, fp, seekable=1): Message = self.__class__ Message.__bases__[0].__bases__[0].__init__(self, fp, seekable) self.encodingheader = self.getheader('content-transfer-encoding') self.typeheader = self.getheader('content-type') self.parsetype() self.parseplist() class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler): def send_document(self, title, contents): try: self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write(html.page(title, contents)) except IOError: pass def do_GET(self): path = self.path if path[-5:] == '.html': path = path[:-5] if path[:1] == '/': path = path[1:] if path and path != '.': try: obj = locate(path, forceload=1) except ErrorDuringImport, value: self.send_document(path, html.escape(str(value))) return if obj: self.send_document(describe(obj), html.document(obj, path)) else: self.send_document(path, 'no Python documentation found for %s' % repr(path)) else: heading = html.heading( '<big><big><strong>Python: Index of Modules</strong></big></big>', '#ffffff', '#7799ee') def bltinlink(name): return '<a href="%s.html">%s</a>' % (name, name) names = filter(lambda x: x != '__main__', sys.builtin_module_names) contents = html.multicolumn(names, bltinlink) indices = ['<p>' + html.bigsection( 'Built-in Modules', '#ffffff', '#ee77aa', contents)] seen = {} for dir in pathdirs(): indices.append(html.index(dir, seen)) contents = heading + join(indices) + '''<p align=right> <font color="#909090" face="helvetica, arial"><strong> pydoc</strong> by Ka-Ping Yee &lt;ping@lfw.org&gt;</font>''' self.send_document('Index of Modules', contents) def log_message(self, *args): pass class DocServer(BaseHTTPServer.HTTPServer): def __init__(self, port, callback): host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost' self.address = ('', port) self.url = 'http://%s:%d/' % (host, port) self.callback = callback self.base.__init__(self, self.address, self.handler) def serve_until_quit(self): import select self.quit = False while not self.quit: rd, wr, ex = select.select([self.socket.fileno()], [], [], 1) if rd: self.handle_request() def server_activate(self): self.base.server_activate(self) if self.callback: self.callback(self) DocServer.base = BaseHTTPServer.HTTPServer DocServer.handler = DocHandler DocHandler.MessageClass = Message try: try: DocServer(port, callback).serve_until_quit() except (KeyboardInterrupt, select.error): pass finally: if completer: completer() # ----------------------------------------------------- graphical interface def gui(): """Graphical interface (starts web server and pops up a control window).""" class GUI: def __init__(self, window, port=7464): self.window = window self.server = None self.scanner = None import Tkinter self.server_frm = Tkinter.Frame(window) self.title_lbl = Tkinter.Label(self.server_frm, text='Starting server...\n ') self.open_btn = Tkinter.Button(self.server_frm, text='open browser', command=self.open, state='disabled') self.quit_btn = Tkinter.Button(self.server_frm, text='quit serving', command=self.quit, state='disabled') self.search_frm = Tkinter.Frame(window) self.search_lbl = Tkinter.Label(self.search_frm, text='Search for') self.search_ent = Tkinter.Entry(self.search_frm) self.search_ent.bind('<Return>', self.search) self.stop_btn = Tkinter.Button(self.search_frm, text='stop', pady=0, command=self.stop, state='disabled') if sys.platform == 'win32': # Trying to hide and show this button crashes under Windows. self.stop_btn.pack(side='right') self.window.title('pydoc') self.window.protocol('WM_DELETE_WINDOW', self.quit) self.title_lbl.pack(side='top', fill='x') self.open_btn.pack(side='left', fill='x', expand=1) self.quit_btn.pack(side='right', fill='x', expand=1) self.server_frm.pack(side='top', fill='x') self.search_lbl.pack(side='left') self.search_ent.pack(side='right', fill='x', expand=1) self.search_frm.pack(side='top', fill='x') self.search_ent.focus_set() font = ('helvetica', sys.platform == 'win32' and 8 or 10) self.result_lst = Tkinter.Listbox(window, font=font, height=6) self.result_lst.bind('<Button-1>', self.select) self.result_lst.bind('<Double-Button-1>', self.goto) self.result_scr = Tkinter.Scrollbar(window, orient='vertical', command=self.result_lst.yview) self.result_lst.config(yscrollcommand=self.result_scr.set) self.result_frm = Tkinter.Frame(window) self.goto_btn = Tkinter.Button(self.result_frm, text='go to selected', command=self.goto) self.hide_btn = Tkinter.Button(self.result_frm, text='hide results', command=self.hide) self.goto_btn.pack(side='left', fill='x', expand=1) self.hide_btn.pack(side='right', fill='x', expand=1) self.window.update() self.minwidth = self.window.winfo_width() self.minheight = self.window.winfo_height() self.bigminheight = (self.server_frm.winfo_reqheight() + self.search_frm.winfo_reqheight() + self.result_lst.winfo_reqheight() + self.result_frm.winfo_reqheight()) self.bigwidth, self.bigheight = self.minwidth, self.bigminheight self.expanded = 0 self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight)) self.window.wm_minsize(self.minwidth, self.minheight) self.window.tk.willdispatch() import threading threading.Thread( target=serve, args=(port, self.ready, self.quit)).start() def ready(self, server): self.server = server self.title_lbl.config( text='Python documentation server at\n' + server.url) self.open_btn.config(state='normal') self.quit_btn.config(state='normal') def open(self, event=None, url=None): url = url or self.server.url try: import webbrowser webbrowser.open(url) except ImportError: # pre-webbrowser.py compatibility if sys.platform == 'win32': os.system('start "%s"' % url) elif sys.platform == 'mac': try: import ic except ImportError: pass else: ic.launchurl(url) else: rc = os.system('netscape -remote "openURL(%s)" &' % url) if rc: os.system('netscape "%s" &' % url) def quit(self, event=None): if self.server: self.server.quit = 1 self.window.quit() def search(self, event=None): key = self.search_ent.get() self.stop_btn.pack(side='right') self.stop_btn.config(state='normal') self.search_lbl.config(text='Searching for "%s"...' % key) self.search_ent.forget() self.search_lbl.pack(side='left') self.result_lst.delete(0, 'end') self.goto_btn.config(state='disabled') self.expand() import threading if self.scanner: self.scanner.quit = 1 self.scanner = ModuleScanner() threading.Thread(target=self.scanner.run, args=(self.update, key, self.done)).start() def update(self, path, modname, desc): if modname[-9:] == '.__init__': modname = modname[:-9] + ' (package)' self.result_lst.insert('end', modname + ' - ' + (desc or '(no description)')) def stop(self, event=None): if self.scanner: self.scanner.quit = 1 self.scanner = None def done(self): self.scanner = None self.search_lbl.config(text='Search for') self.search_lbl.pack(side='left') self.search_ent.pack(side='right', fill='x', expand=1) if sys.platform != 'win32': self.stop_btn.forget() self.stop_btn.config(state='disabled') def select(self, event=None): self.goto_btn.config(state='normal') def goto(self, event=None): selection = self.result_lst.curselection() if selection: modname = split(self.result_lst.get(selection[0]))[0] self.open(url=self.server.url + modname + '.html') def collapse(self): if not self.expanded: return self.result_frm.forget() self.result_scr.forget() self.result_lst.forget() self.bigwidth = self.window.winfo_width() self.bigheight = self.window.winfo_height() self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight)) self.window.wm_minsize(self.minwidth, self.minheight) self.expanded = 0 def expand(self): if self.expanded: return self.result_frm.pack(side='bottom', fill='x') self.result_scr.pack(side='right', fill='y') self.result_lst.pack(side='top', fill='both', expand=1) self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight)) self.window.wm_minsize(self.minwidth, self.bigminheight) self.expanded = 1 def hide(self, event=None): self.stop() self.collapse() import Tkinter try: root = Tkinter.Tk() # Tk will crash if pythonw.exe has an XP .manifest # file and the root has is not destroyed explicitly. # If the problem is ever fixed in Tk, the explicit # destroy can go. try: gui = GUI(root) root.mainloop() finally: root.destroy() except KeyboardInterrupt: pass # -------------------------------------------------- command-line interface def ispath(x): return isinstance(x, str) and find(x, os.sep) >= 0 def cli(): """Command-line interface (looks at sys.argv to decide what to do).""" import getopt class BadUsage: pass # Scripts don't get the current directory in their path by default. scriptdir = os.path.dirname(sys.argv[0]) if scriptdir in sys.path: sys.path.remove(scriptdir) sys.path.insert(0, '.') try: opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w') writing = 0 for opt, val in opts: if opt == '-g': gui() return if opt == '-k': apropos(val) return if opt == '-p': try: port = int(val) except ValueError: raise BadUsage def ready(server): print 'pydoc server ready at %s' % server.url def stopped(): print 'pydoc server stopped' serve(port, ready, stopped) return if opt == '-w': writing = 1 if not args: raise BadUsage for arg in args: if ispath(arg) and not os.path.exists(arg): print 'file %r does not exist' % arg break try: if ispath(arg) and os.path.isfile(arg): arg = importfile(arg) if writing: if ispath(arg) and os.path.isdir(arg): writedocs(arg) else: writedoc(arg) else: help.help(arg) except ErrorDuringImport, value: print value except (getopt.error, BadUsage): cmd = os.path.basename(sys.argv[0]) print """pydoc - the Python documentation tool %s <name> ... Show text documentation on something. <name> may be the name of a Python keyword, topic, function, module, or package, or a dotted reference to a class or function within a module or module in a package. If <name> contains a '%s', it is used as the path to a Python source file to document. If name is 'keywords', 'topics', or 'modules', a listing of these things is displayed. %s -k <keyword> Search for a keyword in the synopsis lines of all available modules. %s -p <port> Start an HTTP server on the given port on the local machine. %s -g Pop up a graphical interface for finding and serving documentation. %s -w <name> ... Write out the HTML documentation for a module to a file in the current directory. If <name> contains a '%s', it is treated as a filename; if it names a directory, documentation is written for all the contents. """ % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep) if __name__ == '__main__': cli()
Python
"""Utility functions for copying files and directory trees. XXX The functions here don't copy the resource fork or other metadata on Mac. """ import os import sys import stat import exceptions from os.path import abspath __all__ = ["copyfileobj","copyfile","copymode","copystat","copy","copy2", "copytree","move","rmtree","Error"] class Error(exceptions.EnvironmentError): pass def copyfileobj(fsrc, fdst, length=16*1024): """copy data from file-like object fsrc to file-like object fdst""" while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf) def _samefile(src, dst): # Macintosh, Unix. if hasattr(os.path,'samefile'): try: return os.path.samefile(src, dst) except OSError: return False # All other platforms: check for same pathname. return (os.path.normcase(os.path.abspath(src)) == os.path.normcase(os.path.abspath(dst))) def copyfile(src, dst): """Copy data from src to dst""" if _samefile(src, dst): raise Error, "`%s` and `%s` are the same file" % (src, dst) fsrc = None fdst = None try: fsrc = open(src, 'rb') fdst = open(dst, 'wb') copyfileobj(fsrc, fdst) finally: if fdst: fdst.close() if fsrc: fsrc.close() def copymode(src, dst): """Copy mode bits from src to dst""" if hasattr(os, 'chmod'): st = os.stat(src) mode = stat.S_IMODE(st.st_mode) os.chmod(dst, mode) def copystat(src, dst): """Copy all stat info (mode bits, atime and mtime) from src to dst""" st = os.stat(src) mode = stat.S_IMODE(st.st_mode) if hasattr(os, 'utime'): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, 'chmod'): os.chmod(dst, mode) def copy(src, dst): """Copy data and mode bits ("cp src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copymode(src, dst) def copy2(src, dst): """Copy data and all stat info ("cp -p src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copystat(src, dst) def copytree(src, dst, symlinks=False): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. XXX Consider this example code rather than the ultimate tool. """ names = os.listdir(src) os.mkdir(dst) errors = [] for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): copytree(srcname, dstname, symlinks) else: copy2(srcname, dstname) # XXX What about devices, sockets etc.? except (IOError, os.error), why: errors.append((srcname, dstname, why)) if errors: raise Error, errors def rmtree(path, ignore_errors=False, onerror=None): """Recursively delete a directory tree. If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised. """ if ignore_errors: def onerror(*args): pass elif onerror is None: def onerror(*args): raise names = [] try: names = os.listdir(path) except os.error, err: onerror(os.listdir, path, sys.exc_info()) for name in names: fullname = os.path.join(path, name) try: mode = os.lstat(fullname).st_mode except os.error: mode = 0 if stat.S_ISDIR(mode): rmtree(fullname, ignore_errors, onerror) else: try: os.remove(fullname) except os.error, err: onerror(os.remove, fullname, sys.exc_info()) try: os.rmdir(path) except os.error: onerror(os.rmdir, path, sys.exc_info()) def move(src, dst): """Recursively move a file or directory to another location. If the destination is on our current filesystem, then simply use rename. Otherwise, copy src to the dst and then remove src. A lot more could be done here... A look at a mv.c shows a lot of the issues this implementation glosses over. """ try: os.rename(src, dst) except OSError: if os.path.isdir(src): if destinsrc(src, dst): raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst) copytree(src, dst, symlinks=True) rmtree(src) else: copy2(src,dst) os.unlink(src) def destinsrc(src, dst): return abspath(dst).startswith(abspath(src))
Python
""" Python Character Mapping Codec generated from 'GREEK.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x0081: 0x00b9, # SUPERSCRIPT ONE 0x0082: 0x00b2, # SUPERSCRIPT TWO 0x0083: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0084: 0x00b3, # SUPERSCRIPT THREE 0x0085: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x0086: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x0087: 0x0385, # GREEK DIALYTIKA TONOS 0x0088: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0089: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x008a: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x008b: 0x0384, # GREEK TONOS 0x008c: 0x00a8, # DIAERESIS 0x008d: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x008e: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x008f: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x0090: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0091: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x0092: 0x00a3, # POUND SIGN 0x0093: 0x2122, # TRADE MARK SIGN 0x0094: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x0095: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x0096: 0x2022, # BULLET 0x0097: 0x00bd, # VULGAR FRACTION ONE HALF 0x0098: 0x2030, # PER MILLE SIGN 0x0099: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x009a: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x009b: 0x00a6, # BROKEN BAR 0x009c: 0x00ad, # SOFT HYPHEN 0x009d: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x009e: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x009f: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x00a0: 0x2020, # DAGGER 0x00a1: 0x0393, # GREEK CAPITAL LETTER GAMMA 0x00a2: 0x0394, # GREEK CAPITAL LETTER DELTA 0x00a3: 0x0398, # GREEK CAPITAL LETTER THETA 0x00a4: 0x039b, # GREEK CAPITAL LETTER LAMBDA 0x00a5: 0x039e, # GREEK CAPITAL LETTER XI 0x00a6: 0x03a0, # GREEK CAPITAL LETTER PI 0x00a7: 0x00df, # LATIN SMALL LETTER SHARP S 0x00a8: 0x00ae, # REGISTERED SIGN 0x00aa: 0x03a3, # GREEK CAPITAL LETTER SIGMA 0x00ab: 0x03aa, # GREEK CAPITAL LETTER IOTA WITH DIALYTIKA 0x00ac: 0x00a7, # SECTION SIGN 0x00ad: 0x2260, # NOT EQUAL TO 0x00ae: 0x00b0, # DEGREE SIGN 0x00af: 0x0387, # GREEK ANO TELEIA 0x00b0: 0x0391, # GREEK CAPITAL LETTER ALPHA 0x00b2: 0x2264, # LESS-THAN OR EQUAL TO 0x00b3: 0x2265, # GREATER-THAN OR EQUAL TO 0x00b4: 0x00a5, # YEN SIGN 0x00b5: 0x0392, # GREEK CAPITAL LETTER BETA 0x00b6: 0x0395, # GREEK CAPITAL LETTER EPSILON 0x00b7: 0x0396, # GREEK CAPITAL LETTER ZETA 0x00b8: 0x0397, # GREEK CAPITAL LETTER ETA 0x00b9: 0x0399, # GREEK CAPITAL LETTER IOTA 0x00ba: 0x039a, # GREEK CAPITAL LETTER KAPPA 0x00bb: 0x039c, # GREEK CAPITAL LETTER MU 0x00bc: 0x03a6, # GREEK CAPITAL LETTER PHI 0x00bd: 0x03ab, # GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA 0x00be: 0x03a8, # GREEK CAPITAL LETTER PSI 0x00bf: 0x03a9, # GREEK CAPITAL LETTER OMEGA 0x00c0: 0x03ac, # GREEK SMALL LETTER ALPHA WITH TONOS 0x00c1: 0x039d, # GREEK CAPITAL LETTER NU 0x00c2: 0x00ac, # NOT SIGN 0x00c3: 0x039f, # GREEK CAPITAL LETTER OMICRON 0x00c4: 0x03a1, # GREEK CAPITAL LETTER RHO 0x00c5: 0x2248, # ALMOST EQUAL TO 0x00c6: 0x03a4, # GREEK CAPITAL LETTER TAU 0x00c7: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c8: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c9: 0x2026, # HORIZONTAL ELLIPSIS 0x00ca: 0x00a0, # NO-BREAK SPACE 0x00cb: 0x03a5, # GREEK CAPITAL LETTER UPSILON 0x00cc: 0x03a7, # GREEK CAPITAL LETTER CHI 0x00cd: 0x0386, # GREEK CAPITAL LETTER ALPHA WITH TONOS 0x00ce: 0x0388, # GREEK CAPITAL LETTER EPSILON WITH TONOS 0x00cf: 0x0153, # LATIN SMALL LIGATURE OE 0x00d0: 0x2013, # EN DASH 0x00d1: 0x2015, # HORIZONTAL BAR 0x00d2: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x00d3: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x00d4: 0x2018, # LEFT SINGLE QUOTATION MARK 0x00d5: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x00d6: 0x00f7, # DIVISION SIGN 0x00d7: 0x0389, # GREEK CAPITAL LETTER ETA WITH TONOS 0x00d8: 0x038a, # GREEK CAPITAL LETTER IOTA WITH TONOS 0x00d9: 0x038c, # GREEK CAPITAL LETTER OMICRON WITH TONOS 0x00da: 0x038e, # GREEK CAPITAL LETTER UPSILON WITH TONOS 0x00db: 0x03ad, # GREEK SMALL LETTER EPSILON WITH TONOS 0x00dc: 0x03ae, # GREEK SMALL LETTER ETA WITH TONOS 0x00dd: 0x03af, # GREEK SMALL LETTER IOTA WITH TONOS 0x00de: 0x03cc, # GREEK SMALL LETTER OMICRON WITH TONOS 0x00df: 0x038f, # GREEK CAPITAL LETTER OMEGA WITH TONOS 0x00e0: 0x03cd, # GREEK SMALL LETTER UPSILON WITH TONOS 0x00e1: 0x03b1, # GREEK SMALL LETTER ALPHA 0x00e2: 0x03b2, # GREEK SMALL LETTER BETA 0x00e3: 0x03c8, # GREEK SMALL LETTER PSI 0x00e4: 0x03b4, # GREEK SMALL LETTER DELTA 0x00e5: 0x03b5, # GREEK SMALL LETTER EPSILON 0x00e6: 0x03c6, # GREEK SMALL LETTER PHI 0x00e7: 0x03b3, # GREEK SMALL LETTER GAMMA 0x00e8: 0x03b7, # GREEK SMALL LETTER ETA 0x00e9: 0x03b9, # GREEK SMALL LETTER IOTA 0x00ea: 0x03be, # GREEK SMALL LETTER XI 0x00eb: 0x03ba, # GREEK SMALL LETTER KAPPA 0x00ec: 0x03bb, # GREEK SMALL LETTER LAMBDA 0x00ed: 0x03bc, # GREEK SMALL LETTER MU 0x00ee: 0x03bd, # GREEK SMALL LETTER NU 0x00ef: 0x03bf, # GREEK SMALL LETTER OMICRON 0x00f0: 0x03c0, # GREEK SMALL LETTER PI 0x00f1: 0x03ce, # GREEK SMALL LETTER OMEGA WITH TONOS 0x00f2: 0x03c1, # GREEK SMALL LETTER RHO 0x00f3: 0x03c3, # GREEK SMALL LETTER SIGMA 0x00f4: 0x03c4, # GREEK SMALL LETTER TAU 0x00f5: 0x03b8, # GREEK SMALL LETTER THETA 0x00f6: 0x03c9, # GREEK SMALL LETTER OMEGA 0x00f7: 0x03c2, # GREEK SMALL LETTER FINAL SIGMA 0x00f8: 0x03c7, # GREEK SMALL LETTER CHI 0x00f9: 0x03c5, # GREEK SMALL LETTER UPSILON 0x00fa: 0x03b6, # GREEK SMALL LETTER ZETA 0x00fb: 0x03ca, # GREEK SMALL LETTER IOTA WITH DIALYTIKA 0x00fc: 0x03cb, # GREEK SMALL LETTER UPSILON WITH DIALYTIKA 0x00fd: 0x0390, # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS 0x00fe: 0x03b0, # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS 0x00ff: None, # UNDEFINED }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP856.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x05d0, # HEBREW LETTER ALEF 0x0081: 0x05d1, # HEBREW LETTER BET 0x0082: 0x05d2, # HEBREW LETTER GIMEL 0x0083: 0x05d3, # HEBREW LETTER DALET 0x0084: 0x05d4, # HEBREW LETTER HE 0x0085: 0x05d5, # HEBREW LETTER VAV 0x0086: 0x05d6, # HEBREW LETTER ZAYIN 0x0087: 0x05d7, # HEBREW LETTER HET 0x0088: 0x05d8, # HEBREW LETTER TET 0x0089: 0x05d9, # HEBREW LETTER YOD 0x008a: 0x05da, # HEBREW LETTER FINAL KAF 0x008b: 0x05db, # HEBREW LETTER KAF 0x008c: 0x05dc, # HEBREW LETTER LAMED 0x008d: 0x05dd, # HEBREW LETTER FINAL MEM 0x008e: 0x05de, # HEBREW LETTER MEM 0x008f: 0x05df, # HEBREW LETTER FINAL NUN 0x0090: 0x05e0, # HEBREW LETTER NUN 0x0091: 0x05e1, # HEBREW LETTER SAMEKH 0x0092: 0x05e2, # HEBREW LETTER AYIN 0x0093: 0x05e3, # HEBREW LETTER FINAL PE 0x0094: 0x05e4, # HEBREW LETTER PE 0x0095: 0x05e5, # HEBREW LETTER FINAL TSADI 0x0096: 0x05e6, # HEBREW LETTER TSADI 0x0097: 0x05e7, # HEBREW LETTER QOF 0x0098: 0x05e8, # HEBREW LETTER RESH 0x0099: 0x05e9, # HEBREW LETTER SHIN 0x009a: 0x05ea, # HEBREW LETTER TAV 0x009b: None, # UNDEFINED 0x009c: 0x00a3, # POUND SIGN 0x009d: None, # UNDEFINED 0x009e: 0x00d7, # MULTIPLICATION SIGN 0x009f: None, # UNDEFINED 0x00a0: None, # UNDEFINED 0x00a1: None, # UNDEFINED 0x00a2: None, # UNDEFINED 0x00a3: None, # UNDEFINED 0x00a4: None, # UNDEFINED 0x00a5: None, # UNDEFINED 0x00a6: None, # UNDEFINED 0x00a7: None, # UNDEFINED 0x00a8: None, # UNDEFINED 0x00a9: 0x00ae, # REGISTERED SIGN 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00ad: None, # UNDEFINED 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: None, # UNDEFINED 0x00b6: None, # UNDEFINED 0x00b7: None, # UNDEFINED 0x00b8: 0x00a9, # COPYRIGHT SIGN 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x00a2, # CENT SIGN 0x00be: 0x00a5, # YEN SIGN 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: None, # UNDEFINED 0x00c7: None, # UNDEFINED 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x00a4, # CURRENCY SIGN 0x00d0: None, # UNDEFINED 0x00d1: None, # UNDEFINED 0x00d2: None, # UNDEFINED 0x00d3: None, # UNDEFINEDS 0x00d4: None, # UNDEFINED 0x00d5: None, # UNDEFINED 0x00d6: None, # UNDEFINEDE 0x00d7: None, # UNDEFINED 0x00d8: None, # UNDEFINED 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x00a6, # BROKEN BAR 0x00de: None, # UNDEFINED 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: None, # UNDEFINED 0x00e1: None, # UNDEFINED 0x00e2: None, # UNDEFINED 0x00e3: None, # UNDEFINED 0x00e4: None, # UNDEFINED 0x00e5: None, # UNDEFINED 0x00e6: 0x00b5, # MICRO SIGN 0x00e7: None, # UNDEFINED 0x00e8: None, # UNDEFINED 0x00e9: None, # UNDEFINED 0x00ea: None, # UNDEFINED 0x00eb: None, # UNDEFINED 0x00ec: None, # UNDEFINED 0x00ed: None, # UNDEFINED 0x00ee: 0x00af, # MACRON 0x00ef: 0x00b4, # ACUTE ACCENT 0x00f0: 0x00ad, # SOFT HYPHEN 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x2017, # DOUBLE LOW LINE 0x00f3: 0x00be, # VULGAR FRACTION THREE QUARTERS 0x00f4: 0x00b6, # PILCROW SIGN 0x00f5: 0x00a7, # SECTION SIGN 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x00b8, # CEDILLA 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x00a8, # DIAERESIS 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x00b9, # SUPERSCRIPT ONE 0x00fc: 0x00b3, # SUPERSCRIPT THREE 0x00fd: 0x00b2, # SUPERSCRIPT TWO 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# # hz.py: Python Unicode Codec for HZ # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: hz.py,v 1.8 2004/06/28 18:16:03 perky Exp $ # import _codecs_cn, codecs codec = _codecs_cn.getcodec('hz') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python 'zlib_codec' Codec - zlib compression encoding Unlike most of the other codecs which target Unicode, this codec will return Python string objects for both encode and decode. Written by Marc-Andre Lemburg (mal@lemburg.com). """ import codecs import zlib # this codec needs the optional zlib module ! ### Codec APIs def zlib_encode(input,errors='strict'): """ Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = zlib.compress(input) return (output, len(input)) def zlib_decode(input,errors='strict'): """ Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = zlib.decompress(input) return (output, len(input)) class Codec(codecs.Codec): def encode(self, input, errors='strict'): return zlib_encode(input, errors) def decode(self, input, errors='strict'): return zlib_decode(input, errors) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (zlib_encode,zlib_decode,StreamReader,StreamWriter)
Python
# # euc_jisx0213.py: Python Unicode Codec for EUC_JISX0213 # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: euc_jisx0213.py,v 1.8 2004/06/28 18:16:03 perky Exp $ # import _codecs_jp, codecs codec = _codecs_jp.getcodec('euc_jisx0213') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP861.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x008b: 0x00d0, # LATIN CAPITAL LETTER ETH 0x008c: 0x00f0, # LATIN SMALL LETTER ETH 0x008d: 0x00de, # LATIN CAPITAL LETTER THORN 0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x00e6, # LATIN SMALL LIGATURE AE 0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x0095: 0x00fe, # LATIN SMALL LETTER THORN 0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x0097: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE 0x0098: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE 0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x009e: 0x20a7, # PESETA SIGN 0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x00a5: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x00a6: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00a7: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00a8: 0x00bf, # INVERTED QUESTION MARK 0x00a9: 0x2310, # REVERSED NOT SIGN 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x258c, # LEFT HALF BLOCK 0x00de: 0x2590, # RIGHT HALF BLOCK 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S 0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA 0x00e3: 0x03c0, # GREEK SMALL LETTER PI 0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA 0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA 0x00e6: 0x00b5, # MICRO SIGN 0x00e7: 0x03c4, # GREEK SMALL LETTER TAU 0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI 0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA 0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA 0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA 0x00ec: 0x221e, # INFINITY 0x00ed: 0x03c6, # GREEK SMALL LETTER PHI 0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON 0x00ef: 0x2229, # INTERSECTION 0x00f0: 0x2261, # IDENTICAL TO 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO 0x00f3: 0x2264, # LESS-THAN OR EQUAL TO 0x00f4: 0x2320, # TOP HALF INTEGRAL 0x00f5: 0x2321, # BOTTOM HALF INTEGRAL 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x2248, # ALMOST EQUAL TO 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x2219, # BULLET OPERATOR 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x221a, # SQUARE ROOT 0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N 0x00fd: 0x00b2, # SUPERSCRIPT TWO 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python 'utf-7' Codec Written by Brian Quinlan (brian@sweetapp.com). """ import codecs ### Codec APIs class Codec(codecs.Codec): # Note: Binding these as C functions will result in the class not # converting them to methods. This is intended. encode = codecs.utf_7_encode decode = codecs.utf_7_decode class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec.encode,Codec.decode,StreamReader,StreamWriter)
Python
# # euc_jp.py: Python Unicode Codec for EUC_JP # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: euc_jp.py,v 1.8 2004/06/28 18:16:03 perky Exp $ # import _codecs_jp, codecs codec = _codecs_jp.getcodec('euc_jp') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP1256.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x20ac, # EURO SIGN 0x0081: 0x067e, # ARABIC LETTER PEH 0x0082: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x0083: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x0084: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x0085: 0x2026, # HORIZONTAL ELLIPSIS 0x0086: 0x2020, # DAGGER 0x0087: 0x2021, # DOUBLE DAGGER 0x0088: 0x02c6, # MODIFIER LETTER CIRCUMFLEX ACCENT 0x0089: 0x2030, # PER MILLE SIGN 0x008a: 0x0679, # ARABIC LETTER TTEH 0x008b: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x008c: 0x0152, # LATIN CAPITAL LIGATURE OE 0x008d: 0x0686, # ARABIC LETTER TCHEH 0x008e: 0x0698, # ARABIC LETTER JEH 0x008f: 0x0688, # ARABIC LETTER DDAL 0x0090: 0x06af, # ARABIC LETTER GAF 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x0095: 0x2022, # BULLET 0x0096: 0x2013, # EN DASH 0x0097: 0x2014, # EM DASH 0x0098: 0x06a9, # ARABIC LETTER KEHEH 0x0099: 0x2122, # TRADE MARK SIGN 0x009a: 0x0691, # ARABIC LETTER RREH 0x009b: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 0x009c: 0x0153, # LATIN SMALL LIGATURE OE 0x009d: 0x200c, # ZERO WIDTH NON-JOINER 0x009e: 0x200d, # ZERO WIDTH JOINER 0x009f: 0x06ba, # ARABIC LETTER NOON GHUNNA 0x00a1: 0x060c, # ARABIC COMMA 0x00aa: 0x06be, # ARABIC LETTER HEH DOACHASHMEE 0x00ba: 0x061b, # ARABIC SEMICOLON 0x00bf: 0x061f, # ARABIC QUESTION MARK 0x00c0: 0x06c1, # ARABIC LETTER HEH GOAL 0x00c1: 0x0621, # ARABIC LETTER HAMZA 0x00c2: 0x0622, # ARABIC LETTER ALEF WITH MADDA ABOVE 0x00c3: 0x0623, # ARABIC LETTER ALEF WITH HAMZA ABOVE 0x00c4: 0x0624, # ARABIC LETTER WAW WITH HAMZA ABOVE 0x00c5: 0x0625, # ARABIC LETTER ALEF WITH HAMZA BELOW 0x00c6: 0x0626, # ARABIC LETTER YEH WITH HAMZA ABOVE 0x00c7: 0x0627, # ARABIC LETTER ALEF 0x00c8: 0x0628, # ARABIC LETTER BEH 0x00c9: 0x0629, # ARABIC LETTER TEH MARBUTA 0x00ca: 0x062a, # ARABIC LETTER TEH 0x00cb: 0x062b, # ARABIC LETTER THEH 0x00cc: 0x062c, # ARABIC LETTER JEEM 0x00cd: 0x062d, # ARABIC LETTER HAH 0x00ce: 0x062e, # ARABIC LETTER KHAH 0x00cf: 0x062f, # ARABIC LETTER DAL 0x00d0: 0x0630, # ARABIC LETTER THAL 0x00d1: 0x0631, # ARABIC LETTER REH 0x00d2: 0x0632, # ARABIC LETTER ZAIN 0x00d3: 0x0633, # ARABIC LETTER SEEN 0x00d4: 0x0634, # ARABIC LETTER SHEEN 0x00d5: 0x0635, # ARABIC LETTER SAD 0x00d6: 0x0636, # ARABIC LETTER DAD 0x00d8: 0x0637, # ARABIC LETTER TAH 0x00d9: 0x0638, # ARABIC LETTER ZAH 0x00da: 0x0639, # ARABIC LETTER AIN 0x00db: 0x063a, # ARABIC LETTER GHAIN 0x00dc: 0x0640, # ARABIC TATWEEL 0x00dd: 0x0641, # ARABIC LETTER FEH 0x00de: 0x0642, # ARABIC LETTER QAF 0x00df: 0x0643, # ARABIC LETTER KAF 0x00e1: 0x0644, # ARABIC LETTER LAM 0x00e3: 0x0645, # ARABIC LETTER MEEM 0x00e4: 0x0646, # ARABIC LETTER NOON 0x00e5: 0x0647, # ARABIC LETTER HEH 0x00e6: 0x0648, # ARABIC LETTER WAW 0x00ec: 0x0649, # ARABIC LETTER ALEF MAKSURA 0x00ed: 0x064a, # ARABIC LETTER YEH 0x00f0: 0x064b, # ARABIC FATHATAN 0x00f1: 0x064c, # ARABIC DAMMATAN 0x00f2: 0x064d, # ARABIC KASRATAN 0x00f3: 0x064e, # ARABIC FATHA 0x00f5: 0x064f, # ARABIC DAMMA 0x00f6: 0x0650, # ARABIC KASRA 0x00f8: 0x0651, # ARABIC SHADDA 0x00fa: 0x0652, # ARABIC SUKUN 0x00fd: 0x200e, # LEFT-TO-RIGHT MARK 0x00fe: 0x200f, # RIGHT-TO-LEFT MARK 0x00ff: 0x06d2, # ARABIC LETTER YEH BARREE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'ICELAND.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x0081: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x0082: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0083: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0084: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x0085: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x0086: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x0087: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x0088: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0089: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x008a: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x008b: 0x00e3, # LATIN SMALL LETTER A WITH TILDE 0x008c: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE 0x008d: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x008e: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x008f: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x0090: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0091: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x0092: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x0093: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE 0x0094: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x0095: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x0096: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x0097: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x0098: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE 0x0099: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x009a: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x009b: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x009c: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x009d: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x009e: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x009f: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x00a0: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00a1: 0x00b0, # DEGREE SIGN 0x00a4: 0x00a7, # SECTION SIGN 0x00a5: 0x2022, # BULLET 0x00a6: 0x00b6, # PILCROW SIGN 0x00a7: 0x00df, # LATIN SMALL LETTER SHARP S 0x00a8: 0x00ae, # REGISTERED SIGN 0x00aa: 0x2122, # TRADE MARK SIGN 0x00ab: 0x00b4, # ACUTE ACCENT 0x00ac: 0x00a8, # DIAERESIS 0x00ad: 0x2260, # NOT EQUAL TO 0x00ae: 0x00c6, # LATIN CAPITAL LIGATURE AE 0x00af: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x00b0: 0x221e, # INFINITY 0x00b2: 0x2264, # LESS-THAN OR EQUAL TO 0x00b3: 0x2265, # GREATER-THAN OR EQUAL TO 0x00b4: 0x00a5, # YEN SIGN 0x00b6: 0x2202, # PARTIAL DIFFERENTIAL 0x00b7: 0x2211, # N-ARY SUMMATION 0x00b8: 0x220f, # N-ARY PRODUCT 0x00b9: 0x03c0, # GREEK SMALL LETTER PI 0x00ba: 0x222b, # INTEGRAL 0x00bb: 0x00aa, # FEMININE ORDINAL INDICATOR 0x00bc: 0x00ba, # MASCULINE ORDINAL INDICATOR 0x00bd: 0x2126, # OHM SIGN 0x00be: 0x00e6, # LATIN SMALL LIGATURE AE 0x00bf: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x00c0: 0x00bf, # INVERTED QUESTION MARK 0x00c1: 0x00a1, # INVERTED EXCLAMATION MARK 0x00c2: 0x00ac, # NOT SIGN 0x00c3: 0x221a, # SQUARE ROOT 0x00c4: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x00c5: 0x2248, # ALMOST EQUAL TO 0x00c6: 0x2206, # INCREMENT 0x00c7: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c8: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c9: 0x2026, # HORIZONTAL ELLIPSIS 0x00ca: 0x00a0, # NO-BREAK SPACE 0x00cb: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE 0x00cc: 0x00c3, # LATIN CAPITAL LETTER A WITH TILDE 0x00cd: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x00ce: 0x0152, # LATIN CAPITAL LIGATURE OE 0x00cf: 0x0153, # LATIN SMALL LIGATURE OE 0x00d0: 0x2013, # EN DASH 0x00d1: 0x2014, # EM DASH 0x00d2: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x00d3: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x00d4: 0x2018, # LEFT SINGLE QUOTATION MARK 0x00d5: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x00d6: 0x00f7, # DIVISION SIGN 0x00d7: 0x25ca, # LOZENGE 0x00d8: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS 0x00d9: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS 0x00da: 0x2044, # FRACTION SLASH 0x00db: 0x00a4, # CURRENCY SIGN 0x00dc: 0x00d0, # LATIN CAPITAL LETTER ETH 0x00dd: 0x00f0, # LATIN SMALL LETTER ETH 0x00df: 0x00fe, # LATIN SMALL LETTER THORN 0x00e0: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE 0x00e1: 0x00b7, # MIDDLE DOT 0x00e2: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x00e3: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x00e4: 0x2030, # PER MILLE SIGN 0x00e5: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00e6: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x00e7: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x00e8: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00e9: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE 0x00ea: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x00eb: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00ec: 0x00cf, # LATIN CAPITAL LETTER I WITH DIAERESIS 0x00ed: 0x00cc, # LATIN CAPITAL LETTER I WITH GRAVE 0x00ee: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00ef: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00f0: None, # UNDEFINED 0x00f1: 0x00d2, # LATIN CAPITAL LETTER O WITH GRAVE 0x00f2: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00f3: 0x00db, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX 0x00f4: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE 0x00f5: 0x0131, # LATIN SMALL LETTER DOTLESS I 0x00f6: 0x02c6, # MODIFIER LETTER CIRCUMFLEX ACCENT 0x00f7: 0x02dc, # SMALL TILDE 0x00f8: 0x00af, # MACRON 0x00f9: 0x02d8, # BREVE 0x00fa: 0x02d9, # DOT ABOVE 0x00fb: 0x02da, # RING ABOVE 0x00fc: 0x00b8, # CEDILLA 0x00fd: 0x02dd, # DOUBLE ACUTE ACCENT 0x00fe: 0x02db, # OGONEK 0x00ff: 0x02c7, # CARON }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from '8859-15.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a4: 0x20ac, # EURO SIGN 0x00a6: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00a8: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00b4: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00b8: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00bc: 0x0152, # LATIN CAPITAL LIGATURE OE 0x00bd: 0x0153, # LATIN SMALL LIGATURE OE 0x00be: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec for TIS-620. According to ftp://ftp.unicode.org/Public/MAPPINGS/ISO8859/8859-11.TXT the TIS-620 is the identical to ISO_8859-11 with the 0xA0 (no-break space) mapping removed. """#" import codecs from encodings.iso8859_11 import decoding_map ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = decoding_map.copy() decoding_map.update({ 0x00a0: None, }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# # gbk.py: Python Unicode Codec for GBK # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: gbk.py,v 1.8 2004/06/28 18:16:03 perky Exp $ # import _codecs_cn, codecs codec = _codecs_cn.getcodec('gbk') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
# # shift_jis.py: Python Unicode Codec for SHIFT_JIS # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: shift_jis.py,v 1.8 2004/06/28 18:16:03 perky Exp $ # import _codecs_jp, codecs codec = _codecs_jp.getcodec('shift_jis') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP1026.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0004: 0x009c, # CONTROL 0x0005: 0x0009, # HORIZONTAL TABULATION 0x0006: 0x0086, # CONTROL 0x0007: 0x007f, # DELETE 0x0008: 0x0097, # CONTROL 0x0009: 0x008d, # CONTROL 0x000a: 0x008e, # CONTROL 0x0014: 0x009d, # CONTROL 0x0015: 0x0085, # CONTROL 0x0016: 0x0008, # BACKSPACE 0x0017: 0x0087, # CONTROL 0x001a: 0x0092, # CONTROL 0x001b: 0x008f, # CONTROL 0x0020: 0x0080, # CONTROL 0x0021: 0x0081, # CONTROL 0x0022: 0x0082, # CONTROL 0x0023: 0x0083, # CONTROL 0x0024: 0x0084, # CONTROL 0x0025: 0x000a, # LINE FEED 0x0026: 0x0017, # END OF TRANSMISSION BLOCK 0x0027: 0x001b, # ESCAPE 0x0028: 0x0088, # CONTROL 0x0029: 0x0089, # CONTROL 0x002a: 0x008a, # CONTROL 0x002b: 0x008b, # CONTROL 0x002c: 0x008c, # CONTROL 0x002d: 0x0005, # ENQUIRY 0x002e: 0x0006, # ACKNOWLEDGE 0x002f: 0x0007, # BELL 0x0030: 0x0090, # CONTROL 0x0031: 0x0091, # CONTROL 0x0032: 0x0016, # SYNCHRONOUS IDLE 0x0033: 0x0093, # CONTROL 0x0034: 0x0094, # CONTROL 0x0035: 0x0095, # CONTROL 0x0036: 0x0096, # CONTROL 0x0037: 0x0004, # END OF TRANSMISSION 0x0038: 0x0098, # CONTROL 0x0039: 0x0099, # CONTROL 0x003a: 0x009a, # CONTROL 0x003b: 0x009b, # CONTROL 0x003c: 0x0014, # DEVICE CONTROL FOUR 0x003d: 0x0015, # NEGATIVE ACKNOWLEDGE 0x003e: 0x009e, # CONTROL 0x003f: 0x001a, # SUBSTITUTE 0x0040: 0x0020, # SPACE 0x0041: 0x00a0, # NO-BREAK SPACE 0x0042: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0043: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0044: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0045: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x0046: 0x00e3, # LATIN SMALL LETTER A WITH TILDE 0x0047: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE 0x0048: 0x007b, # LEFT CURLY BRACKET 0x0049: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x004a: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x004b: 0x002e, # FULL STOP 0x004c: 0x003c, # LESS-THAN SIGN 0x004d: 0x0028, # LEFT PARENTHESIS 0x004e: 0x002b, # PLUS SIGN 0x004f: 0x0021, # EXCLAMATION MARK 0x0050: 0x0026, # AMPERSAND 0x0051: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0052: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0053: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x0054: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x0055: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x0056: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x0057: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x0058: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE 0x0059: 0x00df, # LATIN SMALL LETTER SHARP S (GERMAN) 0x005a: 0x011e, # LATIN CAPITAL LETTER G WITH BREVE 0x005b: 0x0130, # LATIN CAPITAL LETTER I WITH DOT ABOVE 0x005c: 0x002a, # ASTERISK 0x005d: 0x0029, # RIGHT PARENTHESIS 0x005e: 0x003b, # SEMICOLON 0x005f: 0x005e, # CIRCUMFLEX ACCENT 0x0060: 0x002d, # HYPHEN-MINUS 0x0061: 0x002f, # SOLIDUS 0x0062: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x0063: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x0064: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE 0x0065: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x0066: 0x00c3, # LATIN CAPITAL LETTER A WITH TILDE 0x0067: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x0068: 0x005b, # LEFT SQUARE BRACKET 0x0069: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x006a: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA 0x006b: 0x002c, # COMMA 0x006c: 0x0025, # PERCENT SIGN 0x006d: 0x005f, # LOW LINE 0x006e: 0x003e, # GREATER-THAN SIGN 0x006f: 0x003f, # QUESTION MARK 0x0070: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x0071: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0072: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x0073: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x0074: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE 0x0075: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x0076: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x0077: 0x00cf, # LATIN CAPITAL LETTER I WITH DIAERESIS 0x0078: 0x00cc, # LATIN CAPITAL LETTER I WITH GRAVE 0x0079: 0x0131, # LATIN SMALL LETTER DOTLESS I 0x007a: 0x003a, # COLON 0x007b: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x007c: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x007d: 0x0027, # APOSTROPHE 0x007e: 0x003d, # EQUALS SIGN 0x007f: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x0080: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x0081: 0x0061, # LATIN SMALL LETTER A 0x0082: 0x0062, # LATIN SMALL LETTER B 0x0083: 0x0063, # LATIN SMALL LETTER C 0x0084: 0x0064, # LATIN SMALL LETTER D 0x0085: 0x0065, # LATIN SMALL LETTER E 0x0086: 0x0066, # LATIN SMALL LETTER F 0x0087: 0x0067, # LATIN SMALL LETTER G 0x0088: 0x0068, # LATIN SMALL LETTER H 0x0089: 0x0069, # LATIN SMALL LETTER I 0x008a: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x008b: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x008c: 0x007d, # RIGHT CURLY BRACKET 0x008d: 0x0060, # GRAVE ACCENT 0x008e: 0x00a6, # BROKEN BAR 0x008f: 0x00b1, # PLUS-MINUS SIGN 0x0090: 0x00b0, # DEGREE SIGN 0x0091: 0x006a, # LATIN SMALL LETTER J 0x0092: 0x006b, # LATIN SMALL LETTER K 0x0093: 0x006c, # LATIN SMALL LETTER L 0x0094: 0x006d, # LATIN SMALL LETTER M 0x0095: 0x006e, # LATIN SMALL LETTER N 0x0096: 0x006f, # LATIN SMALL LETTER O 0x0097: 0x0070, # LATIN SMALL LETTER P 0x0098: 0x0071, # LATIN SMALL LETTER Q 0x0099: 0x0072, # LATIN SMALL LETTER R 0x009a: 0x00aa, # FEMININE ORDINAL INDICATOR 0x009b: 0x00ba, # MASCULINE ORDINAL INDICATOR 0x009c: 0x00e6, # LATIN SMALL LIGATURE AE 0x009d: 0x00b8, # CEDILLA 0x009e: 0x00c6, # LATIN CAPITAL LIGATURE AE 0x009f: 0x00a4, # CURRENCY SIGN 0x00a0: 0x00b5, # MICRO SIGN 0x00a1: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x00a2: 0x0073, # LATIN SMALL LETTER S 0x00a3: 0x0074, # LATIN SMALL LETTER T 0x00a4: 0x0075, # LATIN SMALL LETTER U 0x00a5: 0x0076, # LATIN SMALL LETTER V 0x00a6: 0x0077, # LATIN SMALL LETTER W 0x00a7: 0x0078, # LATIN SMALL LETTER X 0x00a8: 0x0079, # LATIN SMALL LETTER Y 0x00a9: 0x007a, # LATIN SMALL LETTER Z 0x00aa: 0x00a1, # INVERTED EXCLAMATION MARK 0x00ab: 0x00bf, # INVERTED QUESTION MARK 0x00ac: 0x005d, # RIGHT SQUARE BRACKET 0x00ad: 0x0024, # DOLLAR SIGN 0x00ae: 0x0040, # COMMERCIAL AT 0x00af: 0x00ae, # REGISTERED SIGN 0x00b0: 0x00a2, # CENT SIGN 0x00b1: 0x00a3, # POUND SIGN 0x00b2: 0x00a5, # YEN SIGN 0x00b3: 0x00b7, # MIDDLE DOT 0x00b4: 0x00a9, # COPYRIGHT SIGN 0x00b5: 0x00a7, # SECTION SIGN 0x00b7: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00b8: 0x00bd, # VULGAR FRACTION ONE HALF 0x00b9: 0x00be, # VULGAR FRACTION THREE QUARTERS 0x00ba: 0x00ac, # NOT SIGN 0x00bb: 0x007c, # VERTICAL LINE 0x00bc: 0x00af, # MACRON 0x00bd: 0x00a8, # DIAERESIS 0x00be: 0x00b4, # ACUTE ACCENT 0x00bf: 0x00d7, # MULTIPLICATION SIGN 0x00c0: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x00c1: 0x0041, # LATIN CAPITAL LETTER A 0x00c2: 0x0042, # LATIN CAPITAL LETTER B 0x00c3: 0x0043, # LATIN CAPITAL LETTER C 0x00c4: 0x0044, # LATIN CAPITAL LETTER D 0x00c5: 0x0045, # LATIN CAPITAL LETTER E 0x00c6: 0x0046, # LATIN CAPITAL LETTER F 0x00c7: 0x0047, # LATIN CAPITAL LETTER G 0x00c8: 0x0048, # LATIN CAPITAL LETTER H 0x00c9: 0x0049, # LATIN CAPITAL LETTER I 0x00ca: 0x00ad, # SOFT HYPHEN 0x00cb: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x00cc: 0x007e, # TILDE 0x00cd: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE 0x00ce: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00cf: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x00d0: 0x011f, # LATIN SMALL LETTER G WITH BREVE 0x00d1: 0x004a, # LATIN CAPITAL LETTER J 0x00d2: 0x004b, # LATIN CAPITAL LETTER K 0x00d3: 0x004c, # LATIN CAPITAL LETTER L 0x00d4: 0x004d, # LATIN CAPITAL LETTER M 0x00d5: 0x004e, # LATIN CAPITAL LETTER N 0x00d6: 0x004f, # LATIN CAPITAL LETTER O 0x00d7: 0x0050, # LATIN CAPITAL LETTER P 0x00d8: 0x0051, # LATIN CAPITAL LETTER Q 0x00d9: 0x0052, # LATIN CAPITAL LETTER R 0x00da: 0x00b9, # SUPERSCRIPT ONE 0x00db: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x00dc: 0x005c, # REVERSE SOLIDUS 0x00dd: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x00de: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00df: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS 0x00e0: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x00e1: 0x00f7, # DIVISION SIGN 0x00e2: 0x0053, # LATIN CAPITAL LETTER S 0x00e3: 0x0054, # LATIN CAPITAL LETTER T 0x00e4: 0x0055, # LATIN CAPITAL LETTER U 0x00e5: 0x0056, # LATIN CAPITAL LETTER V 0x00e6: 0x0057, # LATIN CAPITAL LETTER W 0x00e7: 0x0058, # LATIN CAPITAL LETTER X 0x00e8: 0x0059, # LATIN CAPITAL LETTER Y 0x00e9: 0x005a, # LATIN CAPITAL LETTER Z 0x00ea: 0x00b2, # SUPERSCRIPT TWO 0x00eb: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00ec: 0x0023, # NUMBER SIGN 0x00ed: 0x00d2, # LATIN CAPITAL LETTER O WITH GRAVE 0x00ee: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00ef: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x00f0: 0x0030, # DIGIT ZERO 0x00f1: 0x0031, # DIGIT ONE 0x00f2: 0x0032, # DIGIT TWO 0x00f3: 0x0033, # DIGIT THREE 0x00f4: 0x0034, # DIGIT FOUR 0x00f5: 0x0035, # DIGIT FIVE 0x00f6: 0x0036, # DIGIT SIX 0x00f7: 0x0037, # DIGIT SEVEN 0x00f8: 0x0038, # DIGIT EIGHT 0x00f9: 0x0039, # DIGIT NINE 0x00fa: 0x00b3, # SUPERSCRIPT THREE 0x00fb: 0x00db, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX 0x00fc: 0x0022, # QUOTATION MARK 0x00fd: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE 0x00fe: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00ff: 0x009f, # CONTROL }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# # cp932.py: Python Unicode Codec for CP932 # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: cp932.py,v 1.8 2004/06/28 18:16:03 perky Exp $ # import _codecs_jp, codecs codec = _codecs_jp.getcodec('cp932') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP874.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x20ac, # EURO SIGN 0x0081: None, # UNDEFINED 0x0082: None, # UNDEFINED 0x0083: None, # UNDEFINED 0x0084: None, # UNDEFINED 0x0085: 0x2026, # HORIZONTAL ELLIPSIS 0x0086: None, # UNDEFINED 0x0087: None, # UNDEFINED 0x0088: None, # UNDEFINED 0x0089: None, # UNDEFINED 0x008a: None, # UNDEFINED 0x008b: None, # UNDEFINED 0x008c: None, # UNDEFINED 0x008d: None, # UNDEFINED 0x008e: None, # UNDEFINED 0x008f: None, # UNDEFINED 0x0090: None, # UNDEFINED 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x0095: 0x2022, # BULLET 0x0096: 0x2013, # EN DASH 0x0097: 0x2014, # EM DASH 0x0098: None, # UNDEFINED 0x0099: None, # UNDEFINED 0x009a: None, # UNDEFINED 0x009b: None, # UNDEFINED 0x009c: None, # UNDEFINED 0x009d: None, # UNDEFINED 0x009e: None, # UNDEFINED 0x009f: None, # UNDEFINED 0x00a1: 0x0e01, # THAI CHARACTER KO KAI 0x00a2: 0x0e02, # THAI CHARACTER KHO KHAI 0x00a3: 0x0e03, # THAI CHARACTER KHO KHUAT 0x00a4: 0x0e04, # THAI CHARACTER KHO KHWAI 0x00a5: 0x0e05, # THAI CHARACTER KHO KHON 0x00a6: 0x0e06, # THAI CHARACTER KHO RAKHANG 0x00a7: 0x0e07, # THAI CHARACTER NGO NGU 0x00a8: 0x0e08, # THAI CHARACTER CHO CHAN 0x00a9: 0x0e09, # THAI CHARACTER CHO CHING 0x00aa: 0x0e0a, # THAI CHARACTER CHO CHANG 0x00ab: 0x0e0b, # THAI CHARACTER SO SO 0x00ac: 0x0e0c, # THAI CHARACTER CHO CHOE 0x00ad: 0x0e0d, # THAI CHARACTER YO YING 0x00ae: 0x0e0e, # THAI CHARACTER DO CHADA 0x00af: 0x0e0f, # THAI CHARACTER TO PATAK 0x00b0: 0x0e10, # THAI CHARACTER THO THAN 0x00b1: 0x0e11, # THAI CHARACTER THO NANGMONTHO 0x00b2: 0x0e12, # THAI CHARACTER THO PHUTHAO 0x00b3: 0x0e13, # THAI CHARACTER NO NEN 0x00b4: 0x0e14, # THAI CHARACTER DO DEK 0x00b5: 0x0e15, # THAI CHARACTER TO TAO 0x00b6: 0x0e16, # THAI CHARACTER THO THUNG 0x00b7: 0x0e17, # THAI CHARACTER THO THAHAN 0x00b8: 0x0e18, # THAI CHARACTER THO THONG 0x00b9: 0x0e19, # THAI CHARACTER NO NU 0x00ba: 0x0e1a, # THAI CHARACTER BO BAIMAI 0x00bb: 0x0e1b, # THAI CHARACTER PO PLA 0x00bc: 0x0e1c, # THAI CHARACTER PHO PHUNG 0x00bd: 0x0e1d, # THAI CHARACTER FO FA 0x00be: 0x0e1e, # THAI CHARACTER PHO PHAN 0x00bf: 0x0e1f, # THAI CHARACTER FO FAN 0x00c0: 0x0e20, # THAI CHARACTER PHO SAMPHAO 0x00c1: 0x0e21, # THAI CHARACTER MO MA 0x00c2: 0x0e22, # THAI CHARACTER YO YAK 0x00c3: 0x0e23, # THAI CHARACTER RO RUA 0x00c4: 0x0e24, # THAI CHARACTER RU 0x00c5: 0x0e25, # THAI CHARACTER LO LING 0x00c6: 0x0e26, # THAI CHARACTER LU 0x00c7: 0x0e27, # THAI CHARACTER WO WAEN 0x00c8: 0x0e28, # THAI CHARACTER SO SALA 0x00c9: 0x0e29, # THAI CHARACTER SO RUSI 0x00ca: 0x0e2a, # THAI CHARACTER SO SUA 0x00cb: 0x0e2b, # THAI CHARACTER HO HIP 0x00cc: 0x0e2c, # THAI CHARACTER LO CHULA 0x00cd: 0x0e2d, # THAI CHARACTER O ANG 0x00ce: 0x0e2e, # THAI CHARACTER HO NOKHUK 0x00cf: 0x0e2f, # THAI CHARACTER PAIYANNOI 0x00d0: 0x0e30, # THAI CHARACTER SARA A 0x00d1: 0x0e31, # THAI CHARACTER MAI HAN-AKAT 0x00d2: 0x0e32, # THAI CHARACTER SARA AA 0x00d3: 0x0e33, # THAI CHARACTER SARA AM 0x00d4: 0x0e34, # THAI CHARACTER SARA I 0x00d5: 0x0e35, # THAI CHARACTER SARA II 0x00d6: 0x0e36, # THAI CHARACTER SARA UE 0x00d7: 0x0e37, # THAI CHARACTER SARA UEE 0x00d8: 0x0e38, # THAI CHARACTER SARA U 0x00d9: 0x0e39, # THAI CHARACTER SARA UU 0x00da: 0x0e3a, # THAI CHARACTER PHINTHU 0x00db: None, # UNDEFINED 0x00dc: None, # UNDEFINED 0x00dd: None, # UNDEFINED 0x00de: None, # UNDEFINED 0x00df: 0x0e3f, # THAI CURRENCY SYMBOL BAHT 0x00e0: 0x0e40, # THAI CHARACTER SARA E 0x00e1: 0x0e41, # THAI CHARACTER SARA AE 0x00e2: 0x0e42, # THAI CHARACTER SARA O 0x00e3: 0x0e43, # THAI CHARACTER SARA AI MAIMUAN 0x00e4: 0x0e44, # THAI CHARACTER SARA AI MAIMALAI 0x00e5: 0x0e45, # THAI CHARACTER LAKKHANGYAO 0x00e6: 0x0e46, # THAI CHARACTER MAIYAMOK 0x00e7: 0x0e47, # THAI CHARACTER MAITAIKHU 0x00e8: 0x0e48, # THAI CHARACTER MAI EK 0x00e9: 0x0e49, # THAI CHARACTER MAI THO 0x00ea: 0x0e4a, # THAI CHARACTER MAI TRI 0x00eb: 0x0e4b, # THAI CHARACTER MAI CHATTAWA 0x00ec: 0x0e4c, # THAI CHARACTER THANTHAKHAT 0x00ed: 0x0e4d, # THAI CHARACTER NIKHAHIT 0x00ee: 0x0e4e, # THAI CHARACTER YAMAKKAN 0x00ef: 0x0e4f, # THAI CHARACTER FONGMAN 0x00f0: 0x0e50, # THAI DIGIT ZERO 0x00f1: 0x0e51, # THAI DIGIT ONE 0x00f2: 0x0e52, # THAI DIGIT TWO 0x00f3: 0x0e53, # THAI DIGIT THREE 0x00f4: 0x0e54, # THAI DIGIT FOUR 0x00f5: 0x0e55, # THAI DIGIT FIVE 0x00f6: 0x0e56, # THAI DIGIT SIX 0x00f7: 0x0e57, # THAI DIGIT SEVEN 0x00f8: 0x0e58, # THAI DIGIT EIGHT 0x00f9: 0x0e59, # THAI DIGIT NINE 0x00fa: 0x0e5a, # THAI CHARACTER ANGKHANKHU 0x00fb: 0x0e5b, # THAI CHARACTER KHOMUT 0x00fc: None, # UNDEFINED 0x00fd: None, # UNDEFINED 0x00fe: None, # UNDEFINED 0x00ff: None, # UNDEFINED }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
#!/usr/bin/env python """ Python Character Mapping Codec for ROT13. See http://ucsub.colorado.edu/~kominek/rot13/ for details. Written by Marc-Andre Lemburg (mal@lemburg.com). """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0041: 0x004e, 0x0042: 0x004f, 0x0043: 0x0050, 0x0044: 0x0051, 0x0045: 0x0052, 0x0046: 0x0053, 0x0047: 0x0054, 0x0048: 0x0055, 0x0049: 0x0056, 0x004a: 0x0057, 0x004b: 0x0058, 0x004c: 0x0059, 0x004d: 0x005a, 0x004e: 0x0041, 0x004f: 0x0042, 0x0050: 0x0043, 0x0051: 0x0044, 0x0052: 0x0045, 0x0053: 0x0046, 0x0054: 0x0047, 0x0055: 0x0048, 0x0056: 0x0049, 0x0057: 0x004a, 0x0058: 0x004b, 0x0059: 0x004c, 0x005a: 0x004d, 0x0061: 0x006e, 0x0062: 0x006f, 0x0063: 0x0070, 0x0064: 0x0071, 0x0065: 0x0072, 0x0066: 0x0073, 0x0067: 0x0074, 0x0068: 0x0075, 0x0069: 0x0076, 0x006a: 0x0077, 0x006b: 0x0078, 0x006c: 0x0079, 0x006d: 0x007a, 0x006e: 0x0061, 0x006f: 0x0062, 0x0070: 0x0063, 0x0071: 0x0064, 0x0072: 0x0065, 0x0073: 0x0066, 0x0074: 0x0067, 0x0075: 0x0068, 0x0076: 0x0069, 0x0077: 0x006a, 0x0078: 0x006b, 0x0079: 0x006c, 0x007a: 0x006d, }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map) ### Filter API def rot13(infile, outfile): outfile.write(infile.read().encode('rot-13')) if __name__ == '__main__': import sys rot13(sys.stdin, sys.stdout)
Python
""" Python Character Mapping Codec for KOI8U. This character scheme is compliant to RFC2319 Written by Marc-Andre Lemburg (mal@lemburg.com). Modified by Maxim Dzumanenko <mvd@mylinux.com.ua>. (c) Copyright 2002, Python Software Foundation. """#" import codecs, koi8_r ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = koi8_r.decoding_map.copy() decoding_map.update({ 0x00a4: 0x0454, # CYRILLIC SMALL LETTER UKRAINIAN IE 0x00a6: 0x0456, # CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I 0x00a7: 0x0457, # CYRILLIC SMALL LETTER YI (UKRAINIAN) 0x00ad: 0x0491, # CYRILLIC SMALL LETTER UKRAINIAN GHE WITH UPTURN 0x00b4: 0x0404, # CYRILLIC CAPITAL LETTER UKRAINIAN IE 0x00b6: 0x0406, # CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I 0x00b7: 0x0407, # CYRILLIC CAPITAL LETTER YI (UKRAINIAN) 0x00bd: 0x0490, # CYRILLIC CAPITAL LETTER UKRAINIAN GHE WITH UPTURN }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP437.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x008b: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x008d: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE 0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x00e6, # LATIN SMALL LIGATURE AE 0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x0095: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE 0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x0098: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS 0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x00a2, # CENT SIGN 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x00a5, # YEN SIGN 0x009e: 0x20a7, # PESETA SIGN 0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x00a5: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x00a6: 0x00aa, # FEMININE ORDINAL INDICATOR 0x00a7: 0x00ba, # MASCULINE ORDINAL INDICATOR 0x00a8: 0x00bf, # INVERTED QUESTION MARK 0x00a9: 0x2310, # REVERSED NOT SIGN 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x258c, # LEFT HALF BLOCK 0x00de: 0x2590, # RIGHT HALF BLOCK 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S 0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA 0x00e3: 0x03c0, # GREEK SMALL LETTER PI 0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA 0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA 0x00e6: 0x00b5, # MICRO SIGN 0x00e7: 0x03c4, # GREEK SMALL LETTER TAU 0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI 0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA 0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA 0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA 0x00ec: 0x221e, # INFINITY 0x00ed: 0x03c6, # GREEK SMALL LETTER PHI 0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON 0x00ef: 0x2229, # INTERSECTION 0x00f0: 0x2261, # IDENTICAL TO 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO 0x00f3: 0x2264, # LESS-THAN OR EQUAL TO 0x00f4: 0x2320, # TOP HALF INTEGRAL 0x00f5: 0x2321, # BOTTOM HALF INTEGRAL 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x2248, # ALMOST EQUAL TO 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x2219, # BULLET OPERATOR 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x221a, # SQUARE ROOT 0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N 0x00fd: 0x00b2, # SUPERSCRIPT TWO 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from '8859-2.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x00a2: 0x02d8, # BREVE 0x00a3: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE 0x00a5: 0x013d, # LATIN CAPITAL LETTER L WITH CARON 0x00a6: 0x015a, # LATIN CAPITAL LETTER S WITH ACUTE 0x00a9: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00aa: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x00ab: 0x0164, # LATIN CAPITAL LETTER T WITH CARON 0x00ac: 0x0179, # LATIN CAPITAL LETTER Z WITH ACUTE 0x00ae: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00af: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x00b1: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x00b2: 0x02db, # OGONEK 0x00b3: 0x0142, # LATIN SMALL LETTER L WITH STROKE 0x00b5: 0x013e, # LATIN SMALL LETTER L WITH CARON 0x00b6: 0x015b, # LATIN SMALL LETTER S WITH ACUTE 0x00b7: 0x02c7, # CARON 0x00b9: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00ba: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA 0x00bb: 0x0165, # LATIN SMALL LETTER T WITH CARON 0x00bc: 0x017a, # LATIN SMALL LETTER Z WITH ACUTE 0x00bd: 0x02dd, # DOUBLE ACUTE ACCENT 0x00be: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00bf: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x00c0: 0x0154, # LATIN CAPITAL LETTER R WITH ACUTE 0x00c3: 0x0102, # LATIN CAPITAL LETTER A WITH BREVE 0x00c5: 0x0139, # LATIN CAPITAL LETTER L WITH ACUTE 0x00c6: 0x0106, # LATIN CAPITAL LETTER C WITH ACUTE 0x00c8: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x00ca: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00cc: 0x011a, # LATIN CAPITAL LETTER E WITH CARON 0x00cf: 0x010e, # LATIN CAPITAL LETTER D WITH CARON 0x00d0: 0x0110, # LATIN CAPITAL LETTER D WITH STROKE 0x00d1: 0x0143, # LATIN CAPITAL LETTER N WITH ACUTE 0x00d2: 0x0147, # LATIN CAPITAL LETTER N WITH CARON 0x00d5: 0x0150, # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE 0x00d8: 0x0158, # LATIN CAPITAL LETTER R WITH CARON 0x00d9: 0x016e, # LATIN CAPITAL LETTER U WITH RING ABOVE 0x00db: 0x0170, # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE 0x00de: 0x0162, # LATIN CAPITAL LETTER T WITH CEDILLA 0x00e0: 0x0155, # LATIN SMALL LETTER R WITH ACUTE 0x00e3: 0x0103, # LATIN SMALL LETTER A WITH BREVE 0x00e5: 0x013a, # LATIN SMALL LETTER L WITH ACUTE 0x00e6: 0x0107, # LATIN SMALL LETTER C WITH ACUTE 0x00e8: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x00ea: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00ec: 0x011b, # LATIN SMALL LETTER E WITH CARON 0x00ef: 0x010f, # LATIN SMALL LETTER D WITH CARON 0x00f0: 0x0111, # LATIN SMALL LETTER D WITH STROKE 0x00f1: 0x0144, # LATIN SMALL LETTER N WITH ACUTE 0x00f2: 0x0148, # LATIN SMALL LETTER N WITH CARON 0x00f5: 0x0151, # LATIN SMALL LETTER O WITH DOUBLE ACUTE 0x00f8: 0x0159, # LATIN SMALL LETTER R WITH CARON 0x00f9: 0x016f, # LATIN SMALL LETTER U WITH RING ABOVE 0x00fb: 0x0171, # LATIN SMALL LETTER U WITH DOUBLE ACUTE 0x00fe: 0x0163, # LATIN SMALL LETTER T WITH CEDILLA 0x00ff: 0x02d9, # DOT ABOVE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# # cp949.py: Python Unicode Codec for CP949 # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: cp949.py,v 1.8 2004/06/28 18:16:03 perky Exp $ # import _codecs_kr, codecs codec = _codecs_kr.getcodec('cp949') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python Character Mapping Codec generated from '8859-5.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: 0x0401, # CYRILLIC CAPITAL LETTER IO 0x00a2: 0x0402, # CYRILLIC CAPITAL LETTER DJE 0x00a3: 0x0403, # CYRILLIC CAPITAL LETTER GJE 0x00a4: 0x0404, # CYRILLIC CAPITAL LETTER UKRAINIAN IE 0x00a5: 0x0405, # CYRILLIC CAPITAL LETTER DZE 0x00a6: 0x0406, # CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I 0x00a7: 0x0407, # CYRILLIC CAPITAL LETTER YI 0x00a8: 0x0408, # CYRILLIC CAPITAL LETTER JE 0x00a9: 0x0409, # CYRILLIC CAPITAL LETTER LJE 0x00aa: 0x040a, # CYRILLIC CAPITAL LETTER NJE 0x00ab: 0x040b, # CYRILLIC CAPITAL LETTER TSHE 0x00ac: 0x040c, # CYRILLIC CAPITAL LETTER KJE 0x00ae: 0x040e, # CYRILLIC CAPITAL LETTER SHORT U 0x00af: 0x040f, # CYRILLIC CAPITAL LETTER DZHE 0x00b0: 0x0410, # CYRILLIC CAPITAL LETTER A 0x00b1: 0x0411, # CYRILLIC CAPITAL LETTER BE 0x00b2: 0x0412, # CYRILLIC CAPITAL LETTER VE 0x00b3: 0x0413, # CYRILLIC CAPITAL LETTER GHE 0x00b4: 0x0414, # CYRILLIC CAPITAL LETTER DE 0x00b5: 0x0415, # CYRILLIC CAPITAL LETTER IE 0x00b6: 0x0416, # CYRILLIC CAPITAL LETTER ZHE 0x00b7: 0x0417, # CYRILLIC CAPITAL LETTER ZE 0x00b8: 0x0418, # CYRILLIC CAPITAL LETTER I 0x00b9: 0x0419, # CYRILLIC CAPITAL LETTER SHORT I 0x00ba: 0x041a, # CYRILLIC CAPITAL LETTER KA 0x00bb: 0x041b, # CYRILLIC CAPITAL LETTER EL 0x00bc: 0x041c, # CYRILLIC CAPITAL LETTER EM 0x00bd: 0x041d, # CYRILLIC CAPITAL LETTER EN 0x00be: 0x041e, # CYRILLIC CAPITAL LETTER O 0x00bf: 0x041f, # CYRILLIC CAPITAL LETTER PE 0x00c0: 0x0420, # CYRILLIC CAPITAL LETTER ER 0x00c1: 0x0421, # CYRILLIC CAPITAL LETTER ES 0x00c2: 0x0422, # CYRILLIC CAPITAL LETTER TE 0x00c3: 0x0423, # CYRILLIC CAPITAL LETTER U 0x00c4: 0x0424, # CYRILLIC CAPITAL LETTER EF 0x00c5: 0x0425, # CYRILLIC CAPITAL LETTER HA 0x00c6: 0x0426, # CYRILLIC CAPITAL LETTER TSE 0x00c7: 0x0427, # CYRILLIC CAPITAL LETTER CHE 0x00c8: 0x0428, # CYRILLIC CAPITAL LETTER SHA 0x00c9: 0x0429, # CYRILLIC CAPITAL LETTER SHCHA 0x00ca: 0x042a, # CYRILLIC CAPITAL LETTER HARD SIGN 0x00cb: 0x042b, # CYRILLIC CAPITAL LETTER YERU 0x00cc: 0x042c, # CYRILLIC CAPITAL LETTER SOFT SIGN 0x00cd: 0x042d, # CYRILLIC CAPITAL LETTER E 0x00ce: 0x042e, # CYRILLIC CAPITAL LETTER YU 0x00cf: 0x042f, # CYRILLIC CAPITAL LETTER YA 0x00d0: 0x0430, # CYRILLIC SMALL LETTER A 0x00d1: 0x0431, # CYRILLIC SMALL LETTER BE 0x00d2: 0x0432, # CYRILLIC SMALL LETTER VE 0x00d3: 0x0433, # CYRILLIC SMALL LETTER GHE 0x00d4: 0x0434, # CYRILLIC SMALL LETTER DE 0x00d5: 0x0435, # CYRILLIC SMALL LETTER IE 0x00d6: 0x0436, # CYRILLIC SMALL LETTER ZHE 0x00d7: 0x0437, # CYRILLIC SMALL LETTER ZE 0x00d8: 0x0438, # CYRILLIC SMALL LETTER I 0x00d9: 0x0439, # CYRILLIC SMALL LETTER SHORT I 0x00da: 0x043a, # CYRILLIC SMALL LETTER KA 0x00db: 0x043b, # CYRILLIC SMALL LETTER EL 0x00dc: 0x043c, # CYRILLIC SMALL LETTER EM 0x00dd: 0x043d, # CYRILLIC SMALL LETTER EN 0x00de: 0x043e, # CYRILLIC SMALL LETTER O 0x00df: 0x043f, # CYRILLIC SMALL LETTER PE 0x00e0: 0x0440, # CYRILLIC SMALL LETTER ER 0x00e1: 0x0441, # CYRILLIC SMALL LETTER ES 0x00e2: 0x0442, # CYRILLIC SMALL LETTER TE 0x00e3: 0x0443, # CYRILLIC SMALL LETTER U 0x00e4: 0x0444, # CYRILLIC SMALL LETTER EF 0x00e5: 0x0445, # CYRILLIC SMALL LETTER HA 0x00e6: 0x0446, # CYRILLIC SMALL LETTER TSE 0x00e7: 0x0447, # CYRILLIC SMALL LETTER CHE 0x00e8: 0x0448, # CYRILLIC SMALL LETTER SHA 0x00e9: 0x0449, # CYRILLIC SMALL LETTER SHCHA 0x00ea: 0x044a, # CYRILLIC SMALL LETTER HARD SIGN 0x00eb: 0x044b, # CYRILLIC SMALL LETTER YERU 0x00ec: 0x044c, # CYRILLIC SMALL LETTER SOFT SIGN 0x00ed: 0x044d, # CYRILLIC SMALL LETTER E 0x00ee: 0x044e, # CYRILLIC SMALL LETTER YU 0x00ef: 0x044f, # CYRILLIC SMALL LETTER YA 0x00f0: 0x2116, # NUMERO SIGN 0x00f1: 0x0451, # CYRILLIC SMALL LETTER IO 0x00f2: 0x0452, # CYRILLIC SMALL LETTER DJE 0x00f3: 0x0453, # CYRILLIC SMALL LETTER GJE 0x00f4: 0x0454, # CYRILLIC SMALL LETTER UKRAINIAN IE 0x00f5: 0x0455, # CYRILLIC SMALL LETTER DZE 0x00f6: 0x0456, # CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I 0x00f7: 0x0457, # CYRILLIC SMALL LETTER YI 0x00f8: 0x0458, # CYRILLIC SMALL LETTER JE 0x00f9: 0x0459, # CYRILLIC SMALL LETTER LJE 0x00fa: 0x045a, # CYRILLIC SMALL LETTER NJE 0x00fb: 0x045b, # CYRILLIC SMALL LETTER TSHE 0x00fc: 0x045c, # CYRILLIC SMALL LETTER KJE 0x00fd: 0x00a7, # SECTION SIGN 0x00fe: 0x045e, # CYRILLIC SMALL LETTER SHORT U 0x00ff: 0x045f, # CYRILLIC SMALL LETTER DZHE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# # iso2022_jp_2.py: Python Unicode Codec for ISO2022_JP_2 # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: iso2022_jp_2.py,v 1.2 2004/06/28 18:16:03 perky Exp $ # import _codecs_iso2022, codecs codec = _codecs_iso2022.getcodec('iso2022_jp_2') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python 'latin-1' Codec Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs class Codec(codecs.Codec): # Note: Binding these as C functions will result in the class not # converting them to methods. This is intended. encode = codecs.latin_1_encode decode = codecs.latin_1_decode class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass class StreamConverter(StreamWriter,StreamReader): encode = codecs.latin_1_decode decode = codecs.latin_1_encode ### encodings module API def getregentry(): return (Codec.encode,Codec.decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP1253.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x20ac, # EURO SIGN 0x0081: None, # UNDEFINED 0x0082: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x0083: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x0084: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x0085: 0x2026, # HORIZONTAL ELLIPSIS 0x0086: 0x2020, # DAGGER 0x0087: 0x2021, # DOUBLE DAGGER 0x0088: None, # UNDEFINED 0x0089: 0x2030, # PER MILLE SIGN 0x008a: None, # UNDEFINED 0x008b: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x008c: None, # UNDEFINED 0x008d: None, # UNDEFINED 0x008e: None, # UNDEFINED 0x008f: None, # UNDEFINED 0x0090: None, # UNDEFINED 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x0095: 0x2022, # BULLET 0x0096: 0x2013, # EN DASH 0x0097: 0x2014, # EM DASH 0x0098: None, # UNDEFINED 0x0099: 0x2122, # TRADE MARK SIGN 0x009a: None, # UNDEFINED 0x009b: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 0x009c: None, # UNDEFINED 0x009d: None, # UNDEFINED 0x009e: None, # UNDEFINED 0x009f: None, # UNDEFINED 0x00a1: 0x0385, # GREEK DIALYTIKA TONOS 0x00a2: 0x0386, # GREEK CAPITAL LETTER ALPHA WITH TONOS 0x00aa: None, # UNDEFINED 0x00af: 0x2015, # HORIZONTAL BAR 0x00b4: 0x0384, # GREEK TONOS 0x00b8: 0x0388, # GREEK CAPITAL LETTER EPSILON WITH TONOS 0x00b9: 0x0389, # GREEK CAPITAL LETTER ETA WITH TONOS 0x00ba: 0x038a, # GREEK CAPITAL LETTER IOTA WITH TONOS 0x00bc: 0x038c, # GREEK CAPITAL LETTER OMICRON WITH TONOS 0x00be: 0x038e, # GREEK CAPITAL LETTER UPSILON WITH TONOS 0x00bf: 0x038f, # GREEK CAPITAL LETTER OMEGA WITH TONOS 0x00c0: 0x0390, # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS 0x00c1: 0x0391, # GREEK CAPITAL LETTER ALPHA 0x00c2: 0x0392, # GREEK CAPITAL LETTER BETA 0x00c3: 0x0393, # GREEK CAPITAL LETTER GAMMA 0x00c4: 0x0394, # GREEK CAPITAL LETTER DELTA 0x00c5: 0x0395, # GREEK CAPITAL LETTER EPSILON 0x00c6: 0x0396, # GREEK CAPITAL LETTER ZETA 0x00c7: 0x0397, # GREEK CAPITAL LETTER ETA 0x00c8: 0x0398, # GREEK CAPITAL LETTER THETA 0x00c9: 0x0399, # GREEK CAPITAL LETTER IOTA 0x00ca: 0x039a, # GREEK CAPITAL LETTER KAPPA 0x00cb: 0x039b, # GREEK CAPITAL LETTER LAMDA 0x00cc: 0x039c, # GREEK CAPITAL LETTER MU 0x00cd: 0x039d, # GREEK CAPITAL LETTER NU 0x00ce: 0x039e, # GREEK CAPITAL LETTER XI 0x00cf: 0x039f, # GREEK CAPITAL LETTER OMICRON 0x00d0: 0x03a0, # GREEK CAPITAL LETTER PI 0x00d1: 0x03a1, # GREEK CAPITAL LETTER RHO 0x00d2: None, # UNDEFINED 0x00d3: 0x03a3, # GREEK CAPITAL LETTER SIGMA 0x00d4: 0x03a4, # GREEK CAPITAL LETTER TAU 0x00d5: 0x03a5, # GREEK CAPITAL LETTER UPSILON 0x00d6: 0x03a6, # GREEK CAPITAL LETTER PHI 0x00d7: 0x03a7, # GREEK CAPITAL LETTER CHI 0x00d8: 0x03a8, # GREEK CAPITAL LETTER PSI 0x00d9: 0x03a9, # GREEK CAPITAL LETTER OMEGA 0x00da: 0x03aa, # GREEK CAPITAL LETTER IOTA WITH DIALYTIKA 0x00db: 0x03ab, # GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA 0x00dc: 0x03ac, # GREEK SMALL LETTER ALPHA WITH TONOS 0x00dd: 0x03ad, # GREEK SMALL LETTER EPSILON WITH TONOS 0x00de: 0x03ae, # GREEK SMALL LETTER ETA WITH TONOS 0x00df: 0x03af, # GREEK SMALL LETTER IOTA WITH TONOS 0x00e0: 0x03b0, # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS 0x00e1: 0x03b1, # GREEK SMALL LETTER ALPHA 0x00e2: 0x03b2, # GREEK SMALL LETTER BETA 0x00e3: 0x03b3, # GREEK SMALL LETTER GAMMA 0x00e4: 0x03b4, # GREEK SMALL LETTER DELTA 0x00e5: 0x03b5, # GREEK SMALL LETTER EPSILON 0x00e6: 0x03b6, # GREEK SMALL LETTER ZETA 0x00e7: 0x03b7, # GREEK SMALL LETTER ETA 0x00e8: 0x03b8, # GREEK SMALL LETTER THETA 0x00e9: 0x03b9, # GREEK SMALL LETTER IOTA 0x00ea: 0x03ba, # GREEK SMALL LETTER KAPPA 0x00eb: 0x03bb, # GREEK SMALL LETTER LAMDA 0x00ec: 0x03bc, # GREEK SMALL LETTER MU 0x00ed: 0x03bd, # GREEK SMALL LETTER NU 0x00ee: 0x03be, # GREEK SMALL LETTER XI 0x00ef: 0x03bf, # GREEK SMALL LETTER OMICRON 0x00f0: 0x03c0, # GREEK SMALL LETTER PI 0x00f1: 0x03c1, # GREEK SMALL LETTER RHO 0x00f2: 0x03c2, # GREEK SMALL LETTER FINAL SIGMA 0x00f3: 0x03c3, # GREEK SMALL LETTER SIGMA 0x00f4: 0x03c4, # GREEK SMALL LETTER TAU 0x00f5: 0x03c5, # GREEK SMALL LETTER UPSILON 0x00f6: 0x03c6, # GREEK SMALL LETTER PHI 0x00f7: 0x03c7, # GREEK SMALL LETTER CHI 0x00f8: 0x03c8, # GREEK SMALL LETTER PSI 0x00f9: 0x03c9, # GREEK SMALL LETTER OMEGA 0x00fa: 0x03ca, # GREEK SMALL LETTER IOTA WITH DIALYTIKA 0x00fb: 0x03cb, # GREEK SMALL LETTER UPSILON WITH DIALYTIKA 0x00fc: 0x03cc, # GREEK SMALL LETTER OMICRON WITH TONOS 0x00fd: 0x03cd, # GREEK SMALL LETTER UPSILON WITH TONOS 0x00fe: 0x03ce, # GREEK SMALL LETTER OMEGA WITH TONOS 0x00ff: None, # UNDEFINED }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# # shift_jisx0213.py: Python Unicode Codec for SHIFT_JISX0213 # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: shift_jisx0213.py,v 1.8 2004/06/28 18:16:03 perky Exp $ # import _codecs_jp, codecs codec = _codecs_jp.getcodec('shift_jisx0213') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python Character Mapping Codec for PalmOS 3.5. Written by Sjoerd Mullender (sjoerd@acm.org); based on iso8859_15.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) # The PalmOS character set is mostly iso-8859-1 with some differences. decoding_map.update({ 0x0080: 0x20ac, # EURO SIGN 0x0082: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x0083: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x0084: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x0085: 0x2026, # HORIZONTAL ELLIPSIS 0x0086: 0x2020, # DAGGER 0x0087: 0x2021, # DOUBLE DAGGER 0x0088: 0x02c6, # MODIFIER LETTER CIRCUMFLEX ACCENT 0x0089: 0x2030, # PER MILLE SIGN 0x008a: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x008b: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x008c: 0x0152, # LATIN CAPITAL LIGATURE OE 0x008d: 0x2666, # BLACK DIAMOND SUIT 0x008e: 0x2663, # BLACK CLUB SUIT 0x008f: 0x2665, # BLACK HEART SUIT 0x0090: 0x2660, # BLACK SPADE SUIT 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x0095: 0x2022, # BULLET 0x0096: 0x2013, # EN DASH 0x0097: 0x2014, # EM DASH 0x0098: 0x02dc, # SMALL TILDE 0x0099: 0x2122, # TRADE MARK SIGN 0x009a: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x009c: 0x0153, # LATIN SMALL LIGATURE OE 0x009f: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP1258.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x20ac, # EURO SIGN 0x0081: None, # UNDEFINED 0x0082: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x0083: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x0084: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x0085: 0x2026, # HORIZONTAL ELLIPSIS 0x0086: 0x2020, # DAGGER 0x0087: 0x2021, # DOUBLE DAGGER 0x0088: 0x02c6, # MODIFIER LETTER CIRCUMFLEX ACCENT 0x0089: 0x2030, # PER MILLE SIGN 0x008a: None, # UNDEFINED 0x008b: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x008c: 0x0152, # LATIN CAPITAL LIGATURE OE 0x008d: None, # UNDEFINED 0x008e: None, # UNDEFINED 0x008f: None, # UNDEFINED 0x0090: None, # UNDEFINED 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x0095: 0x2022, # BULLET 0x0096: 0x2013, # EN DASH 0x0097: 0x2014, # EM DASH 0x0098: 0x02dc, # SMALL TILDE 0x0099: 0x2122, # TRADE MARK SIGN 0x009a: None, # UNDEFINED 0x009b: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 0x009c: 0x0153, # LATIN SMALL LIGATURE OE 0x009d: None, # UNDEFINED 0x009e: None, # UNDEFINED 0x009f: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS 0x00c3: 0x0102, # LATIN CAPITAL LETTER A WITH BREVE 0x00cc: 0x0300, # COMBINING GRAVE ACCENT 0x00d0: 0x0110, # LATIN CAPITAL LETTER D WITH STROKE 0x00d2: 0x0309, # COMBINING HOOK ABOVE 0x00d5: 0x01a0, # LATIN CAPITAL LETTER O WITH HORN 0x00dd: 0x01af, # LATIN CAPITAL LETTER U WITH HORN 0x00de: 0x0303, # COMBINING TILDE 0x00e3: 0x0103, # LATIN SMALL LETTER A WITH BREVE 0x00ec: 0x0301, # COMBINING ACUTE ACCENT 0x00f0: 0x0111, # LATIN SMALL LETTER D WITH STROKE 0x00f2: 0x0323, # COMBINING DOT BELOW 0x00f5: 0x01a1, # LATIN SMALL LETTER O WITH HORN 0x00fd: 0x01b0, # LATIN SMALL LETTER U WITH HORN 0x00fe: 0x20ab, # DONG SIGN }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP862.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x05d0, # HEBREW LETTER ALEF 0x0081: 0x05d1, # HEBREW LETTER BET 0x0082: 0x05d2, # HEBREW LETTER GIMEL 0x0083: 0x05d3, # HEBREW LETTER DALET 0x0084: 0x05d4, # HEBREW LETTER HE 0x0085: 0x05d5, # HEBREW LETTER VAV 0x0086: 0x05d6, # HEBREW LETTER ZAYIN 0x0087: 0x05d7, # HEBREW LETTER HET 0x0088: 0x05d8, # HEBREW LETTER TET 0x0089: 0x05d9, # HEBREW LETTER YOD 0x008a: 0x05da, # HEBREW LETTER FINAL KAF 0x008b: 0x05db, # HEBREW LETTER KAF 0x008c: 0x05dc, # HEBREW LETTER LAMED 0x008d: 0x05dd, # HEBREW LETTER FINAL MEM 0x008e: 0x05de, # HEBREW LETTER MEM 0x008f: 0x05df, # HEBREW LETTER FINAL NUN 0x0090: 0x05e0, # HEBREW LETTER NUN 0x0091: 0x05e1, # HEBREW LETTER SAMEKH 0x0092: 0x05e2, # HEBREW LETTER AYIN 0x0093: 0x05e3, # HEBREW LETTER FINAL PE 0x0094: 0x05e4, # HEBREW LETTER PE 0x0095: 0x05e5, # HEBREW LETTER FINAL TSADI 0x0096: 0x05e6, # HEBREW LETTER TSADI 0x0097: 0x05e7, # HEBREW LETTER QOF 0x0098: 0x05e8, # HEBREW LETTER RESH 0x0099: 0x05e9, # HEBREW LETTER SHIN 0x009a: 0x05ea, # HEBREW LETTER TAV 0x009b: 0x00a2, # CENT SIGN 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x00a5, # YEN SIGN 0x009e: 0x20a7, # PESETA SIGN 0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x00a5: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x00a6: 0x00aa, # FEMININE ORDINAL INDICATOR 0x00a7: 0x00ba, # MASCULINE ORDINAL INDICATOR 0x00a8: 0x00bf, # INVERTED QUESTION MARK 0x00a9: 0x2310, # REVERSED NOT SIGN 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x258c, # LEFT HALF BLOCK 0x00de: 0x2590, # RIGHT HALF BLOCK 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S (GERMAN) 0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA 0x00e3: 0x03c0, # GREEK SMALL LETTER PI 0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA 0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA 0x00e6: 0x00b5, # MICRO SIGN 0x00e7: 0x03c4, # GREEK SMALL LETTER TAU 0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI 0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA 0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA 0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA 0x00ec: 0x221e, # INFINITY 0x00ed: 0x03c6, # GREEK SMALL LETTER PHI 0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON 0x00ef: 0x2229, # INTERSECTION 0x00f0: 0x2261, # IDENTICAL TO 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO 0x00f3: 0x2264, # LESS-THAN OR EQUAL TO 0x00f4: 0x2320, # TOP HALF INTEGRAL 0x00f5: 0x2321, # BOTTOM HALF INTEGRAL 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x2248, # ALMOST EQUAL TO 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x2219, # BULLET OPERATOR 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x221a, # SQUARE ROOT 0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N 0x00fd: 0x00b2, # SUPERSCRIPT TWO 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# # shift_jis_2004.py: Python Unicode Codec for SHIFT_JIS_2004 # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: shift_jis_2004.py,v 1.1 2004/07/07 16:18:25 perky Exp $ # import _codecs_jp, codecs codec = _codecs_jp.getcodec('shift_jis_2004') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP775.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x0106, # LATIN CAPITAL LETTER C WITH ACUTE 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x0101, # LATIN SMALL LETTER A WITH MACRON 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0085: 0x0123, # LATIN SMALL LETTER G WITH CEDILLA 0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE 0x0087: 0x0107, # LATIN SMALL LETTER C WITH ACUTE 0x0088: 0x0142, # LATIN SMALL LETTER L WITH STROKE 0x0089: 0x0113, # LATIN SMALL LETTER E WITH MACRON 0x008a: 0x0156, # LATIN CAPITAL LETTER R WITH CEDILLA 0x008b: 0x0157, # LATIN SMALL LETTER R WITH CEDILLA 0x008c: 0x012b, # LATIN SMALL LETTER I WITH MACRON 0x008d: 0x0179, # LATIN CAPITAL LETTER Z WITH ACUTE 0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x00e6, # LATIN SMALL LIGATURE AE 0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE 0x0093: 0x014d, # LATIN SMALL LETTER O WITH MACRON 0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x0095: 0x0122, # LATIN CAPITAL LETTER G WITH CEDILLA 0x0096: 0x00a2, # CENT SIGN 0x0097: 0x015a, # LATIN CAPITAL LETTER S WITH ACUTE 0x0098: 0x015b, # LATIN SMALL LETTER S WITH ACUTE 0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x009e: 0x00d7, # MULTIPLICATION SIGN 0x009f: 0x00a4, # CURRENCY SIGN 0x00a0: 0x0100, # LATIN CAPITAL LETTER A WITH MACRON 0x00a1: 0x012a, # LATIN CAPITAL LETTER I WITH MACRON 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x00a4: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x00a5: 0x017a, # LATIN SMALL LETTER Z WITH ACUTE 0x00a6: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x00a7: 0x00a6, # BROKEN BAR 0x00a8: 0x00a9, # COPYRIGHT SIGN 0x00a9: 0x00ae, # REGISTERED SIGN 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00ad: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x00b6: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x00b7: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00b8: 0x0116, # LATIN CAPITAL LETTER E WITH DOT ABOVE 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x012e, # LATIN CAPITAL LETTER I WITH OGONEK 0x00be: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x0172, # LATIN CAPITAL LETTER U WITH OGONEK 0x00c7: 0x016a, # LATIN CAPITAL LETTER U WITH MACRON 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00d0: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x00d1: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x00d2: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00d3: 0x0117, # LATIN SMALL LETTER E WITH DOT ABOVE 0x00d4: 0x012f, # LATIN SMALL LETTER I WITH OGONEK 0x00d5: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00d6: 0x0173, # LATIN SMALL LETTER U WITH OGONEK 0x00d7: 0x016b, # LATIN SMALL LETTER U WITH MACRON 0x00d8: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x258c, # LEFT HALF BLOCK 0x00de: 0x2590, # RIGHT HALF BLOCK 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S (GERMAN) 0x00e2: 0x014c, # LATIN CAPITAL LETTER O WITH MACRON 0x00e3: 0x0143, # LATIN CAPITAL LETTER N WITH ACUTE 0x00e4: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x00e5: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x00e6: 0x00b5, # MICRO SIGN 0x00e7: 0x0144, # LATIN SMALL LETTER N WITH ACUTE 0x00e8: 0x0136, # LATIN CAPITAL LETTER K WITH CEDILLA 0x00e9: 0x0137, # LATIN SMALL LETTER K WITH CEDILLA 0x00ea: 0x013b, # LATIN CAPITAL LETTER L WITH CEDILLA 0x00eb: 0x013c, # LATIN SMALL LETTER L WITH CEDILLA 0x00ec: 0x0146, # LATIN SMALL LETTER N WITH CEDILLA 0x00ed: 0x0112, # LATIN CAPITAL LETTER E WITH MACRON 0x00ee: 0x0145, # LATIN CAPITAL LETTER N WITH CEDILLA 0x00ef: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x00f0: 0x00ad, # SOFT HYPHEN 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x00f3: 0x00be, # VULGAR FRACTION THREE QUARTERS 0x00f4: 0x00b6, # PILCROW SIGN 0x00f5: 0x00a7, # SECTION SIGN 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x2219, # BULLET OPERATOR 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x00b9, # SUPERSCRIPT ONE 0x00fc: 0x00b3, # SUPERSCRIPT THREE 0x00fd: 0x00b2, # SUPERSCRIPT TWO 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
"""Codec for quoted-printable encoding. Like base64 and rot13, this returns Python strings, not Unicode. """ import codecs, quopri try: from cStringIO import StringIO except ImportError: from StringIO import StringIO def quopri_encode(input, errors='strict'): """Encode the input, returning a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' f = StringIO(input) g = StringIO() quopri.encode(f, g, 1) output = g.getvalue() return (output, len(input)) def quopri_decode(input, errors='strict'): """Decode the input, returning a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' f = StringIO(input) g = StringIO() quopri.decode(f, g) output = g.getvalue() return (output, len(input)) class Codec(codecs.Codec): def encode(self, input,errors='strict'): return quopri_encode(input,errors) def decode(self, input,errors='strict'): return quopri_decode(input,errors) class StreamWriter(Codec, codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass # encodings module API def getregentry(): return (quopri_encode, quopri_decode, StreamReader, StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP037.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0004: 0x009c, # CONTROL 0x0005: 0x0009, # HORIZONTAL TABULATION 0x0006: 0x0086, # CONTROL 0x0007: 0x007f, # DELETE 0x0008: 0x0097, # CONTROL 0x0009: 0x008d, # CONTROL 0x000a: 0x008e, # CONTROL 0x0014: 0x009d, # CONTROL 0x0015: 0x0085, # CONTROL 0x0016: 0x0008, # BACKSPACE 0x0017: 0x0087, # CONTROL 0x001a: 0x0092, # CONTROL 0x001b: 0x008f, # CONTROL 0x0020: 0x0080, # CONTROL 0x0021: 0x0081, # CONTROL 0x0022: 0x0082, # CONTROL 0x0023: 0x0083, # CONTROL 0x0024: 0x0084, # CONTROL 0x0025: 0x000a, # LINE FEED 0x0026: 0x0017, # END OF TRANSMISSION BLOCK 0x0027: 0x001b, # ESCAPE 0x0028: 0x0088, # CONTROL 0x0029: 0x0089, # CONTROL 0x002a: 0x008a, # CONTROL 0x002b: 0x008b, # CONTROL 0x002c: 0x008c, # CONTROL 0x002d: 0x0005, # ENQUIRY 0x002e: 0x0006, # ACKNOWLEDGE 0x002f: 0x0007, # BELL 0x0030: 0x0090, # CONTROL 0x0031: 0x0091, # CONTROL 0x0032: 0x0016, # SYNCHRONOUS IDLE 0x0033: 0x0093, # CONTROL 0x0034: 0x0094, # CONTROL 0x0035: 0x0095, # CONTROL 0x0036: 0x0096, # CONTROL 0x0037: 0x0004, # END OF TRANSMISSION 0x0038: 0x0098, # CONTROL 0x0039: 0x0099, # CONTROL 0x003a: 0x009a, # CONTROL 0x003b: 0x009b, # CONTROL 0x003c: 0x0014, # DEVICE CONTROL FOUR 0x003d: 0x0015, # NEGATIVE ACKNOWLEDGE 0x003e: 0x009e, # CONTROL 0x003f: 0x001a, # SUBSTITUTE 0x0040: 0x0020, # SPACE 0x0041: 0x00a0, # NO-BREAK SPACE 0x0042: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0043: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0044: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0045: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x0046: 0x00e3, # LATIN SMALL LETTER A WITH TILDE 0x0047: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE 0x0048: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0049: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x004a: 0x00a2, # CENT SIGN 0x004b: 0x002e, # FULL STOP 0x004c: 0x003c, # LESS-THAN SIGN 0x004d: 0x0028, # LEFT PARENTHESIS 0x004e: 0x002b, # PLUS SIGN 0x004f: 0x007c, # VERTICAL LINE 0x0050: 0x0026, # AMPERSAND 0x0051: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0052: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0053: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x0054: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x0055: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x0056: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x0057: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x0058: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE 0x0059: 0x00df, # LATIN SMALL LETTER SHARP S (GERMAN) 0x005a: 0x0021, # EXCLAMATION MARK 0x005b: 0x0024, # DOLLAR SIGN 0x005c: 0x002a, # ASTERISK 0x005d: 0x0029, # RIGHT PARENTHESIS 0x005e: 0x003b, # SEMICOLON 0x005f: 0x00ac, # NOT SIGN 0x0060: 0x002d, # HYPHEN-MINUS 0x0061: 0x002f, # SOLIDUS 0x0062: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x0063: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x0064: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE 0x0065: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x0066: 0x00c3, # LATIN CAPITAL LETTER A WITH TILDE 0x0067: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x0068: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0069: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x006a: 0x00a6, # BROKEN BAR 0x006b: 0x002c, # COMMA 0x006c: 0x0025, # PERCENT SIGN 0x006d: 0x005f, # LOW LINE 0x006e: 0x003e, # GREATER-THAN SIGN 0x006f: 0x003f, # QUESTION MARK 0x0070: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x0071: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0072: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x0073: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x0074: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE 0x0075: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x0076: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x0077: 0x00cf, # LATIN CAPITAL LETTER I WITH DIAERESIS 0x0078: 0x00cc, # LATIN CAPITAL LETTER I WITH GRAVE 0x0079: 0x0060, # GRAVE ACCENT 0x007a: 0x003a, # COLON 0x007b: 0x0023, # NUMBER SIGN 0x007c: 0x0040, # COMMERCIAL AT 0x007d: 0x0027, # APOSTROPHE 0x007e: 0x003d, # EQUALS SIGN 0x007f: 0x0022, # QUOTATION MARK 0x0080: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x0081: 0x0061, # LATIN SMALL LETTER A 0x0082: 0x0062, # LATIN SMALL LETTER B 0x0083: 0x0063, # LATIN SMALL LETTER C 0x0084: 0x0064, # LATIN SMALL LETTER D 0x0085: 0x0065, # LATIN SMALL LETTER E 0x0086: 0x0066, # LATIN SMALL LETTER F 0x0087: 0x0067, # LATIN SMALL LETTER G 0x0088: 0x0068, # LATIN SMALL LETTER H 0x0089: 0x0069, # LATIN SMALL LETTER I 0x008a: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x008b: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x008c: 0x00f0, # LATIN SMALL LETTER ETH (ICELANDIC) 0x008d: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE 0x008e: 0x00fe, # LATIN SMALL LETTER THORN (ICELANDIC) 0x008f: 0x00b1, # PLUS-MINUS SIGN 0x0090: 0x00b0, # DEGREE SIGN 0x0091: 0x006a, # LATIN SMALL LETTER J 0x0092: 0x006b, # LATIN SMALL LETTER K 0x0093: 0x006c, # LATIN SMALL LETTER L 0x0094: 0x006d, # LATIN SMALL LETTER M 0x0095: 0x006e, # LATIN SMALL LETTER N 0x0096: 0x006f, # LATIN SMALL LETTER O 0x0097: 0x0070, # LATIN SMALL LETTER P 0x0098: 0x0071, # LATIN SMALL LETTER Q 0x0099: 0x0072, # LATIN SMALL LETTER R 0x009a: 0x00aa, # FEMININE ORDINAL INDICATOR 0x009b: 0x00ba, # MASCULINE ORDINAL INDICATOR 0x009c: 0x00e6, # LATIN SMALL LIGATURE AE 0x009d: 0x00b8, # CEDILLA 0x009e: 0x00c6, # LATIN CAPITAL LIGATURE AE 0x009f: 0x00a4, # CURRENCY SIGN 0x00a0: 0x00b5, # MICRO SIGN 0x00a1: 0x007e, # TILDE 0x00a2: 0x0073, # LATIN SMALL LETTER S 0x00a3: 0x0074, # LATIN SMALL LETTER T 0x00a4: 0x0075, # LATIN SMALL LETTER U 0x00a5: 0x0076, # LATIN SMALL LETTER V 0x00a6: 0x0077, # LATIN SMALL LETTER W 0x00a7: 0x0078, # LATIN SMALL LETTER X 0x00a8: 0x0079, # LATIN SMALL LETTER Y 0x00a9: 0x007a, # LATIN SMALL LETTER Z 0x00aa: 0x00a1, # INVERTED EXCLAMATION MARK 0x00ab: 0x00bf, # INVERTED QUESTION MARK 0x00ac: 0x00d0, # LATIN CAPITAL LETTER ETH (ICELANDIC) 0x00ad: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00ae: 0x00de, # LATIN CAPITAL LETTER THORN (ICELANDIC) 0x00af: 0x00ae, # REGISTERED SIGN 0x00b0: 0x005e, # CIRCUMFLEX ACCENT 0x00b1: 0x00a3, # POUND SIGN 0x00b2: 0x00a5, # YEN SIGN 0x00b3: 0x00b7, # MIDDLE DOT 0x00b4: 0x00a9, # COPYRIGHT SIGN 0x00b5: 0x00a7, # SECTION SIGN 0x00b7: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00b8: 0x00bd, # VULGAR FRACTION ONE HALF 0x00b9: 0x00be, # VULGAR FRACTION THREE QUARTERS 0x00ba: 0x005b, # LEFT SQUARE BRACKET 0x00bb: 0x005d, # RIGHT SQUARE BRACKET 0x00bc: 0x00af, # MACRON 0x00bd: 0x00a8, # DIAERESIS 0x00be: 0x00b4, # ACUTE ACCENT 0x00bf: 0x00d7, # MULTIPLICATION SIGN 0x00c0: 0x007b, # LEFT CURLY BRACKET 0x00c1: 0x0041, # LATIN CAPITAL LETTER A 0x00c2: 0x0042, # LATIN CAPITAL LETTER B 0x00c3: 0x0043, # LATIN CAPITAL LETTER C 0x00c4: 0x0044, # LATIN CAPITAL LETTER D 0x00c5: 0x0045, # LATIN CAPITAL LETTER E 0x00c6: 0x0046, # LATIN CAPITAL LETTER F 0x00c7: 0x0047, # LATIN CAPITAL LETTER G 0x00c8: 0x0048, # LATIN CAPITAL LETTER H 0x00c9: 0x0049, # LATIN CAPITAL LETTER I 0x00ca: 0x00ad, # SOFT HYPHEN 0x00cb: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x00cc: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x00cd: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE 0x00ce: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00cf: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x00d0: 0x007d, # RIGHT CURLY BRACKET 0x00d1: 0x004a, # LATIN CAPITAL LETTER J 0x00d2: 0x004b, # LATIN CAPITAL LETTER K 0x00d3: 0x004c, # LATIN CAPITAL LETTER L 0x00d4: 0x004d, # LATIN CAPITAL LETTER M 0x00d5: 0x004e, # LATIN CAPITAL LETTER N 0x00d6: 0x004f, # LATIN CAPITAL LETTER O 0x00d7: 0x0050, # LATIN CAPITAL LETTER P 0x00d8: 0x0051, # LATIN CAPITAL LETTER Q 0x00d9: 0x0052, # LATIN CAPITAL LETTER R 0x00da: 0x00b9, # SUPERSCRIPT ONE 0x00db: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x00dc: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x00dd: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x00de: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00df: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS 0x00e0: 0x005c, # REVERSE SOLIDUS 0x00e1: 0x00f7, # DIVISION SIGN 0x00e2: 0x0053, # LATIN CAPITAL LETTER S 0x00e3: 0x0054, # LATIN CAPITAL LETTER T 0x00e4: 0x0055, # LATIN CAPITAL LETTER U 0x00e5: 0x0056, # LATIN CAPITAL LETTER V 0x00e6: 0x0057, # LATIN CAPITAL LETTER W 0x00e7: 0x0058, # LATIN CAPITAL LETTER X 0x00e8: 0x0059, # LATIN CAPITAL LETTER Y 0x00e9: 0x005a, # LATIN CAPITAL LETTER Z 0x00ea: 0x00b2, # SUPERSCRIPT TWO 0x00eb: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00ec: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x00ed: 0x00d2, # LATIN CAPITAL LETTER O WITH GRAVE 0x00ee: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00ef: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x00f0: 0x0030, # DIGIT ZERO 0x00f1: 0x0031, # DIGIT ONE 0x00f2: 0x0032, # DIGIT TWO 0x00f3: 0x0033, # DIGIT THREE 0x00f4: 0x0034, # DIGIT FOUR 0x00f5: 0x0035, # DIGIT FIVE 0x00f6: 0x0036, # DIGIT SIX 0x00f7: 0x0037, # DIGIT SEVEN 0x00f8: 0x0038, # DIGIT EIGHT 0x00f9: 0x0039, # DIGIT NINE 0x00fa: 0x00b3, # SUPERSCRIPT THREE 0x00fb: 0x00db, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX 0x00fc: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x00fd: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE 0x00fe: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00ff: 0x009f, # CONTROL }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CYRILLIC.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x0410, # CYRILLIC CAPITAL LETTER A 0x0081: 0x0411, # CYRILLIC CAPITAL LETTER BE 0x0082: 0x0412, # CYRILLIC CAPITAL LETTER VE 0x0083: 0x0413, # CYRILLIC CAPITAL LETTER GHE 0x0084: 0x0414, # CYRILLIC CAPITAL LETTER DE 0x0085: 0x0415, # CYRILLIC CAPITAL LETTER IE 0x0086: 0x0416, # CYRILLIC CAPITAL LETTER ZHE 0x0087: 0x0417, # CYRILLIC CAPITAL LETTER ZE 0x0088: 0x0418, # CYRILLIC CAPITAL LETTER I 0x0089: 0x0419, # CYRILLIC CAPITAL LETTER SHORT I 0x008a: 0x041a, # CYRILLIC CAPITAL LETTER KA 0x008b: 0x041b, # CYRILLIC CAPITAL LETTER EL 0x008c: 0x041c, # CYRILLIC CAPITAL LETTER EM 0x008d: 0x041d, # CYRILLIC CAPITAL LETTER EN 0x008e: 0x041e, # CYRILLIC CAPITAL LETTER O 0x008f: 0x041f, # CYRILLIC CAPITAL LETTER PE 0x0090: 0x0420, # CYRILLIC CAPITAL LETTER ER 0x0091: 0x0421, # CYRILLIC CAPITAL LETTER ES 0x0092: 0x0422, # CYRILLIC CAPITAL LETTER TE 0x0093: 0x0423, # CYRILLIC CAPITAL LETTER U 0x0094: 0x0424, # CYRILLIC CAPITAL LETTER EF 0x0095: 0x0425, # CYRILLIC CAPITAL LETTER HA 0x0096: 0x0426, # CYRILLIC CAPITAL LETTER TSE 0x0097: 0x0427, # CYRILLIC CAPITAL LETTER CHE 0x0098: 0x0428, # CYRILLIC CAPITAL LETTER SHA 0x0099: 0x0429, # CYRILLIC CAPITAL LETTER SHCHA 0x009a: 0x042a, # CYRILLIC CAPITAL LETTER HARD SIGN 0x009b: 0x042b, # CYRILLIC CAPITAL LETTER YERU 0x009c: 0x042c, # CYRILLIC CAPITAL LETTER SOFT SIGN 0x009d: 0x042d, # CYRILLIC CAPITAL LETTER E 0x009e: 0x042e, # CYRILLIC CAPITAL LETTER YU 0x009f: 0x042f, # CYRILLIC CAPITAL LETTER YA 0x00a0: 0x2020, # DAGGER 0x00a1: 0x00b0, # DEGREE SIGN 0x00a4: 0x00a7, # SECTION SIGN 0x00a5: 0x2022, # BULLET 0x00a6: 0x00b6, # PILCROW SIGN 0x00a7: 0x0406, # CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I 0x00a8: 0x00ae, # REGISTERED SIGN 0x00aa: 0x2122, # TRADE MARK SIGN 0x00ab: 0x0402, # CYRILLIC CAPITAL LETTER DJE 0x00ac: 0x0452, # CYRILLIC SMALL LETTER DJE 0x00ad: 0x2260, # NOT EQUAL TO 0x00ae: 0x0403, # CYRILLIC CAPITAL LETTER GJE 0x00af: 0x0453, # CYRILLIC SMALL LETTER GJE 0x00b0: 0x221e, # INFINITY 0x00b2: 0x2264, # LESS-THAN OR EQUAL TO 0x00b3: 0x2265, # GREATER-THAN OR EQUAL TO 0x00b4: 0x0456, # CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I 0x00b6: 0x2202, # PARTIAL DIFFERENTIAL 0x00b7: 0x0408, # CYRILLIC CAPITAL LETTER JE 0x00b8: 0x0404, # CYRILLIC CAPITAL LETTER UKRAINIAN IE 0x00b9: 0x0454, # CYRILLIC SMALL LETTER UKRAINIAN IE 0x00ba: 0x0407, # CYRILLIC CAPITAL LETTER YI 0x00bb: 0x0457, # CYRILLIC SMALL LETTER YI 0x00bc: 0x0409, # CYRILLIC CAPITAL LETTER LJE 0x00bd: 0x0459, # CYRILLIC SMALL LETTER LJE 0x00be: 0x040a, # CYRILLIC CAPITAL LETTER NJE 0x00bf: 0x045a, # CYRILLIC SMALL LETTER NJE 0x00c0: 0x0458, # CYRILLIC SMALL LETTER JE 0x00c1: 0x0405, # CYRILLIC CAPITAL LETTER DZE 0x00c2: 0x00ac, # NOT SIGN 0x00c3: 0x221a, # SQUARE ROOT 0x00c4: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x00c5: 0x2248, # ALMOST EQUAL TO 0x00c6: 0x2206, # INCREMENT 0x00c7: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c8: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c9: 0x2026, # HORIZONTAL ELLIPSIS 0x00ca: 0x00a0, # NO-BREAK SPACE 0x00cb: 0x040b, # CYRILLIC CAPITAL LETTER TSHE 0x00cc: 0x045b, # CYRILLIC SMALL LETTER TSHE 0x00cd: 0x040c, # CYRILLIC CAPITAL LETTER KJE 0x00ce: 0x045c, # CYRILLIC SMALL LETTER KJE 0x00cf: 0x0455, # CYRILLIC SMALL LETTER DZE 0x00d0: 0x2013, # EN DASH 0x00d1: 0x2014, # EM DASH 0x00d2: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x00d3: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x00d4: 0x2018, # LEFT SINGLE QUOTATION MARK 0x00d5: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x00d6: 0x00f7, # DIVISION SIGN 0x00d7: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x00d8: 0x040e, # CYRILLIC CAPITAL LETTER SHORT U 0x00d9: 0x045e, # CYRILLIC SMALL LETTER SHORT U 0x00da: 0x040f, # CYRILLIC CAPITAL LETTER DZHE 0x00db: 0x045f, # CYRILLIC SMALL LETTER DZHE 0x00dc: 0x2116, # NUMERO SIGN 0x00dd: 0x0401, # CYRILLIC CAPITAL LETTER IO 0x00de: 0x0451, # CYRILLIC SMALL LETTER IO 0x00df: 0x044f, # CYRILLIC SMALL LETTER YA 0x00e0: 0x0430, # CYRILLIC SMALL LETTER A 0x00e1: 0x0431, # CYRILLIC SMALL LETTER BE 0x00e2: 0x0432, # CYRILLIC SMALL LETTER VE 0x00e3: 0x0433, # CYRILLIC SMALL LETTER GHE 0x00e4: 0x0434, # CYRILLIC SMALL LETTER DE 0x00e5: 0x0435, # CYRILLIC SMALL LETTER IE 0x00e6: 0x0436, # CYRILLIC SMALL LETTER ZHE 0x00e7: 0x0437, # CYRILLIC SMALL LETTER ZE 0x00e8: 0x0438, # CYRILLIC SMALL LETTER I 0x00e9: 0x0439, # CYRILLIC SMALL LETTER SHORT I 0x00ea: 0x043a, # CYRILLIC SMALL LETTER KA 0x00eb: 0x043b, # CYRILLIC SMALL LETTER EL 0x00ec: 0x043c, # CYRILLIC SMALL LETTER EM 0x00ed: 0x043d, # CYRILLIC SMALL LETTER EN 0x00ee: 0x043e, # CYRILLIC SMALL LETTER O 0x00ef: 0x043f, # CYRILLIC SMALL LETTER PE 0x00f0: 0x0440, # CYRILLIC SMALL LETTER ER 0x00f1: 0x0441, # CYRILLIC SMALL LETTER ES 0x00f2: 0x0442, # CYRILLIC SMALL LETTER TE 0x00f3: 0x0443, # CYRILLIC SMALL LETTER U 0x00f4: 0x0444, # CYRILLIC SMALL LETTER EF 0x00f5: 0x0445, # CYRILLIC SMALL LETTER HA 0x00f6: 0x0446, # CYRILLIC SMALL LETTER TSE 0x00f7: 0x0447, # CYRILLIC SMALL LETTER CHE 0x00f8: 0x0448, # CYRILLIC SMALL LETTER SHA 0x00f9: 0x0449, # CYRILLIC SMALL LETTER SHCHA 0x00fa: 0x044a, # CYRILLIC SMALL LETTER HARD SIGN 0x00fb: 0x044b, # CYRILLIC SMALL LETTER YERU 0x00fc: 0x044c, # CYRILLIC SMALL LETTER SOFT SIGN 0x00fd: 0x044d, # CYRILLIC SMALL LETTER E 0x00fe: 0x044e, # CYRILLIC SMALL LETTER YU 0x00ff: 0x00a4, # CURRENCY SIGN }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP852.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0085: 0x016f, # LATIN SMALL LETTER U WITH RING ABOVE 0x0086: 0x0107, # LATIN SMALL LETTER C WITH ACUTE 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0088: 0x0142, # LATIN SMALL LETTER L WITH STROKE 0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x008a: 0x0150, # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE 0x008b: 0x0151, # LATIN SMALL LETTER O WITH DOUBLE ACUTE 0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x008d: 0x0179, # LATIN CAPITAL LETTER Z WITH ACUTE 0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x008f: 0x0106, # LATIN CAPITAL LETTER C WITH ACUTE 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x0139, # LATIN CAPITAL LETTER L WITH ACUTE 0x0092: 0x013a, # LATIN SMALL LETTER L WITH ACUTE 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x0095: 0x013d, # LATIN CAPITAL LETTER L WITH CARON 0x0096: 0x013e, # LATIN SMALL LETTER L WITH CARON 0x0097: 0x015a, # LATIN CAPITAL LETTER S WITH ACUTE 0x0098: 0x015b, # LATIN SMALL LETTER S WITH ACUTE 0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x0164, # LATIN CAPITAL LETTER T WITH CARON 0x009c: 0x0165, # LATIN SMALL LETTER T WITH CARON 0x009d: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE 0x009e: 0x00d7, # MULTIPLICATION SIGN 0x009f: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x00a5: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x00a6: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00a7: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00a8: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00a9: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x017a, # LATIN SMALL LETTER Z WITH ACUTE 0x00ac: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x00ad: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x00b6: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00b7: 0x011a, # LATIN CAPITAL LETTER E WITH CARON 0x00b8: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x00be: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x0102, # LATIN CAPITAL LETTER A WITH BREVE 0x00c7: 0x0103, # LATIN SMALL LETTER A WITH BREVE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x00a4, # CURRENCY SIGN 0x00d0: 0x0111, # LATIN SMALL LETTER D WITH STROKE 0x00d1: 0x0110, # LATIN CAPITAL LETTER D WITH STROKE 0x00d2: 0x010e, # LATIN CAPITAL LETTER D WITH CARON 0x00d3: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00d4: 0x010f, # LATIN SMALL LETTER D WITH CARON 0x00d5: 0x0147, # LATIN CAPITAL LETTER N WITH CARON 0x00d6: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x00d7: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00d8: 0x011b, # LATIN SMALL LETTER E WITH CARON 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x0162, # LATIN CAPITAL LETTER T WITH CEDILLA 0x00de: 0x016e, # LATIN CAPITAL LETTER U WITH RING ABOVE 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S 0x00e2: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00e3: 0x0143, # LATIN CAPITAL LETTER N WITH ACUTE 0x00e4: 0x0144, # LATIN SMALL LETTER N WITH ACUTE 0x00e5: 0x0148, # LATIN SMALL LETTER N WITH CARON 0x00e6: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00e7: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00e8: 0x0154, # LATIN CAPITAL LETTER R WITH ACUTE 0x00e9: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00ea: 0x0155, # LATIN SMALL LETTER R WITH ACUTE 0x00eb: 0x0170, # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE 0x00ec: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE 0x00ed: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00ee: 0x0163, # LATIN SMALL LETTER T WITH CEDILLA 0x00ef: 0x00b4, # ACUTE ACCENT 0x00f0: 0x00ad, # SOFT HYPHEN 0x00f1: 0x02dd, # DOUBLE ACUTE ACCENT 0x00f2: 0x02db, # OGONEK 0x00f3: 0x02c7, # CARON 0x00f4: 0x02d8, # BREVE 0x00f5: 0x00a7, # SECTION SIGN 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x00b8, # CEDILLA 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x00a8, # DIAERESIS 0x00fa: 0x02d9, # DOT ABOVE 0x00fb: 0x0171, # LATIN SMALL LETTER U WITH DOUBLE ACUTE 0x00fc: 0x0158, # LATIN CAPITAL LETTER R WITH CARON 0x00fd: 0x0159, # LATIN SMALL LETTER R WITH CARON 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'PTCP154.txt' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x0496, # CYRILLIC CAPITAL LETTER ZHE WITH DESCENDER 0x0081: 0x0492, # CYRILLIC CAPITAL LETTER GHE WITH STROKE 0x0082: 0x04ee, # CYRILLIC CAPITAL LETTER U WITH MACRON 0x0083: 0x0493, # CYRILLIC SMALL LETTER GHE WITH STROKE 0x0084: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x0085: 0x2026, # HORIZONTAL ELLIPSIS 0x0086: 0x04b6, # CYRILLIC CAPITAL LETTER CHE WITH DESCENDER 0x0087: 0x04ae, # CYRILLIC CAPITAL LETTER STRAIGHT U 0x0088: 0x04b2, # CYRILLIC CAPITAL LETTER HA WITH DESCENDER 0x0089: 0x04af, # CYRILLIC SMALL LETTER STRAIGHT U 0x008a: 0x04a0, # CYRILLIC CAPITAL LETTER BASHKIR KA 0x008b: 0x04e2, # CYRILLIC CAPITAL LETTER I WITH MACRON 0x008c: 0x04a2, # CYRILLIC CAPITAL LETTER EN WITH DESCENDER 0x008d: 0x049a, # CYRILLIC CAPITAL LETTER KA WITH DESCENDER 0x008e: 0x04ba, # CYRILLIC CAPITAL LETTER SHHA 0x008f: 0x04b8, # CYRILLIC CAPITAL LETTER CHE WITH VERTICAL STROKE 0x0090: 0x0497, # CYRILLIC SMALL LETTER ZHE WITH DESCENDER 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x0095: 0x2022, # BULLET 0x0096: 0x2013, # EN DASH 0x0097: 0x2014, # EM DASH 0x0098: 0x04b3, # CYRILLIC SMALL LETTER HA WITH DESCENDER 0x0099: 0x04b7, # CYRILLIC SMALL LETTER CHE WITH DESCENDER 0x009a: 0x04a1, # CYRILLIC SMALL LETTER BASHKIR KA 0x009b: 0x04e3, # CYRILLIC SMALL LETTER I WITH MACRON 0x009c: 0x04a3, # CYRILLIC SMALL LETTER EN WITH DESCENDER 0x009d: 0x049b, # CYRILLIC SMALL LETTER KA WITH DESCENDER 0x009e: 0x04bb, # CYRILLIC SMALL LETTER SHHA 0x009f: 0x04b9, # CYRILLIC SMALL LETTER CHE WITH VERTICAL STROKE 0x00a1: 0x040e, # CYRILLIC CAPITAL LETTER SHORT U (Byelorussian) 0x00a2: 0x045e, # CYRILLIC SMALL LETTER SHORT U (Byelorussian) 0x00a3: 0x0408, # CYRILLIC CAPITAL LETTER JE 0x00a4: 0x04e8, # CYRILLIC CAPITAL LETTER BARRED O 0x00a5: 0x0498, # CYRILLIC CAPITAL LETTER ZE WITH DESCENDER 0x00a6: 0x04b0, # CYRILLIC CAPITAL LETTER STRAIGHT U WITH STROKE 0x00a8: 0x0401, # CYRILLIC CAPITAL LETTER IO 0x00aa: 0x04d8, # CYRILLIC CAPITAL LETTER SCHWA 0x00ad: 0x04ef, # CYRILLIC SMALL LETTER U WITH MACRON 0x00af: 0x049c, # CYRILLIC CAPITAL LETTER KA WITH VERTICAL STROKE 0x00b1: 0x04b1, # CYRILLIC SMALL LETTER STRAIGHT U WITH STROKE 0x00b2: 0x0406, # CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I 0x00b3: 0x0456, # CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I 0x00b4: 0x0499, # CYRILLIC SMALL LETTER ZE WITH DESCENDER 0x00b5: 0x04e9, # CYRILLIC SMALL LETTER BARRED O 0x00b8: 0x0451, # CYRILLIC SMALL LETTER IO 0x00b9: 0x2116, # NUMERO SIGN 0x00ba: 0x04d9, # CYRILLIC SMALL LETTER SCHWA 0x00bc: 0x0458, # CYRILLIC SMALL LETTER JE 0x00bd: 0x04aa, # CYRILLIC CAPITAL LETTER ES WITH DESCENDER 0x00be: 0x04ab, # CYRILLIC SMALL LETTER ES WITH DESCENDER 0x00bf: 0x049d, # CYRILLIC SMALL LETTER KA WITH VERTICAL STROKE 0x00c0: 0x0410, # CYRILLIC CAPITAL LETTER A 0x00c1: 0x0411, # CYRILLIC CAPITAL LETTER BE 0x00c2: 0x0412, # CYRILLIC CAPITAL LETTER VE 0x00c3: 0x0413, # CYRILLIC CAPITAL LETTER GHE 0x00c4: 0x0414, # CYRILLIC CAPITAL LETTER DE 0x00c5: 0x0415, # CYRILLIC CAPITAL LETTER IE 0x00c6: 0x0416, # CYRILLIC CAPITAL LETTER ZHE 0x00c7: 0x0417, # CYRILLIC CAPITAL LETTER ZE 0x00c8: 0x0418, # CYRILLIC CAPITAL LETTER I 0x00c9: 0x0419, # CYRILLIC CAPITAL LETTER SHORT I 0x00ca: 0x041a, # CYRILLIC CAPITAL LETTER KA 0x00cb: 0x041b, # CYRILLIC CAPITAL LETTER EL 0x00cc: 0x041c, # CYRILLIC CAPITAL LETTER EM 0x00cd: 0x041d, # CYRILLIC CAPITAL LETTER EN 0x00ce: 0x041e, # CYRILLIC CAPITAL LETTER O 0x00cf: 0x041f, # CYRILLIC CAPITAL LETTER PE 0x00d0: 0x0420, # CYRILLIC CAPITAL LETTER ER 0x00d1: 0x0421, # CYRILLIC CAPITAL LETTER ES 0x00d2: 0x0422, # CYRILLIC CAPITAL LETTER TE 0x00d3: 0x0423, # CYRILLIC CAPITAL LETTER U 0x00d4: 0x0424, # CYRILLIC CAPITAL LETTER EF 0x00d5: 0x0425, # CYRILLIC CAPITAL LETTER HA 0x00d6: 0x0426, # CYRILLIC CAPITAL LETTER TSE 0x00d7: 0x0427, # CYRILLIC CAPITAL LETTER CHE 0x00d8: 0x0428, # CYRILLIC CAPITAL LETTER SHA 0x00d9: 0x0429, # CYRILLIC CAPITAL LETTER SHCHA 0x00da: 0x042a, # CYRILLIC CAPITAL LETTER HARD SIGN 0x00db: 0x042b, # CYRILLIC CAPITAL LETTER YERU 0x00dc: 0x042c, # CYRILLIC CAPITAL LETTER SOFT SIGN 0x00dd: 0x042d, # CYRILLIC CAPITAL LETTER E 0x00de: 0x042e, # CYRILLIC CAPITAL LETTER YU 0x00df: 0x042f, # CYRILLIC CAPITAL LETTER YA 0x00e0: 0x0430, # CYRILLIC SMALL LETTER A 0x00e1: 0x0431, # CYRILLIC SMALL LETTER BE 0x00e2: 0x0432, # CYRILLIC SMALL LETTER VE 0x00e3: 0x0433, # CYRILLIC SMALL LETTER GHE 0x00e4: 0x0434, # CYRILLIC SMALL LETTER DE 0x00e5: 0x0435, # CYRILLIC SMALL LETTER IE 0x00e6: 0x0436, # CYRILLIC SMALL LETTER ZHE 0x00e7: 0x0437, # CYRILLIC SMALL LETTER ZE 0x00e8: 0x0438, # CYRILLIC SMALL LETTER I 0x00e9: 0x0439, # CYRILLIC SMALL LETTER SHORT I 0x00ea: 0x043a, # CYRILLIC SMALL LETTER KA 0x00eb: 0x043b, # CYRILLIC SMALL LETTER EL 0x00ec: 0x043c, # CYRILLIC SMALL LETTER EM 0x00ed: 0x043d, # CYRILLIC SMALL LETTER EN 0x00ee: 0x043e, # CYRILLIC SMALL LETTER O 0x00ef: 0x043f, # CYRILLIC SMALL LETTER PE 0x00f0: 0x0440, # CYRILLIC SMALL LETTER ER 0x00f1: 0x0441, # CYRILLIC SMALL LETTER ES 0x00f2: 0x0442, # CYRILLIC SMALL LETTER TE 0x00f3: 0x0443, # CYRILLIC SMALL LETTER U 0x00f4: 0x0444, # CYRILLIC SMALL LETTER EF 0x00f5: 0x0445, # CYRILLIC SMALL LETTER HA 0x00f6: 0x0446, # CYRILLIC SMALL LETTER TSE 0x00f7: 0x0447, # CYRILLIC SMALL LETTER CHE 0x00f8: 0x0448, # CYRILLIC SMALL LETTER SHA 0x00f9: 0x0449, # CYRILLIC SMALL LETTER SHCHA 0x00fa: 0x044a, # CYRILLIC SMALL LETTER HARD SIGN 0x00fb: 0x044b, # CYRILLIC SMALL LETTER YERU 0x00fc: 0x044c, # CYRILLIC SMALL LETTER SOFT SIGN 0x00fd: 0x044d, # CYRILLIC SMALL LETTER E 0x00fe: 0x044e, # CYRILLIC SMALL LETTER YU 0x00ff: 0x044f, # CYRILLIC SMALL LETTER YA }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP1251.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x0402, # CYRILLIC CAPITAL LETTER DJE 0x0081: 0x0403, # CYRILLIC CAPITAL LETTER GJE 0x0082: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x0083: 0x0453, # CYRILLIC SMALL LETTER GJE 0x0084: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x0085: 0x2026, # HORIZONTAL ELLIPSIS 0x0086: 0x2020, # DAGGER 0x0087: 0x2021, # DOUBLE DAGGER 0x0088: 0x20ac, # EURO SIGN 0x0089: 0x2030, # PER MILLE SIGN 0x008a: 0x0409, # CYRILLIC CAPITAL LETTER LJE 0x008b: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x008c: 0x040a, # CYRILLIC CAPITAL LETTER NJE 0x008d: 0x040c, # CYRILLIC CAPITAL LETTER KJE 0x008e: 0x040b, # CYRILLIC CAPITAL LETTER TSHE 0x008f: 0x040f, # CYRILLIC CAPITAL LETTER DZHE 0x0090: 0x0452, # CYRILLIC SMALL LETTER DJE 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x0095: 0x2022, # BULLET 0x0096: 0x2013, # EN DASH 0x0097: 0x2014, # EM DASH 0x0098: None, # UNDEFINED 0x0099: 0x2122, # TRADE MARK SIGN 0x009a: 0x0459, # CYRILLIC SMALL LETTER LJE 0x009b: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 0x009c: 0x045a, # CYRILLIC SMALL LETTER NJE 0x009d: 0x045c, # CYRILLIC SMALL LETTER KJE 0x009e: 0x045b, # CYRILLIC SMALL LETTER TSHE 0x009f: 0x045f, # CYRILLIC SMALL LETTER DZHE 0x00a1: 0x040e, # CYRILLIC CAPITAL LETTER SHORT U 0x00a2: 0x045e, # CYRILLIC SMALL LETTER SHORT U 0x00a3: 0x0408, # CYRILLIC CAPITAL LETTER JE 0x00a5: 0x0490, # CYRILLIC CAPITAL LETTER GHE WITH UPTURN 0x00a8: 0x0401, # CYRILLIC CAPITAL LETTER IO 0x00aa: 0x0404, # CYRILLIC CAPITAL LETTER UKRAINIAN IE 0x00af: 0x0407, # CYRILLIC CAPITAL LETTER YI 0x00b2: 0x0406, # CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I 0x00b3: 0x0456, # CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I 0x00b4: 0x0491, # CYRILLIC SMALL LETTER GHE WITH UPTURN 0x00b8: 0x0451, # CYRILLIC SMALL LETTER IO 0x00b9: 0x2116, # NUMERO SIGN 0x00ba: 0x0454, # CYRILLIC SMALL LETTER UKRAINIAN IE 0x00bc: 0x0458, # CYRILLIC SMALL LETTER JE 0x00bd: 0x0405, # CYRILLIC CAPITAL LETTER DZE 0x00be: 0x0455, # CYRILLIC SMALL LETTER DZE 0x00bf: 0x0457, # CYRILLIC SMALL LETTER YI 0x00c0: 0x0410, # CYRILLIC CAPITAL LETTER A 0x00c1: 0x0411, # CYRILLIC CAPITAL LETTER BE 0x00c2: 0x0412, # CYRILLIC CAPITAL LETTER VE 0x00c3: 0x0413, # CYRILLIC CAPITAL LETTER GHE 0x00c4: 0x0414, # CYRILLIC CAPITAL LETTER DE 0x00c5: 0x0415, # CYRILLIC CAPITAL LETTER IE 0x00c6: 0x0416, # CYRILLIC CAPITAL LETTER ZHE 0x00c7: 0x0417, # CYRILLIC CAPITAL LETTER ZE 0x00c8: 0x0418, # CYRILLIC CAPITAL LETTER I 0x00c9: 0x0419, # CYRILLIC CAPITAL LETTER SHORT I 0x00ca: 0x041a, # CYRILLIC CAPITAL LETTER KA 0x00cb: 0x041b, # CYRILLIC CAPITAL LETTER EL 0x00cc: 0x041c, # CYRILLIC CAPITAL LETTER EM 0x00cd: 0x041d, # CYRILLIC CAPITAL LETTER EN 0x00ce: 0x041e, # CYRILLIC CAPITAL LETTER O 0x00cf: 0x041f, # CYRILLIC CAPITAL LETTER PE 0x00d0: 0x0420, # CYRILLIC CAPITAL LETTER ER 0x00d1: 0x0421, # CYRILLIC CAPITAL LETTER ES 0x00d2: 0x0422, # CYRILLIC CAPITAL LETTER TE 0x00d3: 0x0423, # CYRILLIC CAPITAL LETTER U 0x00d4: 0x0424, # CYRILLIC CAPITAL LETTER EF 0x00d5: 0x0425, # CYRILLIC CAPITAL LETTER HA 0x00d6: 0x0426, # CYRILLIC CAPITAL LETTER TSE 0x00d7: 0x0427, # CYRILLIC CAPITAL LETTER CHE 0x00d8: 0x0428, # CYRILLIC CAPITAL LETTER SHA 0x00d9: 0x0429, # CYRILLIC CAPITAL LETTER SHCHA 0x00da: 0x042a, # CYRILLIC CAPITAL LETTER HARD SIGN 0x00db: 0x042b, # CYRILLIC CAPITAL LETTER YERU 0x00dc: 0x042c, # CYRILLIC CAPITAL LETTER SOFT SIGN 0x00dd: 0x042d, # CYRILLIC CAPITAL LETTER E 0x00de: 0x042e, # CYRILLIC CAPITAL LETTER YU 0x00df: 0x042f, # CYRILLIC CAPITAL LETTER YA 0x00e0: 0x0430, # CYRILLIC SMALL LETTER A 0x00e1: 0x0431, # CYRILLIC SMALL LETTER BE 0x00e2: 0x0432, # CYRILLIC SMALL LETTER VE 0x00e3: 0x0433, # CYRILLIC SMALL LETTER GHE 0x00e4: 0x0434, # CYRILLIC SMALL LETTER DE 0x00e5: 0x0435, # CYRILLIC SMALL LETTER IE 0x00e6: 0x0436, # CYRILLIC SMALL LETTER ZHE 0x00e7: 0x0437, # CYRILLIC SMALL LETTER ZE 0x00e8: 0x0438, # CYRILLIC SMALL LETTER I 0x00e9: 0x0439, # CYRILLIC SMALL LETTER SHORT I 0x00ea: 0x043a, # CYRILLIC SMALL LETTER KA 0x00eb: 0x043b, # CYRILLIC SMALL LETTER EL 0x00ec: 0x043c, # CYRILLIC SMALL LETTER EM 0x00ed: 0x043d, # CYRILLIC SMALL LETTER EN 0x00ee: 0x043e, # CYRILLIC SMALL LETTER O 0x00ef: 0x043f, # CYRILLIC SMALL LETTER PE 0x00f0: 0x0440, # CYRILLIC SMALL LETTER ER 0x00f1: 0x0441, # CYRILLIC SMALL LETTER ES 0x00f2: 0x0442, # CYRILLIC SMALL LETTER TE 0x00f3: 0x0443, # CYRILLIC SMALL LETTER U 0x00f4: 0x0444, # CYRILLIC SMALL LETTER EF 0x00f5: 0x0445, # CYRILLIC SMALL LETTER HA 0x00f6: 0x0446, # CYRILLIC SMALL LETTER TSE 0x00f7: 0x0447, # CYRILLIC SMALL LETTER CHE 0x00f8: 0x0448, # CYRILLIC SMALL LETTER SHA 0x00f9: 0x0449, # CYRILLIC SMALL LETTER SHCHA 0x00fa: 0x044a, # CYRILLIC SMALL LETTER HARD SIGN 0x00fb: 0x044b, # CYRILLIC SMALL LETTER YERU 0x00fc: 0x044c, # CYRILLIC SMALL LETTER SOFT SIGN 0x00fd: 0x044d, # CYRILLIC SMALL LETTER E 0x00fe: 0x044e, # CYRILLIC SMALL LETTER YU 0x00ff: 0x044f, # CYRILLIC SMALL LETTER YA }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
#!/usr/bin/env python """ Python Character Mapping Codec for ROT13. See http://ucsub.colorado.edu/~kominek/rot13/ for details. Written by Marc-Andre Lemburg (mal@lemburg.com). """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0041: 0x004e, 0x0042: 0x004f, 0x0043: 0x0050, 0x0044: 0x0051, 0x0045: 0x0052, 0x0046: 0x0053, 0x0047: 0x0054, 0x0048: 0x0055, 0x0049: 0x0056, 0x004a: 0x0057, 0x004b: 0x0058, 0x004c: 0x0059, 0x004d: 0x005a, 0x004e: 0x0041, 0x004f: 0x0042, 0x0050: 0x0043, 0x0051: 0x0044, 0x0052: 0x0045, 0x0053: 0x0046, 0x0054: 0x0047, 0x0055: 0x0048, 0x0056: 0x0049, 0x0057: 0x004a, 0x0058: 0x004b, 0x0059: 0x004c, 0x005a: 0x004d, 0x0061: 0x006e, 0x0062: 0x006f, 0x0063: 0x0070, 0x0064: 0x0071, 0x0065: 0x0072, 0x0066: 0x0073, 0x0067: 0x0074, 0x0068: 0x0075, 0x0069: 0x0076, 0x006a: 0x0077, 0x006b: 0x0078, 0x006c: 0x0079, 0x006d: 0x007a, 0x006e: 0x0061, 0x006f: 0x0062, 0x0070: 0x0063, 0x0071: 0x0064, 0x0072: 0x0065, 0x0073: 0x0066, 0x0074: 0x0067, 0x0075: 0x0068, 0x0076: 0x0069, 0x0077: 0x006a, 0x0078: 0x006b, 0x0079: 0x006c, 0x007a: 0x006d, }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map) ### Filter API def rot13(infile, outfile): outfile.write(infile.read().encode('rot-13')) if __name__ == '__main__': import sys rot13(sys.stdin, sys.stdout)
Python
# # gb18030.py: Python Unicode Codec for GB18030 # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: gb18030.py,v 1.8 2004/06/28 18:16:03 perky Exp $ # import _codecs_cn, codecs codec = _codecs_cn.getcodec('gb18030') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python Character Mapping Codec generated from '8859-3.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: 0x0126, # LATIN CAPITAL LETTER H WITH STROKE 0x00a2: 0x02d8, # BREVE 0x00a5: None, 0x00a6: 0x0124, # LATIN CAPITAL LETTER H WITH CIRCUMFLEX 0x00a9: 0x0130, # LATIN CAPITAL LETTER I WITH DOT ABOVE 0x00aa: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x00ab: 0x011e, # LATIN CAPITAL LETTER G WITH BREVE 0x00ac: 0x0134, # LATIN CAPITAL LETTER J WITH CIRCUMFLEX 0x00ae: None, 0x00af: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x00b1: 0x0127, # LATIN SMALL LETTER H WITH STROKE 0x00b6: 0x0125, # LATIN SMALL LETTER H WITH CIRCUMFLEX 0x00b9: 0x0131, # LATIN SMALL LETTER DOTLESS I 0x00ba: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA 0x00bb: 0x011f, # LATIN SMALL LETTER G WITH BREVE 0x00bc: 0x0135, # LATIN SMALL LETTER J WITH CIRCUMFLEX 0x00be: None, 0x00bf: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x00c3: None, 0x00c5: 0x010a, # LATIN CAPITAL LETTER C WITH DOT ABOVE 0x00c6: 0x0108, # LATIN CAPITAL LETTER C WITH CIRCUMFLEX 0x00d0: None, 0x00d5: 0x0120, # LATIN CAPITAL LETTER G WITH DOT ABOVE 0x00d8: 0x011c, # LATIN CAPITAL LETTER G WITH CIRCUMFLEX 0x00dd: 0x016c, # LATIN CAPITAL LETTER U WITH BREVE 0x00de: 0x015c, # LATIN CAPITAL LETTER S WITH CIRCUMFLEX 0x00e3: None, 0x00e5: 0x010b, # LATIN SMALL LETTER C WITH DOT ABOVE 0x00e6: 0x0109, # LATIN SMALL LETTER C WITH CIRCUMFLEX 0x00f0: None, 0x00f5: 0x0121, # LATIN SMALL LETTER G WITH DOT ABOVE 0x00f8: 0x011d, # LATIN SMALL LETTER G WITH CIRCUMFLEX 0x00fd: 0x016d, # LATIN SMALL LETTER U WITH BREVE 0x00fe: 0x015d, # LATIN SMALL LETTER S WITH CIRCUMFLEX 0x00ff: 0x02d9, # DOT ABOVE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# # iso2022_kr.py: Python Unicode Codec for ISO2022_KR # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: iso2022_kr.py,v 1.2 2004/06/28 18:16:03 perky Exp $ # import _codecs_iso2022, codecs codec = _codecs_iso2022.getcodec('iso2022_kr') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python 'unicode-internal' Codec Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs class Codec(codecs.Codec): # Note: Binding these as C functions will result in the class not # converting them to methods. This is intended. encode = codecs.unicode_internal_encode decode = codecs.unicode_internal_decode class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec.encode,Codec.decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP855.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x0452, # CYRILLIC SMALL LETTER DJE 0x0081: 0x0402, # CYRILLIC CAPITAL LETTER DJE 0x0082: 0x0453, # CYRILLIC SMALL LETTER GJE 0x0083: 0x0403, # CYRILLIC CAPITAL LETTER GJE 0x0084: 0x0451, # CYRILLIC SMALL LETTER IO 0x0085: 0x0401, # CYRILLIC CAPITAL LETTER IO 0x0086: 0x0454, # CYRILLIC SMALL LETTER UKRAINIAN IE 0x0087: 0x0404, # CYRILLIC CAPITAL LETTER UKRAINIAN IE 0x0088: 0x0455, # CYRILLIC SMALL LETTER DZE 0x0089: 0x0405, # CYRILLIC CAPITAL LETTER DZE 0x008a: 0x0456, # CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I 0x008b: 0x0406, # CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I 0x008c: 0x0457, # CYRILLIC SMALL LETTER YI 0x008d: 0x0407, # CYRILLIC CAPITAL LETTER YI 0x008e: 0x0458, # CYRILLIC SMALL LETTER JE 0x008f: 0x0408, # CYRILLIC CAPITAL LETTER JE 0x0090: 0x0459, # CYRILLIC SMALL LETTER LJE 0x0091: 0x0409, # CYRILLIC CAPITAL LETTER LJE 0x0092: 0x045a, # CYRILLIC SMALL LETTER NJE 0x0093: 0x040a, # CYRILLIC CAPITAL LETTER NJE 0x0094: 0x045b, # CYRILLIC SMALL LETTER TSHE 0x0095: 0x040b, # CYRILLIC CAPITAL LETTER TSHE 0x0096: 0x045c, # CYRILLIC SMALL LETTER KJE 0x0097: 0x040c, # CYRILLIC CAPITAL LETTER KJE 0x0098: 0x045e, # CYRILLIC SMALL LETTER SHORT U 0x0099: 0x040e, # CYRILLIC CAPITAL LETTER SHORT U 0x009a: 0x045f, # CYRILLIC SMALL LETTER DZHE 0x009b: 0x040f, # CYRILLIC CAPITAL LETTER DZHE 0x009c: 0x044e, # CYRILLIC SMALL LETTER YU 0x009d: 0x042e, # CYRILLIC CAPITAL LETTER YU 0x009e: 0x044a, # CYRILLIC SMALL LETTER HARD SIGN 0x009f: 0x042a, # CYRILLIC CAPITAL LETTER HARD SIGN 0x00a0: 0x0430, # CYRILLIC SMALL LETTER A 0x00a1: 0x0410, # CYRILLIC CAPITAL LETTER A 0x00a2: 0x0431, # CYRILLIC SMALL LETTER BE 0x00a3: 0x0411, # CYRILLIC CAPITAL LETTER BE 0x00a4: 0x0446, # CYRILLIC SMALL LETTER TSE 0x00a5: 0x0426, # CYRILLIC CAPITAL LETTER TSE 0x00a6: 0x0434, # CYRILLIC SMALL LETTER DE 0x00a7: 0x0414, # CYRILLIC CAPITAL LETTER DE 0x00a8: 0x0435, # CYRILLIC SMALL LETTER IE 0x00a9: 0x0415, # CYRILLIC CAPITAL LETTER IE 0x00aa: 0x0444, # CYRILLIC SMALL LETTER EF 0x00ab: 0x0424, # CYRILLIC CAPITAL LETTER EF 0x00ac: 0x0433, # CYRILLIC SMALL LETTER GHE 0x00ad: 0x0413, # CYRILLIC CAPITAL LETTER GHE 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x0445, # CYRILLIC SMALL LETTER HA 0x00b6: 0x0425, # CYRILLIC CAPITAL LETTER HA 0x00b7: 0x0438, # CYRILLIC SMALL LETTER I 0x00b8: 0x0418, # CYRILLIC CAPITAL LETTER I 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x0439, # CYRILLIC SMALL LETTER SHORT I 0x00be: 0x0419, # CYRILLIC CAPITAL LETTER SHORT I 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x043a, # CYRILLIC SMALL LETTER KA 0x00c7: 0x041a, # CYRILLIC CAPITAL LETTER KA 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x00a4, # CURRENCY SIGN 0x00d0: 0x043b, # CYRILLIC SMALL LETTER EL 0x00d1: 0x041b, # CYRILLIC CAPITAL LETTER EL 0x00d2: 0x043c, # CYRILLIC SMALL LETTER EM 0x00d3: 0x041c, # CYRILLIC CAPITAL LETTER EM 0x00d4: 0x043d, # CYRILLIC SMALL LETTER EN 0x00d5: 0x041d, # CYRILLIC CAPITAL LETTER EN 0x00d6: 0x043e, # CYRILLIC SMALL LETTER O 0x00d7: 0x041e, # CYRILLIC CAPITAL LETTER O 0x00d8: 0x043f, # CYRILLIC SMALL LETTER PE 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x041f, # CYRILLIC CAPITAL LETTER PE 0x00de: 0x044f, # CYRILLIC SMALL LETTER YA 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x042f, # CYRILLIC CAPITAL LETTER YA 0x00e1: 0x0440, # CYRILLIC SMALL LETTER ER 0x00e2: 0x0420, # CYRILLIC CAPITAL LETTER ER 0x00e3: 0x0441, # CYRILLIC SMALL LETTER ES 0x00e4: 0x0421, # CYRILLIC CAPITAL LETTER ES 0x00e5: 0x0442, # CYRILLIC SMALL LETTER TE 0x00e6: 0x0422, # CYRILLIC CAPITAL LETTER TE 0x00e7: 0x0443, # CYRILLIC SMALL LETTER U 0x00e8: 0x0423, # CYRILLIC CAPITAL LETTER U 0x00e9: 0x0436, # CYRILLIC SMALL LETTER ZHE 0x00ea: 0x0416, # CYRILLIC CAPITAL LETTER ZHE 0x00eb: 0x0432, # CYRILLIC SMALL LETTER VE 0x00ec: 0x0412, # CYRILLIC CAPITAL LETTER VE 0x00ed: 0x044c, # CYRILLIC SMALL LETTER SOFT SIGN 0x00ee: 0x042c, # CYRILLIC CAPITAL LETTER SOFT SIGN 0x00ef: 0x2116, # NUMERO SIGN 0x00f0: 0x00ad, # SOFT HYPHEN 0x00f1: 0x044b, # CYRILLIC SMALL LETTER YERU 0x00f2: 0x042b, # CYRILLIC CAPITAL LETTER YERU 0x00f3: 0x0437, # CYRILLIC SMALL LETTER ZE 0x00f4: 0x0417, # CYRILLIC CAPITAL LETTER ZE 0x00f5: 0x0448, # CYRILLIC SMALL LETTER SHA 0x00f6: 0x0428, # CYRILLIC CAPITAL LETTER SHA 0x00f7: 0x044d, # CYRILLIC SMALL LETTER E 0x00f8: 0x042d, # CYRILLIC CAPITAL LETTER E 0x00f9: 0x0449, # CYRILLIC SMALL LETTER SHCHA 0x00fa: 0x0429, # CYRILLIC CAPITAL LETTER SHCHA 0x00fb: 0x0447, # CYRILLIC SMALL LETTER CHE 0x00fc: 0x0427, # CYRILLIC CAPITAL LETTER CHE 0x00fd: 0x00a7, # SECTION SIGN 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python 'utf-16-be' Codec Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs encode = codecs.utf_16_be_encode def decode(input, errors='strict'): return codecs.utf_16_be_decode(input, errors, True) class StreamWriter(codecs.StreamWriter): encode = codecs.utf_16_be_encode class StreamReader(codecs.StreamReader): decode = codecs.utf_16_be_decode ### encodings module API def getregentry(): return (encode,decode,StreamReader,StreamWriter)
Python
""" Python 'ascii' Codec Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs class Codec(codecs.Codec): # Note: Binding these as C functions will result in the class not # converting them to methods. This is intended. encode = codecs.ascii_encode decode = codecs.ascii_decode class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass class StreamConverter(StreamWriter,StreamReader): encode = codecs.ascii_decode decode = codecs.ascii_encode ### encodings module API def getregentry(): return (Codec.encode,Codec.decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP1254.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x20ac, # EURO SIGN 0x0081: None, # UNDEFINED 0x0082: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x0083: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x0084: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x0085: 0x2026, # HORIZONTAL ELLIPSIS 0x0086: 0x2020, # DAGGER 0x0087: 0x2021, # DOUBLE DAGGER 0x0088: 0x02c6, # MODIFIER LETTER CIRCUMFLEX ACCENT 0x0089: 0x2030, # PER MILLE SIGN 0x008a: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x008b: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x008c: 0x0152, # LATIN CAPITAL LIGATURE OE 0x008d: None, # UNDEFINED 0x008e: None, # UNDEFINED 0x008f: None, # UNDEFINED 0x0090: None, # UNDEFINED 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x0095: 0x2022, # BULLET 0x0096: 0x2013, # EN DASH 0x0097: 0x2014, # EM DASH 0x0098: 0x02dc, # SMALL TILDE 0x0099: 0x2122, # TRADE MARK SIGN 0x009a: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x009b: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 0x009c: 0x0153, # LATIN SMALL LIGATURE OE 0x009d: None, # UNDEFINED 0x009e: None, # UNDEFINED 0x009f: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS 0x00d0: 0x011e, # LATIN CAPITAL LETTER G WITH BREVE 0x00dd: 0x0130, # LATIN CAPITAL LETTER I WITH DOT ABOVE 0x00de: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x00f0: 0x011f, # LATIN SMALL LETTER G WITH BREVE 0x00fd: 0x0131, # LATIN SMALL LETTER DOTLESS I 0x00fe: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# This module implements the RFCs 3490 (IDNA) and 3491 (Nameprep) import stringprep, unicodedata, re, codecs # IDNA section 3.1 dots = re.compile(u"[\u002E\u3002\uFF0E\uFF61]") # IDNA section 5 ace_prefix = "xn--" uace_prefix = unicode(ace_prefix, "ascii") # This assumes query strings, so AllowUnassigned is true def nameprep(label): # Map newlabel = [] for c in label: if stringprep.in_table_b1(c): # Map to nothing continue newlabel.append(stringprep.map_table_b2(c)) label = u"".join(newlabel) # Normalize label = unicodedata.normalize("NFKC", label) # Prohibit for c in label: if stringprep.in_table_c12(c) or \ stringprep.in_table_c22(c) or \ stringprep.in_table_c3(c) or \ stringprep.in_table_c4(c) or \ stringprep.in_table_c5(c) or \ stringprep.in_table_c6(c) or \ stringprep.in_table_c7(c) or \ stringprep.in_table_c8(c) or \ stringprep.in_table_c9(c): raise UnicodeError, "Invalid character %s" % repr(c) # Check bidi RandAL = map(stringprep.in_table_d1, label) for c in RandAL: if c: # There is a RandAL char in the string. Must perform further # tests: # 1) The characters in section 5.8 MUST be prohibited. # This is table C.8, which was already checked # 2) If a string contains any RandALCat character, the string # MUST NOT contain any LCat character. if filter(stringprep.in_table_d2, label): raise UnicodeError, "Violation of BIDI requirement 2" # 3) If a string contains any RandALCat character, a # RandALCat character MUST be the first character of the # string, and a RandALCat character MUST be the last # character of the string. if not RandAL[0] or not RandAL[-1]: raise UnicodeError, "Violation of BIDI requirement 3" return label def ToASCII(label): try: # Step 1: try ASCII label = label.encode("ascii") except UnicodeError: pass else: # Skip to step 3: UseSTD3ASCIIRules is false, so # Skip to step 8. if 0 < len(label) < 64: return label raise UnicodeError, "label too long" # Step 2: nameprep label = nameprep(label) # Step 3: UseSTD3ASCIIRules is false # Step 4: try ASCII try: label = label.encode("ascii") except UnicodeError: pass else: # Skip to step 8. if 0 < len(label) < 64: return label raise UnicodeError, "label too long" # Step 5: Check ACE prefix if label.startswith(uace_prefix): raise UnicodeError, "Label starts with ACE prefix" # Step 6: Encode with PUNYCODE label = label.encode("punycode") # Step 7: Prepend ACE prefix label = ace_prefix + label # Step 8: Check size if 0 < len(label) < 64: return label raise UnicodeError, "label too long" def ToUnicode(label): # Step 1: Check for ASCII if isinstance(label, str): pure_ascii = True else: try: label = label.encode("ascii") pure_ascii = True except UnicodeError: pure_ascii = False if not pure_ascii: # Step 2: Perform nameprep label = nameprep(label) # It doesn't say this, but apparently, it should be ASCII now try: label = label.encode("ascii") except UnicodeError: raise UnicodeError, "Invalid character in IDN label" # Step 3: Check for ACE prefix if not label.startswith(ace_prefix): return unicode(label, "ascii") # Step 4: Remove ACE prefix label1 = label[len(ace_prefix):] # Step 5: Decode using PUNYCODE result = label1.decode("punycode") # Step 6: Apply ToASCII label2 = ToASCII(result) # Step 7: Compare the result of step 6 with the one of step 3 # label2 will already be in lower case. if label.lower() != label2: raise UnicodeError, ("IDNA does not round-trip", label, label2) # Step 8: return the result of step 5 return result ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): if errors != 'strict': # IDNA is quite clear that implementations must be strict raise UnicodeError, "unsupported error handling "+errors result = [] labels = dots.split(input) if labels and len(labels[-1])==0: trailing_dot = '.' del labels[-1] else: trailing_dot = '' for label in labels: result.append(ToASCII(label)) # Join with U+002E return ".".join(result)+trailing_dot, len(input) def decode(self,input,errors='strict'): if errors != 'strict': raise UnicodeError, "Unsupported error handling "+errors # IDNA allows decoding to operate on Unicode strings, too. if isinstance(input, unicode): labels = dots.split(input) else: # Must be ASCII string input = str(input) unicode(input, "ascii") labels = input.split(".") if labels and len(labels[-1]) == 0: trailing_dot = u'.' del labels[-1] else: trailing_dot = u'' result = [] for label in labels: result.append(ToUnicode(label)) return u".".join(result)+trailing_dot, len(input) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from '8859-14.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: 0x1e02, # LATIN CAPITAL LETTER B WITH DOT ABOVE 0x00a2: 0x1e03, # LATIN SMALL LETTER B WITH DOT ABOVE 0x00a4: 0x010a, # LATIN CAPITAL LETTER C WITH DOT ABOVE 0x00a5: 0x010b, # LATIN SMALL LETTER C WITH DOT ABOVE 0x00a6: 0x1e0a, # LATIN CAPITAL LETTER D WITH DOT ABOVE 0x00a8: 0x1e80, # LATIN CAPITAL LETTER W WITH GRAVE 0x00aa: 0x1e82, # LATIN CAPITAL LETTER W WITH ACUTE 0x00ab: 0x1e0b, # LATIN SMALL LETTER D WITH DOT ABOVE 0x00ac: 0x1ef2, # LATIN CAPITAL LETTER Y WITH GRAVE 0x00af: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS 0x00b0: 0x1e1e, # LATIN CAPITAL LETTER F WITH DOT ABOVE 0x00b1: 0x1e1f, # LATIN SMALL LETTER F WITH DOT ABOVE 0x00b2: 0x0120, # LATIN CAPITAL LETTER G WITH DOT ABOVE 0x00b3: 0x0121, # LATIN SMALL LETTER G WITH DOT ABOVE 0x00b4: 0x1e40, # LATIN CAPITAL LETTER M WITH DOT ABOVE 0x00b5: 0x1e41, # LATIN SMALL LETTER M WITH DOT ABOVE 0x00b7: 0x1e56, # LATIN CAPITAL LETTER P WITH DOT ABOVE 0x00b8: 0x1e81, # LATIN SMALL LETTER W WITH GRAVE 0x00b9: 0x1e57, # LATIN SMALL LETTER P WITH DOT ABOVE 0x00ba: 0x1e83, # LATIN SMALL LETTER W WITH ACUTE 0x00bb: 0x1e60, # LATIN CAPITAL LETTER S WITH DOT ABOVE 0x00bc: 0x1ef3, # LATIN SMALL LETTER Y WITH GRAVE 0x00bd: 0x1e84, # LATIN CAPITAL LETTER W WITH DIAERESIS 0x00be: 0x1e85, # LATIN SMALL LETTER W WITH DIAERESIS 0x00bf: 0x1e61, # LATIN SMALL LETTER S WITH DOT ABOVE 0x00d0: 0x0174, # LATIN CAPITAL LETTER W WITH CIRCUMFLEX 0x00d7: 0x1e6a, # LATIN CAPITAL LETTER T WITH DOT ABOVE 0x00de: 0x0176, # LATIN CAPITAL LETTER Y WITH CIRCUMFLEX 0x00f0: 0x0175, # LATIN SMALL LETTER W WITH CIRCUMFLEX 0x00f7: 0x1e6b, # LATIN SMALL LETTER T WITH DOT ABOVE 0x00fe: 0x0177, # LATIN SMALL LETTER Y WITH CIRCUMFLEX }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP864.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0025: 0x066a, # ARABIC PERCENT SIGN 0x0080: 0x00b0, # DEGREE SIGN 0x0081: 0x00b7, # MIDDLE DOT 0x0082: 0x2219, # BULLET OPERATOR 0x0083: 0x221a, # SQUARE ROOT 0x0084: 0x2592, # MEDIUM SHADE 0x0085: 0x2500, # FORMS LIGHT HORIZONTAL 0x0086: 0x2502, # FORMS LIGHT VERTICAL 0x0087: 0x253c, # FORMS LIGHT VERTICAL AND HORIZONTAL 0x0088: 0x2524, # FORMS LIGHT VERTICAL AND LEFT 0x0089: 0x252c, # FORMS LIGHT DOWN AND HORIZONTAL 0x008a: 0x251c, # FORMS LIGHT VERTICAL AND RIGHT 0x008b: 0x2534, # FORMS LIGHT UP AND HORIZONTAL 0x008c: 0x2510, # FORMS LIGHT DOWN AND LEFT 0x008d: 0x250c, # FORMS LIGHT DOWN AND RIGHT 0x008e: 0x2514, # FORMS LIGHT UP AND RIGHT 0x008f: 0x2518, # FORMS LIGHT UP AND LEFT 0x0090: 0x03b2, # GREEK SMALL BETA 0x0091: 0x221e, # INFINITY 0x0092: 0x03c6, # GREEK SMALL PHI 0x0093: 0x00b1, # PLUS-OR-MINUS SIGN 0x0094: 0x00bd, # FRACTION 1/2 0x0095: 0x00bc, # FRACTION 1/4 0x0096: 0x2248, # ALMOST EQUAL TO 0x0097: 0x00ab, # LEFT POINTING GUILLEMET 0x0098: 0x00bb, # RIGHT POINTING GUILLEMET 0x0099: 0xfef7, # ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE ISOLATED FORM 0x009a: 0xfef8, # ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE FINAL FORM 0x009b: None, # UNDEFINED 0x009c: None, # UNDEFINED 0x009d: 0xfefb, # ARABIC LIGATURE LAM WITH ALEF ISOLATED FORM 0x009e: 0xfefc, # ARABIC LIGATURE LAM WITH ALEF FINAL FORM 0x009f: None, # UNDEFINED 0x00a1: 0x00ad, # SOFT HYPHEN 0x00a2: 0xfe82, # ARABIC LETTER ALEF WITH MADDA ABOVE FINAL FORM 0x00a5: 0xfe84, # ARABIC LETTER ALEF WITH HAMZA ABOVE FINAL FORM 0x00a6: None, # UNDEFINED 0x00a7: None, # UNDEFINED 0x00a8: 0xfe8e, # ARABIC LETTER ALEF FINAL FORM 0x00a9: 0xfe8f, # ARABIC LETTER BEH ISOLATED FORM 0x00aa: 0xfe95, # ARABIC LETTER TEH ISOLATED FORM 0x00ab: 0xfe99, # ARABIC LETTER THEH ISOLATED FORM 0x00ac: 0x060c, # ARABIC COMMA 0x00ad: 0xfe9d, # ARABIC LETTER JEEM ISOLATED FORM 0x00ae: 0xfea1, # ARABIC LETTER HAH ISOLATED FORM 0x00af: 0xfea5, # ARABIC LETTER KHAH ISOLATED FORM 0x00b0: 0x0660, # ARABIC-INDIC DIGIT ZERO 0x00b1: 0x0661, # ARABIC-INDIC DIGIT ONE 0x00b2: 0x0662, # ARABIC-INDIC DIGIT TWO 0x00b3: 0x0663, # ARABIC-INDIC DIGIT THREE 0x00b4: 0x0664, # ARABIC-INDIC DIGIT FOUR 0x00b5: 0x0665, # ARABIC-INDIC DIGIT FIVE 0x00b6: 0x0666, # ARABIC-INDIC DIGIT SIX 0x00b7: 0x0667, # ARABIC-INDIC DIGIT SEVEN 0x00b8: 0x0668, # ARABIC-INDIC DIGIT EIGHT 0x00b9: 0x0669, # ARABIC-INDIC DIGIT NINE 0x00ba: 0xfed1, # ARABIC LETTER FEH ISOLATED FORM 0x00bb: 0x061b, # ARABIC SEMICOLON 0x00bc: 0xfeb1, # ARABIC LETTER SEEN ISOLATED FORM 0x00bd: 0xfeb5, # ARABIC LETTER SHEEN ISOLATED FORM 0x00be: 0xfeb9, # ARABIC LETTER SAD ISOLATED FORM 0x00bf: 0x061f, # ARABIC QUESTION MARK 0x00c0: 0x00a2, # CENT SIGN 0x00c1: 0xfe80, # ARABIC LETTER HAMZA ISOLATED FORM 0x00c2: 0xfe81, # ARABIC LETTER ALEF WITH MADDA ABOVE ISOLATED FORM 0x00c3: 0xfe83, # ARABIC LETTER ALEF WITH HAMZA ABOVE ISOLATED FORM 0x00c4: 0xfe85, # ARABIC LETTER WAW WITH HAMZA ABOVE ISOLATED FORM 0x00c5: 0xfeca, # ARABIC LETTER AIN FINAL FORM 0x00c6: 0xfe8b, # ARABIC LETTER YEH WITH HAMZA ABOVE INITIAL FORM 0x00c7: 0xfe8d, # ARABIC LETTER ALEF ISOLATED FORM 0x00c8: 0xfe91, # ARABIC LETTER BEH INITIAL FORM 0x00c9: 0xfe93, # ARABIC LETTER TEH MARBUTA ISOLATED FORM 0x00ca: 0xfe97, # ARABIC LETTER TEH INITIAL FORM 0x00cb: 0xfe9b, # ARABIC LETTER THEH INITIAL FORM 0x00cc: 0xfe9f, # ARABIC LETTER JEEM INITIAL FORM 0x00cd: 0xfea3, # ARABIC LETTER HAH INITIAL FORM 0x00ce: 0xfea7, # ARABIC LETTER KHAH INITIAL FORM 0x00cf: 0xfea9, # ARABIC LETTER DAL ISOLATED FORM 0x00d0: 0xfeab, # ARABIC LETTER THAL ISOLATED FORM 0x00d1: 0xfead, # ARABIC LETTER REH ISOLATED FORM 0x00d2: 0xfeaf, # ARABIC LETTER ZAIN ISOLATED FORM 0x00d3: 0xfeb3, # ARABIC LETTER SEEN INITIAL FORM 0x00d4: 0xfeb7, # ARABIC LETTER SHEEN INITIAL FORM 0x00d5: 0xfebb, # ARABIC LETTER SAD INITIAL FORM 0x00d6: 0xfebf, # ARABIC LETTER DAD INITIAL FORM 0x00d7: 0xfec1, # ARABIC LETTER TAH ISOLATED FORM 0x00d8: 0xfec5, # ARABIC LETTER ZAH ISOLATED FORM 0x00d9: 0xfecb, # ARABIC LETTER AIN INITIAL FORM 0x00da: 0xfecf, # ARABIC LETTER GHAIN INITIAL FORM 0x00db: 0x00a6, # BROKEN VERTICAL BAR 0x00dc: 0x00ac, # NOT SIGN 0x00dd: 0x00f7, # DIVISION SIGN 0x00de: 0x00d7, # MULTIPLICATION SIGN 0x00df: 0xfec9, # ARABIC LETTER AIN ISOLATED FORM 0x00e0: 0x0640, # ARABIC TATWEEL 0x00e1: 0xfed3, # ARABIC LETTER FEH INITIAL FORM 0x00e2: 0xfed7, # ARABIC LETTER QAF INITIAL FORM 0x00e3: 0xfedb, # ARABIC LETTER KAF INITIAL FORM 0x00e4: 0xfedf, # ARABIC LETTER LAM INITIAL FORM 0x00e5: 0xfee3, # ARABIC LETTER MEEM INITIAL FORM 0x00e6: 0xfee7, # ARABIC LETTER NOON INITIAL FORM 0x00e7: 0xfeeb, # ARABIC LETTER HEH INITIAL FORM 0x00e8: 0xfeed, # ARABIC LETTER WAW ISOLATED FORM 0x00e9: 0xfeef, # ARABIC LETTER ALEF MAKSURA ISOLATED FORM 0x00ea: 0xfef3, # ARABIC LETTER YEH INITIAL FORM 0x00eb: 0xfebd, # ARABIC LETTER DAD ISOLATED FORM 0x00ec: 0xfecc, # ARABIC LETTER AIN MEDIAL FORM 0x00ed: 0xfece, # ARABIC LETTER GHAIN FINAL FORM 0x00ee: 0xfecd, # ARABIC LETTER GHAIN ISOLATED FORM 0x00ef: 0xfee1, # ARABIC LETTER MEEM ISOLATED FORM 0x00f0: 0xfe7d, # ARABIC SHADDA MEDIAL FORM 0x00f1: 0x0651, # ARABIC SHADDAH 0x00f2: 0xfee5, # ARABIC LETTER NOON ISOLATED FORM 0x00f3: 0xfee9, # ARABIC LETTER HEH ISOLATED FORM 0x00f4: 0xfeec, # ARABIC LETTER HEH MEDIAL FORM 0x00f5: 0xfef0, # ARABIC LETTER ALEF MAKSURA FINAL FORM 0x00f6: 0xfef2, # ARABIC LETTER YEH FINAL FORM 0x00f7: 0xfed0, # ARABIC LETTER GHAIN MEDIAL FORM 0x00f8: 0xfed5, # ARABIC LETTER QAF ISOLATED FORM 0x00f9: 0xfef5, # ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM 0x00fa: 0xfef6, # ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE FINAL FORM 0x00fb: 0xfedd, # ARABIC LETTER LAM ISOLATED FORM 0x00fc: 0xfed9, # ARABIC LETTER KAF ISOLATED FORM 0x00fd: 0xfef1, # ARABIC LETTER YEH ISOLATED FORM 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: None, # UNDEFINED }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP866.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x0410, # CYRILLIC CAPITAL LETTER A 0x0081: 0x0411, # CYRILLIC CAPITAL LETTER BE 0x0082: 0x0412, # CYRILLIC CAPITAL LETTER VE 0x0083: 0x0413, # CYRILLIC CAPITAL LETTER GHE 0x0084: 0x0414, # CYRILLIC CAPITAL LETTER DE 0x0085: 0x0415, # CYRILLIC CAPITAL LETTER IE 0x0086: 0x0416, # CYRILLIC CAPITAL LETTER ZHE 0x0087: 0x0417, # CYRILLIC CAPITAL LETTER ZE 0x0088: 0x0418, # CYRILLIC CAPITAL LETTER I 0x0089: 0x0419, # CYRILLIC CAPITAL LETTER SHORT I 0x008a: 0x041a, # CYRILLIC CAPITAL LETTER KA 0x008b: 0x041b, # CYRILLIC CAPITAL LETTER EL 0x008c: 0x041c, # CYRILLIC CAPITAL LETTER EM 0x008d: 0x041d, # CYRILLIC CAPITAL LETTER EN 0x008e: 0x041e, # CYRILLIC CAPITAL LETTER O 0x008f: 0x041f, # CYRILLIC CAPITAL LETTER PE 0x0090: 0x0420, # CYRILLIC CAPITAL LETTER ER 0x0091: 0x0421, # CYRILLIC CAPITAL LETTER ES 0x0092: 0x0422, # CYRILLIC CAPITAL LETTER TE 0x0093: 0x0423, # CYRILLIC CAPITAL LETTER U 0x0094: 0x0424, # CYRILLIC CAPITAL LETTER EF 0x0095: 0x0425, # CYRILLIC CAPITAL LETTER HA 0x0096: 0x0426, # CYRILLIC CAPITAL LETTER TSE 0x0097: 0x0427, # CYRILLIC CAPITAL LETTER CHE 0x0098: 0x0428, # CYRILLIC CAPITAL LETTER SHA 0x0099: 0x0429, # CYRILLIC CAPITAL LETTER SHCHA 0x009a: 0x042a, # CYRILLIC CAPITAL LETTER HARD SIGN 0x009b: 0x042b, # CYRILLIC CAPITAL LETTER YERU 0x009c: 0x042c, # CYRILLIC CAPITAL LETTER SOFT SIGN 0x009d: 0x042d, # CYRILLIC CAPITAL LETTER E 0x009e: 0x042e, # CYRILLIC CAPITAL LETTER YU 0x009f: 0x042f, # CYRILLIC CAPITAL LETTER YA 0x00a0: 0x0430, # CYRILLIC SMALL LETTER A 0x00a1: 0x0431, # CYRILLIC SMALL LETTER BE 0x00a2: 0x0432, # CYRILLIC SMALL LETTER VE 0x00a3: 0x0433, # CYRILLIC SMALL LETTER GHE 0x00a4: 0x0434, # CYRILLIC SMALL LETTER DE 0x00a5: 0x0435, # CYRILLIC SMALL LETTER IE 0x00a6: 0x0436, # CYRILLIC SMALL LETTER ZHE 0x00a7: 0x0437, # CYRILLIC SMALL LETTER ZE 0x00a8: 0x0438, # CYRILLIC SMALL LETTER I 0x00a9: 0x0439, # CYRILLIC SMALL LETTER SHORT I 0x00aa: 0x043a, # CYRILLIC SMALL LETTER KA 0x00ab: 0x043b, # CYRILLIC SMALL LETTER EL 0x00ac: 0x043c, # CYRILLIC SMALL LETTER EM 0x00ad: 0x043d, # CYRILLIC SMALL LETTER EN 0x00ae: 0x043e, # CYRILLIC SMALL LETTER O 0x00af: 0x043f, # CYRILLIC SMALL LETTER PE 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x258c, # LEFT HALF BLOCK 0x00de: 0x2590, # RIGHT HALF BLOCK 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x0440, # CYRILLIC SMALL LETTER ER 0x00e1: 0x0441, # CYRILLIC SMALL LETTER ES 0x00e2: 0x0442, # CYRILLIC SMALL LETTER TE 0x00e3: 0x0443, # CYRILLIC SMALL LETTER U 0x00e4: 0x0444, # CYRILLIC SMALL LETTER EF 0x00e5: 0x0445, # CYRILLIC SMALL LETTER HA 0x00e6: 0x0446, # CYRILLIC SMALL LETTER TSE 0x00e7: 0x0447, # CYRILLIC SMALL LETTER CHE 0x00e8: 0x0448, # CYRILLIC SMALL LETTER SHA 0x00e9: 0x0449, # CYRILLIC SMALL LETTER SHCHA 0x00ea: 0x044a, # CYRILLIC SMALL LETTER HARD SIGN 0x00eb: 0x044b, # CYRILLIC SMALL LETTER YERU 0x00ec: 0x044c, # CYRILLIC SMALL LETTER SOFT SIGN 0x00ed: 0x044d, # CYRILLIC SMALL LETTER E 0x00ee: 0x044e, # CYRILLIC SMALL LETTER YU 0x00ef: 0x044f, # CYRILLIC SMALL LETTER YA 0x00f0: 0x0401, # CYRILLIC CAPITAL LETTER IO 0x00f1: 0x0451, # CYRILLIC SMALL LETTER IO 0x00f2: 0x0404, # CYRILLIC CAPITAL LETTER UKRAINIAN IE 0x00f3: 0x0454, # CYRILLIC SMALL LETTER UKRAINIAN IE 0x00f4: 0x0407, # CYRILLIC CAPITAL LETTER YI 0x00f5: 0x0457, # CYRILLIC SMALL LETTER YI 0x00f6: 0x040e, # CYRILLIC CAPITAL LETTER SHORT U 0x00f7: 0x045e, # CYRILLIC SMALL LETTER SHORT U 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x2219, # BULLET OPERATOR 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x221a, # SQUARE ROOT 0x00fc: 0x2116, # NUMERO SIGN 0x00fd: 0x00a4, # CURRENCY SIGN 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python 'utf-16' Codec Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs, sys ### Codec APIs encode = codecs.utf_16_encode def decode(input, errors='strict'): return codecs.utf_16_decode(input, errors, True) class StreamWriter(codecs.StreamWriter): def __init__(self, stream, errors='strict'): self.bom_written = False codecs.StreamWriter.__init__(self, stream, errors) def encode(self, input, errors='strict'): self.bom_written = True result = codecs.utf_16_encode(input, errors) if sys.byteorder == 'little': self.encode = codecs.utf_16_le_encode else: self.encode = codecs.utf_16_be_encode return result class StreamReader(codecs.StreamReader): def reset(self): codecs.StreamReader.reset(self) try: del self.decode except AttributeError: pass def decode(self, input, errors='strict'): (object, consumed, byteorder) = \ codecs.utf_16_ex_decode(input, errors, 0, False) if byteorder == -1: self.decode = codecs.utf_16_le_decode elif byteorder == 1: self.decode = codecs.utf_16_be_decode elif consumed>=2: raise UnicodeError,"UTF-16 stream does not start with BOM" return (object, consumed) ### encodings module API def getregentry(): return (encode,decode,StreamReader,StreamWriter)
Python
""" Python 'uu_codec' Codec - UU content transfer encoding Unlike most of the other codecs which target Unicode, this codec will return Python string objects for both encode and decode. Written by Marc-Andre Lemburg (mal@lemburg.com). Some details were adapted from uu.py which was written by Lance Ellinghouse and modified by Jack Jansen and Fredrik Lundh. """ import codecs, binascii ### Codec APIs def uu_encode(input,errors='strict',filename='<data>',mode=0666): """ Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' from cStringIO import StringIO from binascii import b2a_uu infile = StringIO(input) outfile = StringIO() read = infile.read write = outfile.write # Encode write('begin %o %s\n' % (mode & 0777, filename)) chunk = read(45) while chunk: write(b2a_uu(chunk)) chunk = read(45) write(' \nend\n') return (outfile.getvalue(), len(input)) def uu_decode(input,errors='strict'): """ Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. Note: filename and file mode information in the input data is ignored. """ assert errors == 'strict' from cStringIO import StringIO from binascii import a2b_uu infile = StringIO(input) outfile = StringIO() readline = infile.readline write = outfile.write # Find start of encoded data while 1: s = readline() if not s: raise ValueError, 'Missing "begin" line in input data' if s[:5] == 'begin': break # Decode while 1: s = readline() if not s or \ s == 'end\n': break try: data = a2b_uu(s) except binascii.Error, v: # Workaround for broken uuencoders by /Fredrik Lundh nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3 data = a2b_uu(s[:nbytes]) #sys.stderr.write("Warning: %s\n" % str(v)) write(data) if not s: raise ValueError, 'Truncated input data' return (outfile.getvalue(), len(input)) class Codec(codecs.Codec): def encode(self,input,errors='strict'): return uu_encode(input,errors) def decode(self,input,errors='strict'): return uu_decode(input,errors) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (uu_encode,uu_decode,StreamReader,StreamWriter)
Python
""" Python 'undefined' Codec This codec will always raise a ValueError exception when being used. It is intended for use by the site.py file to switch off automatic string to Unicode coercion. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): raise UnicodeError, "undefined encoding" def decode(self,input,errors='strict'): raise UnicodeError, "undefined encoding" class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from '8859-10.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x00a2: 0x0112, # LATIN CAPITAL LETTER E WITH MACRON 0x00a3: 0x0122, # LATIN CAPITAL LETTER G WITH CEDILLA 0x00a4: 0x012a, # LATIN CAPITAL LETTER I WITH MACRON 0x00a5: 0x0128, # LATIN CAPITAL LETTER I WITH TILDE 0x00a6: 0x0136, # LATIN CAPITAL LETTER K WITH CEDILLA 0x00a8: 0x013b, # LATIN CAPITAL LETTER L WITH CEDILLA 0x00a9: 0x0110, # LATIN CAPITAL LETTER D WITH STROKE 0x00aa: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00ab: 0x0166, # LATIN CAPITAL LETTER T WITH STROKE 0x00ac: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00ae: 0x016a, # LATIN CAPITAL LETTER U WITH MACRON 0x00af: 0x014a, # LATIN CAPITAL LETTER ENG 0x00b1: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x00b2: 0x0113, # LATIN SMALL LETTER E WITH MACRON 0x00b3: 0x0123, # LATIN SMALL LETTER G WITH CEDILLA 0x00b4: 0x012b, # LATIN SMALL LETTER I WITH MACRON 0x00b5: 0x0129, # LATIN SMALL LETTER I WITH TILDE 0x00b6: 0x0137, # LATIN SMALL LETTER K WITH CEDILLA 0x00b8: 0x013c, # LATIN SMALL LETTER L WITH CEDILLA 0x00b9: 0x0111, # LATIN SMALL LETTER D WITH STROKE 0x00ba: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00bb: 0x0167, # LATIN SMALL LETTER T WITH STROKE 0x00bc: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00bd: 0x2015, # HORIZONTAL BAR 0x00be: 0x016b, # LATIN SMALL LETTER U WITH MACRON 0x00bf: 0x014b, # LATIN SMALL LETTER ENG 0x00c0: 0x0100, # LATIN CAPITAL LETTER A WITH MACRON 0x00c7: 0x012e, # LATIN CAPITAL LETTER I WITH OGONEK 0x00c8: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x00ca: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00cc: 0x0116, # LATIN CAPITAL LETTER E WITH DOT ABOVE 0x00d1: 0x0145, # LATIN CAPITAL LETTER N WITH CEDILLA 0x00d2: 0x014c, # LATIN CAPITAL LETTER O WITH MACRON 0x00d7: 0x0168, # LATIN CAPITAL LETTER U WITH TILDE 0x00d9: 0x0172, # LATIN CAPITAL LETTER U WITH OGONEK 0x00e0: 0x0101, # LATIN SMALL LETTER A WITH MACRON 0x00e7: 0x012f, # LATIN SMALL LETTER I WITH OGONEK 0x00e8: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x00ea: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00ec: 0x0117, # LATIN SMALL LETTER E WITH DOT ABOVE 0x00f1: 0x0146, # LATIN SMALL LETTER N WITH CEDILLA 0x00f2: 0x014d, # LATIN SMALL LETTER O WITH MACRON 0x00f7: 0x0169, # LATIN SMALL LETTER U WITH TILDE 0x00f9: 0x0173, # LATIN SMALL LETTER U WITH OGONEK 0x00ff: 0x0138, # LATIN SMALL LETTER KRA }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP860.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084: 0x00e3, # LATIN SMALL LETTER A WITH TILDE 0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0086: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0089: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x008b: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x008c: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x008d: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE 0x008e: 0x00c3, # LATIN CAPITAL LETTER A WITH TILDE 0x008f: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE 0x0092: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x0094: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x0095: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE 0x0096: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x0098: 0x00cc, # LATIN CAPITAL LETTER I WITH GRAVE 0x0099: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x00a2, # CENT SIGN 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE 0x009e: 0x20a7, # PESETA SIGN 0x009f: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x00a5: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x00a6: 0x00aa, # FEMININE ORDINAL INDICATOR 0x00a7: 0x00ba, # MASCULINE ORDINAL INDICATOR 0x00a8: 0x00bf, # INVERTED QUESTION MARK 0x00a9: 0x00d2, # LATIN CAPITAL LETTER O WITH GRAVE 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x258c, # LEFT HALF BLOCK 0x00de: 0x2590, # RIGHT HALF BLOCK 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S 0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA 0x00e3: 0x03c0, # GREEK SMALL LETTER PI 0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA 0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA 0x00e6: 0x00b5, # MICRO SIGN 0x00e7: 0x03c4, # GREEK SMALL LETTER TAU 0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI 0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA 0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA 0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA 0x00ec: 0x221e, # INFINITY 0x00ed: 0x03c6, # GREEK SMALL LETTER PHI 0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON 0x00ef: 0x2229, # INTERSECTION 0x00f0: 0x2261, # IDENTICAL TO 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO 0x00f3: 0x2264, # LESS-THAN OR EQUAL TO 0x00f4: 0x2320, # TOP HALF INTEGRAL 0x00f5: 0x2321, # BOTTOM HALF INTEGRAL 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x2248, # ALMOST EQUAL TO 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x2219, # BULLET OPERATOR 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x221a, # SQUARE ROOT 0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N 0x00fd: 0x00b2, # SUPERSCRIPT TWO 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from '8859-11.TXT' with gencodec.py. Generated from mapping found in ftp://ftp.unicode.org/Public/MAPPINGS/ISO8859/8859-11.TXT """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: 0x0e01, # THAI CHARACTER KO KAI 0x00a2: 0x0e02, # THAI CHARACTER KHO KHAI 0x00a3: 0x0e03, # THAI CHARACTER KHO KHUAT 0x00a4: 0x0e04, # THAI CHARACTER KHO KHWAI 0x00a5: 0x0e05, # THAI CHARACTER KHO KHON 0x00a6: 0x0e06, # THAI CHARACTER KHO RAKHANG 0x00a7: 0x0e07, # THAI CHARACTER NGO NGU 0x00a8: 0x0e08, # THAI CHARACTER CHO CHAN 0x00a9: 0x0e09, # THAI CHARACTER CHO CHING 0x00aa: 0x0e0a, # THAI CHARACTER CHO CHANG 0x00ab: 0x0e0b, # THAI CHARACTER SO SO 0x00ac: 0x0e0c, # THAI CHARACTER CHO CHOE 0x00ad: 0x0e0d, # THAI CHARACTER YO YING 0x00ae: 0x0e0e, # THAI CHARACTER DO CHADA 0x00af: 0x0e0f, # THAI CHARACTER TO PATAK 0x00b0: 0x0e10, # THAI CHARACTER THO THAN 0x00b1: 0x0e11, # THAI CHARACTER THO NANGMONTHO 0x00b2: 0x0e12, # THAI CHARACTER THO PHUTHAO 0x00b3: 0x0e13, # THAI CHARACTER NO NEN 0x00b4: 0x0e14, # THAI CHARACTER DO DEK 0x00b5: 0x0e15, # THAI CHARACTER TO TAO 0x00b6: 0x0e16, # THAI CHARACTER THO THUNG 0x00b7: 0x0e17, # THAI CHARACTER THO THAHAN 0x00b8: 0x0e18, # THAI CHARACTER THO THONG 0x00b9: 0x0e19, # THAI CHARACTER NO NU 0x00ba: 0x0e1a, # THAI CHARACTER BO BAIMAI 0x00bb: 0x0e1b, # THAI CHARACTER PO PLA 0x00bc: 0x0e1c, # THAI CHARACTER PHO PHUNG 0x00bd: 0x0e1d, # THAI CHARACTER FO FA 0x00be: 0x0e1e, # THAI CHARACTER PHO PHAN 0x00bf: 0x0e1f, # THAI CHARACTER FO FAN 0x00c0: 0x0e20, # THAI CHARACTER PHO SAMPHAO 0x00c1: 0x0e21, # THAI CHARACTER MO MA 0x00c2: 0x0e22, # THAI CHARACTER YO YAK 0x00c3: 0x0e23, # THAI CHARACTER RO RUA 0x00c4: 0x0e24, # THAI CHARACTER RU 0x00c5: 0x0e25, # THAI CHARACTER LO LING 0x00c6: 0x0e26, # THAI CHARACTER LU 0x00c7: 0x0e27, # THAI CHARACTER WO WAEN 0x00c8: 0x0e28, # THAI CHARACTER SO SALA 0x00c9: 0x0e29, # THAI CHARACTER SO RUSI 0x00ca: 0x0e2a, # THAI CHARACTER SO SUA 0x00cb: 0x0e2b, # THAI CHARACTER HO HIP 0x00cc: 0x0e2c, # THAI CHARACTER LO CHULA 0x00cd: 0x0e2d, # THAI CHARACTER O ANG 0x00ce: 0x0e2e, # THAI CHARACTER HO NOKHUK 0x00cf: 0x0e2f, # THAI CHARACTER PAIYANNOI 0x00d0: 0x0e30, # THAI CHARACTER SARA A 0x00d1: 0x0e31, # THAI CHARACTER MAI HAN-AKAT 0x00d2: 0x0e32, # THAI CHARACTER SARA AA 0x00d3: 0x0e33, # THAI CHARACTER SARA AM 0x00d4: 0x0e34, # THAI CHARACTER SARA I 0x00d5: 0x0e35, # THAI CHARACTER SARA II 0x00d6: 0x0e36, # THAI CHARACTER SARA UE 0x00d7: 0x0e37, # THAI CHARACTER SARA UEE 0x00d8: 0x0e38, # THAI CHARACTER SARA U 0x00d9: 0x0e39, # THAI CHARACTER SARA UU 0x00da: 0x0e3a, # THAI CHARACTER PHINTHU 0x00db: None, 0x00dc: None, 0x00dd: None, 0x00de: None, 0x00df: 0x0e3f, # THAI CURRENCY SYMBOL BAHT 0x00e0: 0x0e40, # THAI CHARACTER SARA E 0x00e1: 0x0e41, # THAI CHARACTER SARA AE 0x00e2: 0x0e42, # THAI CHARACTER SARA O 0x00e3: 0x0e43, # THAI CHARACTER SARA AI MAIMUAN 0x00e4: 0x0e44, # THAI CHARACTER SARA AI MAIMALAI 0x00e5: 0x0e45, # THAI CHARACTER LAKKHANGYAO 0x00e6: 0x0e46, # THAI CHARACTER MAIYAMOK 0x00e7: 0x0e47, # THAI CHARACTER MAITAIKHU 0x00e8: 0x0e48, # THAI CHARACTER MAI EK 0x00e9: 0x0e49, # THAI CHARACTER MAI THO 0x00ea: 0x0e4a, # THAI CHARACTER MAI TRI 0x00eb: 0x0e4b, # THAI CHARACTER MAI CHATTAWA 0x00ec: 0x0e4c, # THAI CHARACTER THANTHAKHAT 0x00ed: 0x0e4d, # THAI CHARACTER NIKHAHIT 0x00ee: 0x0e4e, # THAI CHARACTER YAMAKKAN 0x00ef: 0x0e4f, # THAI CHARACTER FONGMAN 0x00f0: 0x0e50, # THAI DIGIT ZERO 0x00f1: 0x0e51, # THAI DIGIT ONE 0x00f2: 0x0e52, # THAI DIGIT TWO 0x00f3: 0x0e53, # THAI DIGIT THREE 0x00f4: 0x0e54, # THAI DIGIT FOUR 0x00f5: 0x0e55, # THAI DIGIT FIVE 0x00f6: 0x0e56, # THAI DIGIT SIX 0x00f7: 0x0e57, # THAI DIGIT SEVEN 0x00f8: 0x0e58, # THAI DIGIT EIGHT 0x00f9: 0x0e59, # THAI DIGIT NINE 0x00fa: 0x0e5a, # THAI CHARACTER ANGKHANKHU 0x00fb: 0x0e5b, # THAI CHARACTER KHOMUT 0x00fc: None, 0x00fd: None, 0x00fe: None, 0x00ff: None, }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python 'hex_codec' Codec - 2-digit hex content transfer encoding Unlike most of the other codecs which target Unicode, this codec will return Python string objects for both encode and decode. Written by Marc-Andre Lemburg (mal@lemburg.com). """ import codecs, binascii ### Codec APIs def hex_encode(input,errors='strict'): """ Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = binascii.b2a_hex(input) return (output, len(input)) def hex_decode(input,errors='strict'): """ Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = binascii.a2b_hex(input) return (output, len(input)) class Codec(codecs.Codec): def encode(self, input,errors='strict'): return hex_encode(input,errors) def decode(self, input,errors='strict'): return hex_decode(input,errors) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (hex_encode,hex_decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP1255.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x20ac, # EURO SIGN 0x0081: None, # UNDEFINED 0x0082: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x0083: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x0084: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x0085: 0x2026, # HORIZONTAL ELLIPSIS 0x0086: 0x2020, # DAGGER 0x0087: 0x2021, # DOUBLE DAGGER 0x0088: 0x02c6, # MODIFIER LETTER CIRCUMFLEX ACCENT 0x0089: 0x2030, # PER MILLE SIGN 0x008a: None, # UNDEFINED 0x008b: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x008c: None, # UNDEFINED 0x008d: None, # UNDEFINED 0x008e: None, # UNDEFINED 0x008f: None, # UNDEFINED 0x0090: None, # UNDEFINED 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x0095: 0x2022, # BULLET 0x0096: 0x2013, # EN DASH 0x0097: 0x2014, # EM DASH 0x0098: 0x02dc, # SMALL TILDE 0x0099: 0x2122, # TRADE MARK SIGN 0x009a: None, # UNDEFINED 0x009b: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 0x009c: None, # UNDEFINED 0x009d: None, # UNDEFINED 0x009e: None, # UNDEFINED 0x009f: None, # UNDEFINED 0x00a4: 0x20aa, # NEW SHEQEL SIGN 0x00aa: 0x00d7, # MULTIPLICATION SIGN 0x00ba: 0x00f7, # DIVISION SIGN 0x00c0: 0x05b0, # HEBREW POINT SHEVA 0x00c1: 0x05b1, # HEBREW POINT HATAF SEGOL 0x00c2: 0x05b2, # HEBREW POINT HATAF PATAH 0x00c3: 0x05b3, # HEBREW POINT HATAF QAMATS 0x00c4: 0x05b4, # HEBREW POINT HIRIQ 0x00c5: 0x05b5, # HEBREW POINT TSERE 0x00c6: 0x05b6, # HEBREW POINT SEGOL 0x00c7: 0x05b7, # HEBREW POINT PATAH 0x00c8: 0x05b8, # HEBREW POINT QAMATS 0x00c9: 0x05b9, # HEBREW POINT HOLAM 0x00ca: None, # UNDEFINED 0x00cb: 0x05bb, # HEBREW POINT QUBUTS 0x00cc: 0x05bc, # HEBREW POINT DAGESH OR MAPIQ 0x00cd: 0x05bd, # HEBREW POINT METEG 0x00ce: 0x05be, # HEBREW PUNCTUATION MAQAF 0x00cf: 0x05bf, # HEBREW POINT RAFE 0x00d0: 0x05c0, # HEBREW PUNCTUATION PASEQ 0x00d1: 0x05c1, # HEBREW POINT SHIN DOT 0x00d2: 0x05c2, # HEBREW POINT SIN DOT 0x00d3: 0x05c3, # HEBREW PUNCTUATION SOF PASUQ 0x00d4: 0x05f0, # HEBREW LIGATURE YIDDISH DOUBLE VAV 0x00d5: 0x05f1, # HEBREW LIGATURE YIDDISH VAV YOD 0x00d6: 0x05f2, # HEBREW LIGATURE YIDDISH DOUBLE YOD 0x00d7: 0x05f3, # HEBREW PUNCTUATION GERESH 0x00d8: 0x05f4, # HEBREW PUNCTUATION GERSHAYIM 0x00d9: None, # UNDEFINED 0x00da: None, # UNDEFINED 0x00db: None, # UNDEFINED 0x00dc: None, # UNDEFINED 0x00dd: None, # UNDEFINED 0x00de: None, # UNDEFINED 0x00df: None, # UNDEFINED 0x00e0: 0x05d0, # HEBREW LETTER ALEF 0x00e1: 0x05d1, # HEBREW LETTER BET 0x00e2: 0x05d2, # HEBREW LETTER GIMEL 0x00e3: 0x05d3, # HEBREW LETTER DALET 0x00e4: 0x05d4, # HEBREW LETTER HE 0x00e5: 0x05d5, # HEBREW LETTER VAV 0x00e6: 0x05d6, # HEBREW LETTER ZAYIN 0x00e7: 0x05d7, # HEBREW LETTER HET 0x00e8: 0x05d8, # HEBREW LETTER TET 0x00e9: 0x05d9, # HEBREW LETTER YOD 0x00ea: 0x05da, # HEBREW LETTER FINAL KAF 0x00eb: 0x05db, # HEBREW LETTER KAF 0x00ec: 0x05dc, # HEBREW LETTER LAMED 0x00ed: 0x05dd, # HEBREW LETTER FINAL MEM 0x00ee: 0x05de, # HEBREW LETTER MEM 0x00ef: 0x05df, # HEBREW LETTER FINAL NUN 0x00f0: 0x05e0, # HEBREW LETTER NUN 0x00f1: 0x05e1, # HEBREW LETTER SAMEKH 0x00f2: 0x05e2, # HEBREW LETTER AYIN 0x00f3: 0x05e3, # HEBREW LETTER FINAL PE 0x00f4: 0x05e4, # HEBREW LETTER PE 0x00f5: 0x05e5, # HEBREW LETTER FINAL TSADI 0x00f6: 0x05e6, # HEBREW LETTER TSADI 0x00f7: 0x05e7, # HEBREW LETTER QOF 0x00f8: 0x05e8, # HEBREW LETTER RESH 0x00f9: 0x05e9, # HEBREW LETTER SHIN 0x00fa: 0x05ea, # HEBREW LETTER TAV 0x00fb: None, # UNDEFINED 0x00fc: None, # UNDEFINED 0x00fd: 0x200e, # LEFT-TO-RIGHT MARK 0x00fe: 0x200f, # RIGHT-TO-LEFT MARK 0x00ff: None, # UNDEFINED }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python