Delete Python
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- Python/DLLs/_asyncio.pydDeleted
- Python/DLLs/_bz2.pydDeleted
- Python/DLLs/_ctypes.pydDeleted
- Python/DLLs/_ctypes_test.pydDeleted
- Python/DLLs/_decimal.pydDeleted
- Python/DLLs/_elementtree.pydDeleted
- Python/DLLs/_hashlib.pydDeleted
- Python/DLLs/_lzma.pydDeleted
- Python/DLLs/_msi.pydDeleted
- Python/DLLs/_multiprocessing.pydDeleted
- Python/DLLs/_overlapped.pydDeleted
- Python/DLLs/_queue.pydDeleted
- Python/DLLs/_socket.pydDeleted
- Python/DLLs/_sqlite3.pydDeleted
- Python/DLLs/_ssl.pydDeleted
- Python/DLLs/_testbuffer.pydDeleted
- Python/DLLs/_testcapi.pydDeleted
- Python/DLLs/_testconsole.pydDeleted
- Python/DLLs/_testimportmultiple.pydDeleted
- Python/DLLs/_testinternalcapi.pydDeleted
- Python/DLLs/_testmultiphase.pydDeleted
- Python/DLLs/_tkinter.pydDeleted
- Python/DLLs/_uuid.pydDeleted
- Python/DLLs/_zoneinfo.pydDeleted
- Python/DLLs/pyexpat.pydDeleted
- Python/DLLs/select.pydDeleted
- Python/DLLs/unicodedata.pydDeleted-3
- Python/DLLs/winsound.pydDeleted
- Python/DLLs/xxlimited.pydDeleted
- Python/DLLs/xxlimited_35.pydDeleted
- Python/Lib/abc.pyDeleted-188
- Python/Lib/aifc.pyDeleted-947
- Python/Lib/antigravity.pyDeleted-17
- Python/Lib/argparse.pyDeleted
- Python/Lib/ast.pyDeleted-1709
- Python/Lib/asynchat.pyDeleted-315
- Python/Lib/asyncore.pyDeleted-649
- Python/Lib/base64.pyDeleted-603
- Python/Lib/bdb.pyDeleted-891
- Python/Lib/binhex.pyDeleted-502
- Python/Lib/bisect.pyDeleted-110
- Python/Lib/bz2.pyDeleted-344
- Python/Lib/cProfile.pyDeleted-190
- Python/Lib/calendar.pyDeleted-759
- Python/Lib/cgi.pyDeleted-1004
- Python/Lib/cgitb.pyDeleted-321
- Python/Lib/chunk.pyDeleted-169
- Python/Lib/cmd.pyDeleted-401
- Python/Lib/code.pyDeleted-315
- Python/Lib/codecs.pyDeleted-1127
123version https://git-lfs.github.com/spec/v1oid sha256:7f6c5e644eade65f0f8762157efb19c5051817bd778d674a9c3b47955ecab3dfsize 1109504123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188# Copyright 2007 Google, Inc. All Rights Reserved.# Licensed to PSF under a Contributor Agreement.
"""Abstract Base Classes (ABCs) according to PEP 3119."""
def abstractmethod(funcobj): """A decorator indicating abstract methods.
Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. abstractmethod() may be used to declare abstract methods for properties and descriptors.
Usage:
class C(metaclass=ABCMeta): @abstractmethod def my_abstract_method(self, ...): ... """ funcobj.__isabstractmethod__ = True return funcobj
class abstractclassmethod(classmethod): """A decorator indicating abstract classmethods.
Deprecated, use 'classmethod' with 'abstractmethod' instead:
class C(ABC): @classmethod @abstractmethod def my_abstract_classmethod(cls, ...): ...
"""
__isabstractmethod__ = True
def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable)
class abstractstaticmethod(staticmethod): """A decorator indicating abstract staticmethods.
Deprecated, use 'staticmethod' with 'abstractmethod' instead:
class C(ABC): @staticmethod @abstractmethod def my_abstract_staticmethod(...): ...
"""
__isabstractmethod__ = True
def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable)
class abstractproperty(property): """A decorator indicating abstract properties.
Deprecated, use 'property' with 'abstractmethod' instead:
class C(ABC): @property @abstractmethod def my_abstract_property(self): ...
"""
__isabstractmethod__ = True
try: from _abc import (get_cache_token, _abc_init, _abc_register, _abc_instancecheck, _abc_subclasscheck, _get_dump, _reset_registry, _reset_caches)except ImportError: from _py_abc import ABCMeta, get_cache_token ABCMeta.__module__ = 'abc'else: class ABCMeta(type): """Metaclass for defining Abstract Base Classes (ABCs).
Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as 'virtual subclasses' -- these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won't show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()). """ def __new__(mcls, name, bases, namespace, **kwargs): cls = super().__new__(mcls, name, bases, namespace, **kwargs) _abc_init(cls) return cls
def register(cls, subclass): """Register a virtual subclass of an ABC.
Returns the subclass, to allow usage as a class decorator. """ return _abc_register(cls, subclass)
def __instancecheck__(cls, instance): """Override for isinstance(instance, cls).""" return _abc_instancecheck(cls, instance)
def __subclasscheck__(cls, subclass): """Override for issubclass(subclass, cls).""" return _abc_subclasscheck(cls, subclass)
def _dump_registry(cls, file=None): """Debug helper to print the ABC registry.""" print(f"Class: {cls.__module__}.{cls.__qualname__}", file=file) print(f"Inv. counter: {get_cache_token()}", file=file) (_abc_registry, _abc_cache, _abc_negative_cache, _abc_negative_cache_version) = _get_dump(cls) print(f"_abc_registry: {_abc_registry!r}", file=file) print(f"_abc_cache: {_abc_cache!r}", file=file) print(f"_abc_negative_cache: {_abc_negative_cache!r}", file=file) print(f"_abc_negative_cache_version: {_abc_negative_cache_version!r}", file=file)
def _abc_registry_clear(cls): """Clear the registry (for debugging or testing).""" _reset_registry(cls)
def _abc_caches_clear(cls): """Clear the caches (for debugging or testing).""" _reset_caches(cls)
def update_abstractmethods(cls): """Recalculate the set of abstract methods of an abstract class.
If a class has had one of its abstract methods implemented after the class was created, the method will not be considered implemented until this function is called. Alternatively, if a new abstract method has been added to the class, it will only be considered an abstract method of the class after this function is called.
This function should be called before any use is made of the class, usually in class decorators that add methods to the subject class.
Returns cls, to allow usage as a class decorator.
If cls is not an instance of ABCMeta, does nothing. """ if not hasattr(cls, '__abstractmethods__'): # We check for __abstractmethods__ here because cls might by a C # implementation or a python implementation (especially during # testing), and we want to handle both cases. return cls
abstracts = set() # Check the existing abstract methods of the parents, keep only the ones # that are not implemented. for scls in cls.__bases__: for name in getattr(scls, '__abstractmethods__', ()): value = getattr(cls, name, None) if getattr(value, "__isabstractmethod__", False): abstracts.add(name) # Also add any other newly added abstract methods. for name, value in cls.__dict__.items(): if getattr(value, "__isabstractmethod__", False): abstracts.add(name) cls.__abstractmethods__ = frozenset(abstracts) return cls
class ABC(metaclass=ABCMeta): """Helper class that provides a standard way to create an ABC using inheritance. """ __slots__ = ()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947"""Stuff to parse AIFF-C and AIFF files.
Unless explicitly stated otherwise, the description below is trueboth for AIFF-C files and AIFF files.
An AIFF-C file has the following structure.
+-----------------+ | FORM | +-----------------+ | <size> | +----+------------+ | | AIFC | | +------------+ | | <chunks> | | | . | | | . | | | . | +----+------------+
An AIFF file has the string "AIFF" instead of "AIFC".
A chunk consists of an identifier (4 bytes) followed by a size (4 bytes,big endian order), followed by the data. The size field does not includethe size of the 8 byte header.
The following chunk types are recognized.
FVER <version number of AIFF-C defining document> (AIFF-C only). MARK <# of markers> (2 bytes) list of markers: <marker ID> (2 bytes, must be > 0) <position> (4 bytes) <marker name> ("pstring") COMM <# of channels> (2 bytes) <# of sound frames> (4 bytes) <size of the samples> (2 bytes) <sampling frequency> (10 bytes, IEEE 80-bit extended floating point) in AIFF-C files only: <compression type> (4 bytes) <human-readable version of compression type> ("pstring") SSND <offset> (4 bytes, not used by this program) <blocksize> (4 bytes, not used by this program) <sound data>
A pstring consists of 1 byte length, a string of characters, and 0 or 1byte pad to make the total length even.
Usage.
Reading AIFF files: f = aifc.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().In some types of audio files, if the setpos() method is 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 AIFF files) getcompname() -- returns human-readable version of compression type ('not compressed' for AIFF files) getparams() -- returns a namedtuple consisting of all of the above in the above order getmarkers() -- get the list of marks in the audio file or None if there are no marks getmark(id) -- get mark with the specified id (raises an error if the mark does not exist) 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(), the position given to setpos() andthe position of marks are all compatible and have nothing to do withthe actual position in the file.The close() method is called automatically when the class instanceis destroyed.
Writing AIFF files: f = aifc.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(), andclose().
This returns an instance of a class with the following public methods: aiff() -- create an AIFF file (AIFF-C default) aifc() -- create an AIFF-C file 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 setmark(id, pos, name) -- add specified mark to the list of marks tell() -- return current position in output file (useful in combination with setmark()) 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 fileYou should set the parameters before the first writeframesraw orwriteframes. 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 tobe patched up.It is best to first set all parameters, perhaps possibly thecompression type, and then write audio frames using writeframesraw.When all frames have been written, either call writeframes(b'') orclose() to patch up the sizes in the header.Marks can be added anytime. If there are any marks, you must callclose() after all frames have been written.The close() method is called automatically when the class instanceis destroyed.
When a file is opened with the extension '.aiff', an AIFF file iswritten, otherwise an AIFF-C file is written. This default can bechanged by calling aiff() or aifc() before the first writeframes orwriteframesraw."""
import structimport builtinsimport warnings
__all__ = ["Error", "open"]
class Error(Exception): pass
_AIFC_version = 0xA2805140 # Version 1 of AIFF-C
def _read_long(file): try: return struct.unpack('>l', file.read(4))[0] except struct.error: raise EOFError from None
def _read_ulong(file): try: return struct.unpack('>L', file.read(4))[0] except struct.error: raise EOFError from None
def _read_short(file): try: return struct.unpack('>h', file.read(2))[0] except struct.error: raise EOFError from None
def _read_ushort(file): try: return struct.unpack('>H', file.read(2))[0] except struct.error: raise EOFError from None
def _read_string(file): length = ord(file.read(1)) if length == 0: data = b'' else: data = file.read(length) if length & 1 == 0: dummy = file.read(1) return data
_HUGE_VAL = 1.79769313486231e+308 # See <limits.h>
def _read_float(f): # 10 bytes expon = _read_short(f) # 2 bytes sign = 1 if expon < 0: sign = -1 expon = expon + 0x8000 himant = _read_ulong(f) # 4 bytes lomant = _read_ulong(f) # 4 bytes if expon == himant == lomant == 0: f = 0.0 elif expon == 0x7FFF: f = _HUGE_VAL else: expon = expon - 16383 f = (himant * 0x100000000 + lomant) * pow(2.0, expon - 63) return sign * f
def _write_short(f, x): f.write(struct.pack('>h', x))
def _write_ushort(f, x): f.write(struct.pack('>H', x))
def _write_long(f, x): f.write(struct.pack('>l', x))
def _write_ulong(f, x): f.write(struct.pack('>L', x))
def _write_string(f, s): if len(s) > 255: raise ValueError("string exceeds maximum pstring length") f.write(struct.pack('B', len(s))) f.write(s) if len(s) & 1 == 0: f.write(b'\x00')
def _write_float(f, x): import math if x < 0: sign = 0x8000 x = x * -1 else: sign = 0 if x == 0: expon = 0 himant = 0 lomant = 0 else: fmant, expon = math.frexp(x) if expon > 16384 or fmant >= 1 or fmant != fmant: # Infinity or NaN expon = sign|0x7FFF himant = 0 lomant = 0 else: # Finite expon = expon + 16382 if expon < 0: # denormalized fmant = math.ldexp(fmant, expon) expon = 0 expon = expon | sign fmant = math.ldexp(fmant, 32) fsmant = math.floor(fmant) himant = int(fsmant) fmant = math.ldexp(fmant - fsmant, 32) fsmant = math.floor(fmant) lomant = int(fsmant) _write_ushort(f, expon) _write_ulong(f, himant) _write_ulong(f, lomant)
from chunk import Chunkfrom collections import namedtuple
_aifc_params = namedtuple('_aifc_params', 'nchannels sampwidth framerate nframes comptype compname')
_aifc_params.nchannels.__doc__ = 'Number of audio channels (1 for mono, 2 for stereo)'_aifc_params.sampwidth.__doc__ = 'Sample width in bytes'_aifc_params.framerate.__doc__ = 'Sampling frequency'_aifc_params.nframes.__doc__ = 'Number of audio frames'_aifc_params.comptype.__doc__ = 'Compression type ("NONE" for AIFF files)'_aifc_params.compname.__doc__ = ("""\A human-readable version of the compression type('not compressed' for AIFF files)""")
class Aifc_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 # _markers -- the marks in the audio file # available through the getmarkers() and getmark() # methods # _soundpos -- the position in the audio stream # available through the tell() method, set through the # setpos() method # # These variables are used internally only: # _version -- the AIFF-C version number # _decomp -- the decompressor from builtin module cl # _comm_chunk_read -- 1 iff the COMM chunk has been read # _aifc -- 1 iff reading an AIFF-C file # _ssnd_seek_needed -- 1 iff positioned correctly in audio # file for readframes() # _ssnd_chunk -- instantiation of a chunk class for the SSND chunk # _framesize -- size of one frame in the file
_file = None # Set here since __del__ checks it
def initfp(self, file): self._version = 0 self._convert = None self._markers = [] self._soundpos = 0 self._file = file chunk = Chunk(file) if chunk.getname() != b'FORM': raise Error('file does not start with FORM id') formdata = chunk.read(4) if formdata == b'AIFF': self._aifc = 0 elif formdata == b'AIFC': self._aifc = 1 else: raise Error('not an AIFF or AIFF-C file') self._comm_chunk_read = 0 self._ssnd_chunk = None while 1: self._ssnd_seek_needed = 1 try: chunk = Chunk(self._file) except EOFError: break chunkname = chunk.getname() if chunkname == b'COMM': self._read_comm_chunk(chunk) self._comm_chunk_read = 1 elif chunkname == b'SSND': self._ssnd_chunk = chunk dummy = chunk.read(8) self._ssnd_seek_needed = 0 elif chunkname == b'FVER': self._version = _read_ulong(chunk) elif chunkname == b'MARK': self._readmark(chunk) chunk.skip() if not self._comm_chunk_read or not self._ssnd_chunk: raise Error('COMM chunk and/or SSND chunk missing')
def __init__(self, f): if isinstance(f, str): file_object = builtins.open(f, 'rb') try: self.initfp(file_object) except: file_object.close() raise else: # assume it is an open file object already self.initfp(f)
def __enter__(self): return self
def __exit__(self, *args): self.close()
# # User visible methods. # def getfp(self): return self._file
def rewind(self): self._ssnd_seek_needed = 1 self._soundpos = 0
def close(self): file = self._file if file is not None: self._file = None file.close()
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 getversion(self):## return self._version
def getparams(self): return _aifc_params(self.getnchannels(), self.getsampwidth(), self.getframerate(), self.getnframes(), self.getcomptype(), self.getcompname())
def getmarkers(self): if len(self._markers) == 0: return None return self._markers
def getmark(self, id): for marker in self._markers: if id == marker[0]: return marker raise Error('marker {0!r} does not exist'.format(id))
def setpos(self, pos): if pos < 0 or pos > self._nframes: raise Error('position not in range') self._soundpos = pos self._ssnd_seek_needed = 1
def readframes(self, nframes): if self._ssnd_seek_needed: self._ssnd_chunk.seek(0) dummy = self._ssnd_chunk.read(8) pos = self._soundpos * self._framesize if pos: self._ssnd_chunk.seek(pos + 8) self._ssnd_seek_needed = 0 if nframes == 0: return b'' data = self._ssnd_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 _alaw2lin(self, data): import audioop return audioop.alaw2lin(data, 2)
def _ulaw2lin(self, data): import audioop return audioop.ulaw2lin(data, 2)
def _adpcm2lin(self, data): import audioop if not hasattr(self, '_adpcmstate'): # first time self._adpcmstate = None data, self._adpcmstate = audioop.adpcm2lin(data, 2, self._adpcmstate) return data
def _read_comm_chunk(self, chunk): self._nchannels = _read_short(chunk) self._nframes = _read_long(chunk) self._sampwidth = (_read_short(chunk) + 7) // 8 self._framerate = int(_read_float(chunk)) if self._sampwidth <= 0: raise Error('bad sample width') if self._nchannels <= 0: raise Error('bad # of channels') self._framesize = self._nchannels * self._sampwidth if self._aifc: #DEBUG: SGI's soundeditor produces a bad size :-( kludge = 0 if chunk.chunksize == 18: kludge = 1 warnings.warn('Warning: bad COMM chunk size') chunk.chunksize = 23 #DEBUG end self._comptype = chunk.read(4) #DEBUG start if kludge: length = ord(chunk.file.read(1)) if length & 1 == 0: length = length + 1 chunk.chunksize = chunk.chunksize + length chunk.file.seek(-1, 1) #DEBUG end self._compname = _read_string(chunk) if self._comptype != b'NONE': if self._comptype == b'G722': self._convert = self._adpcm2lin elif self._comptype in (b'ulaw', b'ULAW'): self._convert = self._ulaw2lin elif self._comptype in (b'alaw', b'ALAW'): self._convert = self._alaw2lin else: raise Error('unsupported compression type') self._sampwidth = 2 else: self._comptype = b'NONE' self._compname = b'not compressed'
def _readmark(self, chunk): nmarkers = _read_short(chunk) # Some files appear to contain invalid counts. # Cope with this by testing for EOF. try: for i in range(nmarkers): id = _read_short(chunk) pos = _read_long(chunk) name = _read_string(chunk) if pos or name: # some files appear to have # dummy markers consisting of # a position 0 and name '' self._markers.append((id, pos, name)) except EOFError: w = ('Warning: MARK chunk contains only %s marker%s instead of %s' % (len(self._markers), '' if len(self._markers) == 1 else 's', nmarkers)) warnings.warn(w)
class Aifc_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 # _aifc -- whether we're writing an AIFF-C file or an AIFF file # set through the aifc() method, reset through the # aiff() method # # These variables are used internally only: # _version -- the AIFF-C version number # _comp -- the compressor from builtin module cl # _nframeswritten -- the number of audio frames actually written # _datalength -- the size of the audio samples written to the header # _datawritten -- the size of the audio samples actually written
_file = None # Set here since __del__ checks it
def __init__(self, f): if isinstance(f, str): file_object = builtins.open(f, 'wb') try: self.initfp(file_object) except: file_object.close() raise
# treat .aiff file extensions as non-compressed audio if f.endswith('.aiff'): self._aifc = 0 else: # assume it is an open file object already self.initfp(f)
def initfp(self, file): self._file = file self._version = _AIFC_version self._comptype = b'NONE' self._compname = b'not compressed' self._convert = None self._nchannels = 0 self._sampwidth = 0 self._framerate = 0 self._nframes = 0 self._nframeswritten = 0 self._datawritten = 0 self._datalength = 0 self._markers = [] self._marklength = 0 self._aifc = 1 # AIFF-C is default
def __del__(self): self.close()
def __enter__(self): return self
def __exit__(self, *args): self.close()
# # User visible methods. # def aiff(self): if self._nframeswritten: raise Error('cannot change parameters after starting to write') self._aifc = 0
def aifc(self): if self._nframeswritten: raise Error('cannot change parameters after starting to write') self._aifc = 1
def setnchannels(self, nchannels): if self._nframeswritten: 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._nframeswritten: 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._nframeswritten: 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._nframeswritten: 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._nframeswritten: raise Error('cannot change parameters after starting to write') if comptype not in (b'NONE', b'ulaw', b'ULAW', b'alaw', b'ALAW', b'G722'): raise Error('unsupported compression type') self._comptype = comptype self._compname = compname
def getcomptype(self): return self._comptype
def getcompname(self): return self._compname
## def setversion(self, version):## if self._nframeswritten:## raise Error, 'cannot change parameters after starting to write'## self._version = version
def setparams(self, params): nchannels, sampwidth, framerate, nframes, comptype, compname = params if self._nframeswritten: raise Error('cannot change parameters after starting to write') if comptype not in (b'NONE', b'ulaw', b'ULAW', b'alaw', b'ALAW', b'G722'): raise Error('unsupported compression type') 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 _aifc_params(self._nchannels, self._sampwidth, self._framerate, self._nframes, self._comptype, self._compname)
def setmark(self, id, pos, name): if id <= 0: raise Error('marker ID must be > 0') if pos < 0: raise Error('marker position must be >= 0') if not isinstance(name, bytes): raise Error('marker name must be bytes') for i in range(len(self._markers)): if id == self._markers[i][0]: self._markers[i] = id, pos, name return self._markers.append((id, pos, name))
def getmark(self, id): for marker in self._markers: if id == marker[0]: return marker raise Error('marker {0!r} does not exist'.format(id))
def getmarkers(self): if len(self._markers) == 0: return None return self._markers
def tell(self): return self._nframeswritten
def writeframesraw(self, data): if not isinstance(data, (bytes, bytearray)): data = memoryview(data).cast('B') self._ensure_header_written(len(data)) nframes = len(data) // (self._sampwidth * self._nchannels) if self._convert: data = self._convert(data) self._file.write(data) self._nframeswritten = self._nframeswritten + nframes self._datawritten = self._datawritten + len(data)
def writeframes(self, data): self.writeframesraw(data) if self._nframeswritten != self._nframes or \ self._datalength != self._datawritten: self._patchheader()
def close(self): if self._file is None: return try: self._ensure_header_written(0) if self._datawritten & 1: # quick pad to even size self._file.write(b'\x00') self._datawritten = self._datawritten + 1 self._writemarkers() if self._nframeswritten != self._nframes or \ self._datalength != self._datawritten or \ self._marklength: self._patchheader() finally: # Prevent ref cycles self._convert = None f = self._file self._file = None f.close()
# # Internal methods. #
def _lin2alaw(self, data): import audioop return audioop.lin2alaw(data, 2)
def _lin2ulaw(self, data): import audioop return audioop.lin2ulaw(data, 2)
def _lin2adpcm(self, data): import audioop if not hasattr(self, '_adpcmstate'): self._adpcmstate = None data, self._adpcmstate = audioop.lin2adpcm(data, 2, self._adpcmstate) return data
def _ensure_header_written(self, datasize): if not self._nframeswritten: if self._comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'): if not self._sampwidth: self._sampwidth = 2 if self._sampwidth != 2: raise Error('sample width must be 2 when compressing ' 'with ulaw/ULAW, alaw/ALAW or G7.22 (ADPCM)') 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 _init_compression(self): if self._comptype == b'G722': self._convert = self._lin2adpcm elif self._comptype in (b'ulaw', b'ULAW'): self._convert = self._lin2ulaw elif self._comptype in (b'alaw', b'ALAW'): self._convert = self._lin2alaw
def _write_header(self, initlength): if self._aifc and self._comptype != b'NONE': self._init_compression() self._file.write(b'FORM') if not self._nframes: self._nframes = initlength // (self._nchannels * self._sampwidth) self._datalength = self._nframes * self._nchannels * self._sampwidth if self._datalength & 1: self._datalength = self._datalength + 1 if self._aifc: if self._comptype in (b'ulaw', b'ULAW', b'alaw', b'ALAW'): self._datalength = self._datalength // 2 if self._datalength & 1: self._datalength = self._datalength + 1 elif self._comptype == b'G722': self._datalength = (self._datalength + 3) // 4 if self._datalength & 1: self._datalength = self._datalength + 1 try: self._form_length_pos = self._file.tell() except (AttributeError, OSError): self._form_length_pos = None commlength = self._write_form_length(self._datalength) if self._aifc: self._file.write(b'AIFC') self._file.write(b'FVER') _write_ulong(self._file, 4) _write_ulong(self._file, self._version) else: self._file.write(b'AIFF') self._file.write(b'COMM') _write_ulong(self._file, commlength) _write_short(self._file, self._nchannels) if self._form_length_pos is not None: self._nframes_pos = self._file.tell() _write_ulong(self._file, self._nframes) if self._comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'): _write_short(self._file, 8) else: _write_short(self._file, self._sampwidth * 8) _write_float(self._file, self._framerate) if self._aifc: self._file.write(self._comptype) _write_string(self._file, self._compname) self._file.write(b'SSND') if self._form_length_pos is not None: self._ssnd_length_pos = self._file.tell() _write_ulong(self._file, self._datalength + 8) _write_ulong(self._file, 0) _write_ulong(self._file, 0)
def _write_form_length(self, datalength): if self._aifc: commlength = 18 + 5 + len(self._compname) if commlength & 1: commlength = commlength + 1 verslength = 12 else: commlength = 18 verslength = 0 _write_ulong(self._file, 4 + verslength + self._marklength + \ 8 + commlength + 16 + datalength) return commlength
def _patchheader(self): curpos = self._file.tell() if self._datawritten & 1: datalength = self._datawritten + 1 self._file.write(b'\x00') else: datalength = self._datawritten if datalength == self._datalength and \ self._nframes == self._nframeswritten and \ self._marklength == 0: self._file.seek(curpos, 0) return self._file.seek(self._form_length_pos, 0) dummy = self._write_form_length(datalength) self._file.seek(self._nframes_pos, 0) _write_ulong(self._file, self._nframeswritten) self._file.seek(self._ssnd_length_pos, 0) _write_ulong(self._file, datalength + 8) self._file.seek(curpos, 0) self._nframes = self._nframeswritten self._datalength = datalength
def _writemarkers(self): if len(self._markers) == 0: return self._file.write(b'MARK') length = 2 for marker in self._markers: id, pos, name = marker length = length + len(name) + 1 + 6 if len(name) & 1 == 0: length = length + 1 _write_ulong(self._file, length) self._marklength = length + 8 _write_short(self._file, len(self._markers)) for marker in self._markers: id, pos, name = marker _write_short(self._file, id) _write_ulong(self._file, pos) _write_string(self._file, name)
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 Aifc_read(f) elif mode in ('w', 'wb'): return Aifc_write(f) else: raise Error("mode must be 'r', 'rb', 'w', or 'wb'")
if __name__ == '__main__': import sys if not sys.argv[1:]: sys.argv.append('/usr/demos/data/audio/bach.aiff') fn = sys.argv[1] with open(fn, 'r') as f: print("Reading", fn) print("nchannels =", f.getnchannels()) print("nframes =", f.getnframes()) print("sampwidth =", f.getsampwidth()) print("framerate =", f.getframerate()) print("comptype =", f.getcomptype()) print("compname =", f.getcompname()) if sys.argv[2:]: gn = sys.argv[2] print("Writing", gn) with open(gn, 'w') as g: g.setparams(f.getparams()) while 1: data = f.readframes(1024) if not data: break g.writeframes(data) print("Done.")1234567891011121314151617
import webbrowserimport hashlib
webbrowser.open("https://xkcd.com/353/")
def geohash(latitude, longitude, datedow): '''Compute geohash() using the Munroe algorithm.
>>> geohash(37.421542, -122.085589, b'2005-05-26-10458.68') 37.857713 -122.544543
''' # https://xkcd.com/426/ h = hashlib.md5(datedow, usedforsecurity=False).hexdigest() p, q = [('%f' % float.fromhex('0.' + x)) for x in (h[:16], h[16:32])] print('%d%s %d%s' % (latitude, p[1:], longitude, q[1:]))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709""" ast ~~~
The `ast` module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like and allows modifications of it.
An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as a flag to the `compile()` builtin function or by using the `parse()` function from this module. The result will be a tree of objects whose classes all inherit from `ast.AST`.
A modified abstract syntax tree can be compiled into a Python code object using the built-in `compile()` function.
Additionally various helper functions are provided that make working with the trees simpler. The main intention of the helper functions and this module in general is to provide an easy to use interface for libraries that work tightly with the python syntax (template engines for example).
:copyright: Copyright 2008 by Armin Ronacher. :license: Python License."""import sysfrom _ast import *from contextlib import contextmanager, nullcontextfrom enum import IntEnum, auto
def parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None): """ Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). Pass type_comments=True to get back type comments where the syntax allows. """ flags = PyCF_ONLY_AST if type_comments: flags |= PyCF_TYPE_COMMENTS if isinstance(feature_version, tuple): major, minor = feature_version # Should be a 2-tuple. assert major == 3 feature_version = minor elif feature_version is None: feature_version = -1 # Else it should be an int giving the minor version for 3.x. return compile(source, filename, mode, flags, _feature_version=feature_version)
def literal_eval(node_or_string): """ Evaluate an expression node or a string containing only a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
Caution: A complex expression can overflow the C stack and cause a crash. """ if isinstance(node_or_string, str): node_or_string = parse(node_or_string.lstrip(" \t"), mode='eval') if isinstance(node_or_string, Expression): node_or_string = node_or_string.body def _raise_malformed_node(node): msg = "malformed node or string" if lno := getattr(node, 'lineno', None): msg += f' on line {lno}' raise ValueError(msg + f': {node!r}') def _convert_num(node): if not isinstance(node, Constant) or type(node.value) not in (int, float, complex): _raise_malformed_node(node) return node.value def _convert_signed_num(node): if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)): operand = _convert_num(node.operand) if isinstance(node.op, UAdd): return + operand else: return - operand return _convert_num(node) def _convert(node): if isinstance(node, Constant): return node.value elif isinstance(node, Tuple): return tuple(map(_convert, node.elts)) elif isinstance(node, List): return list(map(_convert, node.elts)) elif isinstance(node, Set): return set(map(_convert, node.elts)) elif (isinstance(node, Call) and isinstance(node.func, Name) and node.func.id == 'set' and node.args == node.keywords == []): return set() elif isinstance(node, Dict): if len(node.keys) != len(node.values): _raise_malformed_node(node) return dict(zip(map(_convert, node.keys), map(_convert, node.values))) elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)): left = _convert_signed_num(node.left) right = _convert_num(node.right) if isinstance(left, (int, float)) and isinstance(right, complex): if isinstance(node.op, Add): return left + right else: return left - right return _convert_signed_num(node) return _convert(node_or_string)
def dump(node, annotate_fields=True, include_attributes=False, *, indent=None): """ Return a formatted dump of the tree in node. This is mainly useful for debugging purposes. If annotate_fields is true (by default), the returned string will show the names and the values for fields. If annotate_fields is false, the result string will be more compact by omitting unambiguous field names. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, include_attributes can be set to true. If indent is a non-negative integer or string, then the tree will be pretty-printed with that indent level. None (the default) selects the single line representation. """ def _format(node, level=0): if indent is not None: level += 1 prefix = '\n' + indent * level sep = ',\n' + indent * level else: prefix = '' sep = ', ' if isinstance(node, AST): cls = type(node) args = [] allsimple = True keywords = annotate_fields for name in node._fields: try: value = getattr(node, name) except AttributeError: keywords = True continue if value is None and getattr(cls, name, ...) is None: keywords = True continue value, simple = _format(value, level) allsimple = allsimple and simple if keywords: args.append('%s=%s' % (name, value)) else: args.append(value) if include_attributes and node._attributes: for name in node._attributes: try: value = getattr(node, name) except AttributeError: continue if value is None and getattr(cls, name, ...) is None: continue value, simple = _format(value, level) allsimple = allsimple and simple args.append('%s=%s' % (name, value)) if allsimple and len(args) <= 3: return '%s(%s)' % (node.__class__.__name__, ', '.join(args)), not args return '%s(%s%s)' % (node.__class__.__name__, prefix, sep.join(args)), False elif isinstance(node, list): if not node: return '[]', True return '[%s%s]' % (prefix, sep.join(_format(x, level)[0] for x in node)), False return repr(node), True
if not isinstance(node, AST): raise TypeError('expected AST, got %r' % node.__class__.__name__) if indent is not None and not isinstance(indent, str): indent = ' ' * indent return _format(node)[0]
def copy_location(new_node, old_node): """ Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset` attributes) from *old_node* to *new_node* if possible, and return *new_node*. """ for attr in 'lineno', 'col_offset', 'end_lineno', 'end_col_offset': if attr in old_node._attributes and attr in new_node._attributes: value = getattr(old_node, attr, None) # end_lineno and end_col_offset are optional attributes, and they # should be copied whether the value is None or not. if value is not None or ( hasattr(old_node, attr) and attr.startswith("end_") ): setattr(new_node, attr, value) return new_node
def fix_missing_locations(node): """ When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at *node*. """ def _fix(node, lineno, col_offset, end_lineno, end_col_offset): if 'lineno' in node._attributes: if not hasattr(node, 'lineno'): node.lineno = lineno else: lineno = node.lineno if 'end_lineno' in node._attributes: if getattr(node, 'end_lineno', None) is None: node.end_lineno = end_lineno else: end_lineno = node.end_lineno if 'col_offset' in node._attributes: if not hasattr(node, 'col_offset'): node.col_offset = col_offset else: col_offset = node.col_offset if 'end_col_offset' in node._attributes: if getattr(node, 'end_col_offset', None) is None: node.end_col_offset = end_col_offset else: end_col_offset = node.end_col_offset for child in iter_child_nodes(node): _fix(child, lineno, col_offset, end_lineno, end_col_offset) _fix(node, 1, 0, 1, 0) return node
def increment_lineno(node, n=1): """ Increment the line number and end line number of each node in the tree starting at *node* by *n*. This is useful to "move code" to a different location in a file. """ for child in walk(node): # TypeIgnore is a special case where lineno is not an attribute # but rather a field of the node itself. if isinstance(child, TypeIgnore): child.lineno = getattr(child, 'lineno', 0) + n continue
if 'lineno' in child._attributes: child.lineno = getattr(child, 'lineno', 0) + n if ( "end_lineno" in child._attributes and (end_lineno := getattr(child, "end_lineno", 0)) is not None ): child.end_lineno = end_lineno + n return node
def iter_fields(node): """ Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*. """ for field in node._fields: try: yield field, getattr(node, field) except AttributeError: pass
def iter_child_nodes(node): """ Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes. """ for name, field in iter_fields(node): if isinstance(field, AST): yield field elif isinstance(field, list): for item in field: if isinstance(item, AST): yield item
def get_docstring(node, clean=True): """ Return the docstring for the given node or None if no docstring can be found. If the node provided does not have docstrings a TypeError will be raised.
If *clean* is `True`, all tabs are expanded to spaces and any whitespace that can be uniformly removed from the second line onwards is removed. """ if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)): raise TypeError("%r can't have docstrings" % node.__class__.__name__) if not(node.body and isinstance(node.body[0], Expr)): return None node = node.body[0].value if isinstance(node, Str): text = node.s elif isinstance(node, Constant) and isinstance(node.value, str): text = node.value else: return None if clean: import inspect text = inspect.cleandoc(text) return text
def _splitlines_no_ff(source): """Split a string into lines ignoring form feed and other chars.
This mimics how the Python parser splits source code. """ idx = 0 lines = [] next_line = '' while idx < len(source): c = source[idx] next_line += c idx += 1 # Keep \r\n together if c == '\r' and idx < len(source) and source[idx] == '\n': next_line += '\n' idx += 1 if c in '\r\n': lines.append(next_line) next_line = ''
if next_line: lines.append(next_line) return lines
def _pad_whitespace(source): r"""Replace all chars except '\f\t' in a line with spaces.""" result = '' for c in source: if c in '\f\t': result += c else: result += ' ' return result
def get_source_segment(source, node, *, padded=False): """Get source code segment of the *source* that generated *node*.
If some location information (`lineno`, `end_lineno`, `col_offset`, or `end_col_offset`) is missing, return None.
If *padded* is `True`, the first line of a multi-line statement will be padded with spaces to match its original position. """ try: if node.end_lineno is None or node.end_col_offset is None: return None lineno = node.lineno - 1 end_lineno = node.end_lineno - 1 col_offset = node.col_offset end_col_offset = node.end_col_offset except AttributeError: return None
lines = _splitlines_no_ff(source) if end_lineno == lineno: return lines[lineno].encode()[col_offset:end_col_offset].decode()
if padded: padding = _pad_whitespace(lines[lineno].encode()[:col_offset].decode()) else: padding = ''
first = padding + lines[lineno].encode()[col_offset:].decode() last = lines[end_lineno].encode()[:end_col_offset].decode() lines = lines[lineno+1:end_lineno]
lines.insert(0, first) lines.append(last) return ''.join(lines)
def walk(node): """ Recursively yield all descendant nodes in the tree starting at *node* (including *node* itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context. """ from collections import deque todo = deque([node]) while todo: node = todo.popleft() todo.extend(iter_child_nodes(node)) yield node
class NodeVisitor(object): """ A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the `visit` method.
This class is meant to be subclassed, with the subclass adding visitor methods.
Per default the visitor functions for the nodes are ``'visit_'`` + class name of the node. So a `TryFinally` node visit function would be `visit_TryFinally`. This behavior can be changed by overriding the `visit` method. If no visitor function exists for a node (return value `None`) the `generic_visit` visitor is used instead.
Don't use the `NodeVisitor` if you want to apply changes to nodes during traversing. For this a special visitor exists (`NodeTransformer`) that allows modifications. """
def visit(self, node): """Visit a node.""" method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self.generic_visit) return visitor(node)
def generic_visit(self, node): """Called if no explicit visitor function exists for a node.""" for field, value in iter_fields(node): if isinstance(value, list): for item in value: if isinstance(item, AST): self.visit(item) elif isinstance(value, AST): self.visit(value)
def visit_Constant(self, node): value = node.value type_name = _const_node_type_names.get(type(value)) if type_name is None: for cls, name in _const_node_type_names.items(): if isinstance(value, cls): type_name = name break if type_name is not None: method = 'visit_' + type_name try: visitor = getattr(self, method) except AttributeError: pass else: import warnings warnings.warn(f"{method} is deprecated; add visit_Constant", DeprecationWarning, 2) return visitor(node) return self.generic_visit(node)
class NodeTransformer(NodeVisitor): """ A :class:`NodeVisitor` subclass that walks the abstract syntax tree and allows modification of nodes.
The `NodeTransformer` will walk the AST and use the return value of the visitor methods to replace or remove the old node. If the return value of the visitor method is ``None``, the node will be removed from its location, otherwise it is replaced with the return value. The return value may be the original node in which case no replacement takes place.
Here is an example transformer that rewrites all occurrences of name lookups (``foo``) to ``data['foo']``::
class RewriteName(NodeTransformer):
def visit_Name(self, node): return Subscript( value=Name(id='data', ctx=Load()), slice=Constant(value=node.id), ctx=node.ctx )
Keep in mind that if the node you're operating on has child nodes you must either transform the child nodes yourself or call the :meth:`generic_visit` method for the node first.
For nodes that were part of a collection of statements (that applies to all statement nodes), the visitor may also return a list of nodes rather than just a single node.
Usually you use the transformer like this::
node = YourTransformer().visit(node) """
def generic_visit(self, node): for field, old_value in iter_fields(node): if isinstance(old_value, list): new_values = [] for value in old_value: if isinstance(value, AST): value = self.visit(value) if value is None: continue elif not isinstance(value, AST): new_values.extend(value) continue new_values.append(value) old_value[:] = new_values elif isinstance(old_value, AST): new_node = self.visit(old_value) if new_node is None: delattr(node, field) else: setattr(node, field, new_node) return node
# If the ast module is loaded more than once, only add deprecated methods onceif not hasattr(Constant, 'n'): # The following code is for backward compatibility. # It will be removed in future.
def _getter(self): """Deprecated. Use value instead.""" return self.value
def _setter(self, value): self.value = value
Constant.n = property(_getter, _setter) Constant.s = property(_getter, _setter)
class _ABC(type):
def __init__(cls, *args): cls.__doc__ = """Deprecated AST node class. Use ast.Constant instead"""
def __instancecheck__(cls, inst): if not isinstance(inst, Constant): return False if cls in _const_types: try: value = inst.value except AttributeError: return False else: return ( isinstance(value, _const_types[cls]) and not isinstance(value, _const_types_not.get(cls, ())) ) return type.__instancecheck__(cls, inst)
def _new(cls, *args, **kwargs): for key in kwargs: if key not in cls._fields: # arbitrary keyword arguments are accepted continue pos = cls._fields.index(key) if pos < len(args): raise TypeError(f"{cls.__name__} got multiple values for argument {key!r}") if cls in _const_types: return Constant(*args, **kwargs) return Constant.__new__(cls, *args, **kwargs)
class Num(Constant, metaclass=_ABC): _fields = ('n',) __new__ = _new
class Str(Constant, metaclass=_ABC): _fields = ('s',) __new__ = _new
class Bytes(Constant, metaclass=_ABC): _fields = ('s',) __new__ = _new
class NameConstant(Constant, metaclass=_ABC): __new__ = _new
class Ellipsis(Constant, metaclass=_ABC): _fields = ()
def __new__(cls, *args, **kwargs): if cls is Ellipsis: return Constant(..., *args, **kwargs) return Constant.__new__(cls, *args, **kwargs)
_const_types = { Num: (int, float, complex), Str: (str,), Bytes: (bytes,), NameConstant: (type(None), bool), Ellipsis: (type(...),),}_const_types_not = { Num: (bool,),}
_const_node_type_names = { bool: 'NameConstant', # should be before int type(None): 'NameConstant', int: 'Num', float: 'Num', complex: 'Num', str: 'Str', bytes: 'Bytes', type(...): 'Ellipsis',}
class slice(AST): """Deprecated AST node class."""
class Index(slice): """Deprecated AST node class. Use the index value directly instead.""" def __new__(cls, value, **kwargs): return value
class ExtSlice(slice): """Deprecated AST node class. Use ast.Tuple instead.""" def __new__(cls, dims=(), **kwargs): return Tuple(list(dims), Load(), **kwargs)
# If the ast module is loaded more than once, only add deprecated methods onceif not hasattr(Tuple, 'dims'): # The following code is for backward compatibility. # It will be removed in future.
def _dims_getter(self): """Deprecated. Use elts instead.""" return self.elts
def _dims_setter(self, value): self.elts = value
Tuple.dims = property(_dims_getter, _dims_setter)
class Suite(mod): """Deprecated AST node class. Unused in Python 3."""
class AugLoad(expr_context): """Deprecated AST node class. Unused in Python 3."""
class AugStore(expr_context): """Deprecated AST node class. Unused in Python 3."""
class Param(expr_context): """Deprecated AST node class. Unused in Python 3."""
# Large float and imaginary literals get turned into infinities in the AST.# We unparse those infinities to INFSTR._INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1)
class _Precedence(IntEnum): """Precedence table that originated from python grammar."""
TUPLE = auto() YIELD = auto() # 'yield', 'yield from' TEST = auto() # 'if'-'else', 'lambda' OR = auto() # 'or' AND = auto() # 'and' NOT = auto() # 'not' CMP = auto() # '<', '>', '==', '>=', '<=', '!=', # 'in', 'not in', 'is', 'is not' EXPR = auto() BOR = EXPR # '|' BXOR = auto() # '^' BAND = auto() # '&' SHIFT = auto() # '<<', '>>' ARITH = auto() # '+', '-' TERM = auto() # '*', '@', '/', '%', '//' FACTOR = auto() # unary '+', '-', '~' POWER = auto() # '**' AWAIT = auto() # 'await' ATOM = auto()
def next(self): try: return self.__class__(self + 1) except ValueError: return self
_SINGLE_QUOTES = ("'", '"')_MULTI_QUOTES = ('"""', "'''")_ALL_QUOTES = (*_SINGLE_QUOTES, *_MULTI_QUOTES)
class _Unparser(NodeVisitor): """Methods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarded."""
def __init__(self, *, _avoid_backslashes=False): self._source = [] self._buffer = [] self._precedences = {} self._type_ignores = {} self._indent = 0 self._avoid_backslashes = _avoid_backslashes
def interleave(self, inter, f, seq): """Call f on each item in seq, calling inter() in between.""" seq = iter(seq) try: f(next(seq)) except StopIteration: pass else: for x in seq: inter() f(x)
def items_view(self, traverser, items): """Traverse and separate the given *items* with a comma and append it to the buffer. If *items* is a single item sequence, a trailing comma will be added.""" if len(items) == 1: traverser(items[0]) self.write(",") else: self.interleave(lambda: self.write(", "), traverser, items)
def maybe_newline(self): """Adds a newline if it isn't the start of generated source""" if self._source: self.write("\n")
def fill(self, text=""): """Indent a piece of text and append it, according to the current indentation level""" self.maybe_newline() self.write(" " * self._indent + text)
def write(self, text): """Append a piece of text""" self._source.append(text)
def buffer_writer(self, text): self._buffer.append(text)
@property def buffer(self): value = "".join(self._buffer) self._buffer.clear() return value
@contextmanager def block(self, *, extra = None): """A context manager for preparing the source for blocks. It adds the character':', increases the indentation on enter and decreases the indentation on exit. If *extra* is given, it will be directly appended after the colon character. """ self.write(":") if extra: self.write(extra) self._indent += 1 yield self._indent -= 1
@contextmanager def delimit(self, start, end): """A context manager for preparing the source for expressions. It adds *start* to the buffer and enters, after exit it adds *end*."""
self.write(start) yield self.write(end)
def delimit_if(self, start, end, condition): if condition: return self.delimit(start, end) else: return nullcontext()
def require_parens(self, precedence, node): """Shortcut to adding precedence related parens""" return self.delimit_if("(", ")", self.get_precedence(node) > precedence)
def get_precedence(self, node): return self._precedences.get(node, _Precedence.TEST)
def set_precedence(self, precedence, *nodes): for node in nodes: self._precedences[node] = precedence
def get_raw_docstring(self, node): """If a docstring node is found in the body of the *node* parameter, return that docstring node, None otherwise.
Logic mirrored from ``_PyAST_GetDocString``.""" if not isinstance( node, (AsyncFunctionDef, FunctionDef, ClassDef, Module) ) or len(node.body) < 1: return None node = node.body[0] if not isinstance(node, Expr): return None node = node.value if isinstance(node, Constant) and isinstance(node.value, str): return node
def get_type_comment(self, node): comment = self._type_ignores.get(node.lineno) or node.type_comment if comment is not None: return f" # type: {comment}"
def traverse(self, node): if isinstance(node, list): for item in node: self.traverse(item) else: super().visit(node)
# Note: as visit() resets the output text, do NOT rely on # NodeVisitor.generic_visit to handle any nodes (as it calls back in to # the subclass visit() method, which resets self._source to an empty list) def visit(self, node): """Outputs a source code string that, if converted back to an ast (using ast.parse) will generate an AST equivalent to *node*""" self._source = [] self.traverse(node) return "".join(self._source)
def _write_docstring_and_traverse_body(self, node): if (docstring := self.get_raw_docstring(node)): self._write_docstring(docstring) self.traverse(node.body[1:]) else: self.traverse(node.body)
def visit_Module(self, node): self._type_ignores = { ignore.lineno: f"ignore{ignore.tag}" for ignore in node.type_ignores } self._write_docstring_and_traverse_body(node) self._type_ignores.clear()
def visit_FunctionType(self, node): with self.delimit("(", ")"): self.interleave( lambda: self.write(", "), self.traverse, node.argtypes )
self.write(" -> ") self.traverse(node.returns)
def visit_Expr(self, node): self.fill() self.set_precedence(_Precedence.YIELD, node.value) self.traverse(node.value)
def visit_NamedExpr(self, node): with self.require_parens(_Precedence.TUPLE, node): self.set_precedence(_Precedence.ATOM, node.target, node.value) self.traverse(node.target) self.write(" := ") self.traverse(node.value)
def visit_Import(self, node): self.fill("import ") self.interleave(lambda: self.write(", "), self.traverse, node.names)
def visit_ImportFrom(self, node): self.fill("from ") self.write("." * (node.level or 0)) if node.module: self.write(node.module) self.write(" import ") self.interleave(lambda: self.write(", "), self.traverse, node.names)
def visit_Assign(self, node): self.fill() for target in node.targets: self.traverse(target) self.write(" = ") self.traverse(node.value) if type_comment := self.get_type_comment(node): self.write(type_comment)
def visit_AugAssign(self, node): self.fill() self.traverse(node.target) self.write(" " + self.binop[node.op.__class__.__name__] + "= ") self.traverse(node.value)
def visit_AnnAssign(self, node): self.fill() with self.delimit_if("(", ")", not node.simple and isinstance(node.target, Name)): self.traverse(node.target) self.write(": ") self.traverse(node.annotation) if node.value: self.write(" = ") self.traverse(node.value)
def visit_Return(self, node): self.fill("return") if node.value: self.write(" ") self.traverse(node.value)
def visit_Pass(self, node): self.fill("pass")
def visit_Break(self, node): self.fill("break")
def visit_Continue(self, node): self.fill("continue")
def visit_Delete(self, node): self.fill("del ") self.interleave(lambda: self.write(", "), self.traverse, node.targets)
def visit_Assert(self, node): self.fill("assert ") self.traverse(node.test) if node.msg: self.write(", ") self.traverse(node.msg)
def visit_Global(self, node): self.fill("global ") self.interleave(lambda: self.write(", "), self.write, node.names)
def visit_Nonlocal(self, node): self.fill("nonlocal ") self.interleave(lambda: self.write(", "), self.write, node.names)
def visit_Await(self, node): with self.require_parens(_Precedence.AWAIT, node): self.write("await") if node.value: self.write(" ") self.set_precedence(_Precedence.ATOM, node.value) self.traverse(node.value)
def visit_Yield(self, node): with self.require_parens(_Precedence.YIELD, node): self.write("yield") if node.value: self.write(" ") self.set_precedence(_Precedence.ATOM, node.value) self.traverse(node.value)
def visit_YieldFrom(self, node): with self.require_parens(_Precedence.YIELD, node): self.write("yield from ") if not node.value: raise ValueError("Node can't be used without a value attribute.") self.set_precedence(_Precedence.ATOM, node.value) self.traverse(node.value)
def visit_Raise(self, node): self.fill("raise") if not node.exc: if node.cause: raise ValueError(f"Node can't use cause without an exception.") return self.write(" ") self.traverse(node.exc) if node.cause: self.write(" from ") self.traverse(node.cause)
def visit_Try(self, node): self.fill("try") with self.block(): self.traverse(node.body) for ex in node.handlers: self.traverse(ex) if node.orelse: self.fill("else") with self.block(): self.traverse(node.orelse) if node.finalbody: self.fill("finally") with self.block(): self.traverse(node.finalbody)
def visit_ExceptHandler(self, node): self.fill("except") if node.type: self.write(" ") self.traverse(node.type) if node.name: self.write(" as ") self.write(node.name) with self.block(): self.traverse(node.body)
def visit_ClassDef(self, node): self.maybe_newline() for deco in node.decorator_list: self.fill("@") self.traverse(deco) self.fill("class " + node.name) with self.delimit_if("(", ")", condition = node.bases or node.keywords): comma = False for e in node.bases: if comma: self.write(", ") else: comma = True self.traverse(e) for e in node.keywords: if comma: self.write(", ") else: comma = True self.traverse(e)
with self.block(): self._write_docstring_and_traverse_body(node)
def visit_FunctionDef(self, node): self._function_helper(node, "def")
def visit_AsyncFunctionDef(self, node): self._function_helper(node, "async def")
def _function_helper(self, node, fill_suffix): self.maybe_newline() for deco in node.decorator_list: self.fill("@") self.traverse(deco) def_str = fill_suffix + " " + node.name self.fill(def_str) with self.delimit("(", ")"): self.traverse(node.args) if node.returns: self.write(" -> ") self.traverse(node.returns) with self.block(extra=self.get_type_comment(node)): self._write_docstring_and_traverse_body(node)
def visit_For(self, node): self._for_helper("for ", node)
def visit_AsyncFor(self, node): self._for_helper("async for ", node)
def _for_helper(self, fill, node): self.fill(fill) self.traverse(node.target) self.write(" in ") self.traverse(node.iter) with self.block(extra=self.get_type_comment(node)): self.traverse(node.body) if node.orelse: self.fill("else") with self.block(): self.traverse(node.orelse)
def visit_If(self, node): self.fill("if ") self.traverse(node.test) with self.block(): self.traverse(node.body) # collapse nested ifs into equivalent elifs. while node.orelse and len(node.orelse) == 1 and isinstance(node.orelse[0], If): node = node.orelse[0] self.fill("elif ") self.traverse(node.test) with self.block(): self.traverse(node.body) # final else if node.orelse: self.fill("else") with self.block(): self.traverse(node.orelse)
def visit_While(self, node): self.fill("while ") self.traverse(node.test) with self.block(): self.traverse(node.body) if node.orelse: self.fill("else") with self.block(): self.traverse(node.orelse)
def visit_With(self, node): self.fill("with ") self.interleave(lambda: self.write(", "), self.traverse, node.items) with self.block(extra=self.get_type_comment(node)): self.traverse(node.body)
def visit_AsyncWith(self, node): self.fill("async with ") self.interleave(lambda: self.write(", "), self.traverse, node.items) with self.block(extra=self.get_type_comment(node)): self.traverse(node.body)
def _str_literal_helper( self, string, *, quote_types=_ALL_QUOTES, escape_special_whitespace=False ): """Helper for writing string literals, minimizing escapes. Returns the tuple (string literal to write, possible quote types). """ def escape_char(c): # \n and \t are non-printable, but we only escape them if # escape_special_whitespace is True if not escape_special_whitespace and c in "\n\t": return c # Always escape backslashes and other non-printable characters if c == "\\" or not c.isprintable(): return c.encode("unicode_escape").decode("ascii") return c
escaped_string = "".join(map(escape_char, string)) possible_quotes = quote_types if "\n" in escaped_string: possible_quotes = [q for q in possible_quotes if q in _MULTI_QUOTES] possible_quotes = [q for q in possible_quotes if q not in escaped_string] if not possible_quotes: # If there aren't any possible_quotes, fallback to using repr # on the original string. Try to use a quote from quote_types, # e.g., so that we use triple quotes for docstrings. string = repr(string) quote = next((q for q in quote_types if string[0] in q), string[0]) return string[1:-1], [quote] if escaped_string: # Sort so that we prefer '''"''' over """\"""" possible_quotes.sort(key=lambda q: q[0] == escaped_string[-1]) # If we're using triple quotes and we'd need to escape a final # quote, escape it if possible_quotes[0][0] == escaped_string[-1]: assert len(possible_quotes[0]) == 3 escaped_string = escaped_string[:-1] + "\\" + escaped_string[-1] return escaped_string, possible_quotes
def _write_str_avoiding_backslashes(self, string, *, quote_types=_ALL_QUOTES): """Write string literal value with a best effort attempt to avoid backslashes.""" string, quote_types = self._str_literal_helper(string, quote_types=quote_types) quote_type = quote_types[0] self.write(f"{quote_type}{string}{quote_type}")
def visit_JoinedStr(self, node): self.write("f") if self._avoid_backslashes: self._fstring_JoinedStr(node, self.buffer_writer) self._write_str_avoiding_backslashes(self.buffer) return
# If we don't need to avoid backslashes globally (i.e., we only need # to avoid them inside FormattedValues), it's cosmetically preferred # to use escaped whitespace. That is, it's preferred to use backslashes # for cases like: f"{x}\n". To accomplish this, we keep track of what # in our buffer corresponds to FormattedValues and what corresponds to # Constant parts of the f-string, and allow escapes accordingly. buffer = [] for value in node.values: meth = getattr(self, "_fstring_" + type(value).__name__) meth(value, self.buffer_writer) buffer.append((self.buffer, isinstance(value, Constant))) new_buffer = [] quote_types = _ALL_QUOTES for value, is_constant in buffer: # Repeatedly narrow down the list of possible quote_types value, quote_types = self._str_literal_helper( value, quote_types=quote_types, escape_special_whitespace=is_constant ) new_buffer.append(value) value = "".join(new_buffer) quote_type = quote_types[0] self.write(f"{quote_type}{value}{quote_type}")
def visit_FormattedValue(self, node): self.write("f") self._fstring_FormattedValue(node, self.buffer_writer) self._write_str_avoiding_backslashes(self.buffer)
def _fstring_JoinedStr(self, node, write): for value in node.values: meth = getattr(self, "_fstring_" + type(value).__name__) meth(value, write)
def _fstring_Constant(self, node, write): if not isinstance(node.value, str): raise ValueError("Constants inside JoinedStr should be a string.") value = node.value.replace("{", "{{").replace("}", "}}") write(value)
def _fstring_FormattedValue(self, node, write): write("{") unparser = type(self)(_avoid_backslashes=True) unparser.set_precedence(_Precedence.TEST.next(), node.value) expr = unparser.visit(node.value) if expr.startswith("{"): write(" ") # Separate pair of opening brackets as "{ {" if "\\" in expr: raise ValueError("Unable to avoid backslash in f-string expression part") write(expr) if node.conversion != -1: conversion = chr(node.conversion) if conversion not in "sra": raise ValueError("Unknown f-string conversion.") write(f"!{conversion}") if node.format_spec: write(":") meth = getattr(self, "_fstring_" + type(node.format_spec).__name__) meth(node.format_spec, write) write("}")
def visit_Name(self, node): self.write(node.id)
def _write_docstring(self, node): self.fill() if node.kind == "u": self.write("u") self._write_str_avoiding_backslashes(node.value, quote_types=_MULTI_QUOTES)
def _write_constant(self, value): if isinstance(value, (float, complex)): # Substitute overflowing decimal literal for AST infinities, # and inf - inf for NaNs. self.write( repr(value) .replace("inf", _INFSTR) .replace("nan", f"({_INFSTR}-{_INFSTR})") ) elif self._avoid_backslashes and isinstance(value, str): self._write_str_avoiding_backslashes(value) else: self.write(repr(value))
def visit_Constant(self, node): value = node.value if isinstance(value, tuple): with self.delimit("(", ")"): self.items_view(self._write_constant, value) elif value is ...: self.write("...") else: if node.kind == "u": self.write("u") self._write_constant(node.value)
def visit_List(self, node): with self.delimit("[", "]"): self.interleave(lambda: self.write(", "), self.traverse, node.elts)
def visit_ListComp(self, node): with self.delimit("[", "]"): self.traverse(node.elt) for gen in node.generators: self.traverse(gen)
def visit_GeneratorExp(self, node): with self.delimit("(", ")"): self.traverse(node.elt) for gen in node.generators: self.traverse(gen)
def visit_SetComp(self, node): with self.delimit("{", "}"): self.traverse(node.elt) for gen in node.generators: self.traverse(gen)
def visit_DictComp(self, node): with self.delimit("{", "}"): self.traverse(node.key) self.write(": ") self.traverse(node.value) for gen in node.generators: self.traverse(gen)
def visit_comprehension(self, node): if node.is_async: self.write(" async for ") else: self.write(" for ") self.set_precedence(_Precedence.TUPLE, node.target) self.traverse(node.target) self.write(" in ") self.set_precedence(_Precedence.TEST.next(), node.iter, *node.ifs) self.traverse(node.iter) for if_clause in node.ifs: self.write(" if ") self.traverse(if_clause)
def visit_IfExp(self, node): with self.require_parens(_Precedence.TEST, node): self.set_precedence(_Precedence.TEST.next(), node.body, node.test) self.traverse(node.body) self.write(" if ") self.traverse(node.test) self.write(" else ") self.set_precedence(_Precedence.TEST, node.orelse) self.traverse(node.orelse)
def visit_Set(self, node): if node.elts: with self.delimit("{", "}"): self.interleave(lambda: self.write(", "), self.traverse, node.elts) else: # `{}` would be interpreted as a dictionary literal, and # `set` might be shadowed. Thus: self.write('{*()}')
def visit_Dict(self, node): def write_key_value_pair(k, v): self.traverse(k) self.write(": ") self.traverse(v)
def write_item(item): k, v = item if k is None: # for dictionary unpacking operator in dicts {**{'y': 2}} # see PEP 448 for details self.write("**") self.set_precedence(_Precedence.EXPR, v) self.traverse(v) else: write_key_value_pair(k, v)
with self.delimit("{", "}"): self.interleave( lambda: self.write(", "), write_item, zip(node.keys, node.values) )
def visit_Tuple(self, node): with self.delimit("(", ")"): self.items_view(self.traverse, node.elts)
unop = {"Invert": "~", "Not": "not", "UAdd": "+", "USub": "-"} unop_precedence = { "not": _Precedence.NOT, "~": _Precedence.FACTOR, "+": _Precedence.FACTOR, "-": _Precedence.FACTOR, }
def visit_UnaryOp(self, node): operator = self.unop[node.op.__class__.__name__] operator_precedence = self.unop_precedence[operator] with self.require_parens(operator_precedence, node): self.write(operator) # factor prefixes (+, -, ~) shouldn't be seperated # from the value they belong, (e.g: +1 instead of + 1) if operator_precedence is not _Precedence.FACTOR: self.write(" ") self.set_precedence(operator_precedence, node.operand) self.traverse(node.operand)
binop = { "Add": "+", "Sub": "-", "Mult": "*", "MatMult": "@", "Div": "/", "Mod": "%", "LShift": "<<", "RShift": ">>", "BitOr": "|", "BitXor": "^", "BitAnd": "&", "FloorDiv": "//", "Pow": "**", }
binop_precedence = { "+": _Precedence.ARITH, "-": _Precedence.ARITH, "*": _Precedence.TERM, "@": _Precedence.TERM, "/": _Precedence.TERM, "%": _Precedence.TERM, "<<": _Precedence.SHIFT, ">>": _Precedence.SHIFT, "|": _Precedence.BOR, "^": _Precedence.BXOR, "&": _Precedence.BAND, "//": _Precedence.TERM, "**": _Precedence.POWER, }
binop_rassoc = frozenset(("**",)) def visit_BinOp(self, node): operator = self.binop[node.op.__class__.__name__] operator_precedence = self.binop_precedence[operator] with self.require_parens(operator_precedence, node): if operator in self.binop_rassoc: left_precedence = operator_precedence.next() right_precedence = operator_precedence else: left_precedence = operator_precedence right_precedence = operator_precedence.next()
self.set_precedence(left_precedence, node.left) self.traverse(node.left) self.write(f" {operator} ") self.set_precedence(right_precedence, node.right) self.traverse(node.right)
cmpops = { "Eq": "==", "NotEq": "!=", "Lt": "<", "LtE": "<=", "Gt": ">", "GtE": ">=", "Is": "is", "IsNot": "is not", "In": "in", "NotIn": "not in", }
def visit_Compare(self, node): with self.require_parens(_Precedence.CMP, node): self.set_precedence(_Precedence.CMP.next(), node.left, *node.comparators) self.traverse(node.left) for o, e in zip(node.ops, node.comparators): self.write(" " + self.cmpops[o.__class__.__name__] + " ") self.traverse(e)
boolops = {"And": "and", "Or": "or"} boolop_precedence = {"and": _Precedence.AND, "or": _Precedence.OR}
def visit_BoolOp(self, node): operator = self.boolops[node.op.__class__.__name__] operator_precedence = self.boolop_precedence[operator]
def increasing_level_traverse(node): nonlocal operator_precedence operator_precedence = operator_precedence.next() self.set_precedence(operator_precedence, node) self.traverse(node)
with self.require_parens(operator_precedence, node): s = f" {operator} " self.interleave(lambda: self.write(s), increasing_level_traverse, node.values)
def visit_Attribute(self, node): self.set_precedence(_Precedence.ATOM, node.value) self.traverse(node.value) # Special case: 3.__abs__() is a syntax error, so if node.value # is an integer literal then we need to either parenthesize # it or add an extra space to get 3 .__abs__(). if isinstance(node.value, Constant) and isinstance(node.value.value, int): self.write(" ") self.write(".") self.write(node.attr)
def visit_Call(self, node): self.set_precedence(_Precedence.ATOM, node.func) self.traverse(node.func) with self.delimit("(", ")"): comma = False for e in node.args: if comma: self.write(", ") else: comma = True self.traverse(e) for e in node.keywords: if comma: self.write(", ") else: comma = True self.traverse(e)
def visit_Subscript(self, node): def is_simple_tuple(slice_value): # when unparsing a non-empty tuple, the parentheses can be safely # omitted if there aren't any elements that explicitly requires # parentheses (such as starred expressions). return ( isinstance(slice_value, Tuple) and slice_value.elts and not any(isinstance(elt, Starred) for elt in slice_value.elts) )
self.set_precedence(_Precedence.ATOM, node.value) self.traverse(node.value) with self.delimit("[", "]"): if is_simple_tuple(node.slice): self.items_view(self.traverse, node.slice.elts) else: self.traverse(node.slice)
def visit_Starred(self, node): self.write("*") self.set_precedence(_Precedence.EXPR, node.value) self.traverse(node.value)
def visit_Ellipsis(self, node): self.write("...")
def visit_Slice(self, node): if node.lower: self.traverse(node.lower) self.write(":") if node.upper: self.traverse(node.upper) if node.step: self.write(":") self.traverse(node.step)
def visit_Match(self, node): self.fill("match ") self.traverse(node.subject) with self.block(): for case in node.cases: self.traverse(case)
def visit_arg(self, node): self.write(node.arg) if node.annotation: self.write(": ") self.traverse(node.annotation)
def visit_arguments(self, node): first = True # normal arguments all_args = node.posonlyargs + node.args defaults = [None] * (len(all_args) - len(node.defaults)) + node.defaults for index, elements in enumerate(zip(all_args, defaults), 1): a, d = elements if first: first = False else: self.write(", ") self.traverse(a) if d: self.write("=") self.traverse(d) if index == len(node.posonlyargs): self.write(", /")
# varargs, or bare '*' if no varargs but keyword-only arguments present if node.vararg or node.kwonlyargs: if first: first = False else: self.write(", ") self.write("*") if node.vararg: self.write(node.vararg.arg) if node.vararg.annotation: self.write(": ") self.traverse(node.vararg.annotation)
# keyword-only arguments if node.kwonlyargs: for a, d in zip(node.kwonlyargs, node.kw_defaults): self.write(", ") self.traverse(a) if d: self.write("=") self.traverse(d)
# kwargs if node.kwarg: if first: first = False else: self.write(", ") self.write("**" + node.kwarg.arg) if node.kwarg.annotation: self.write(": ") self.traverse(node.kwarg.annotation)
def visit_keyword(self, node): if node.arg is None: self.write("**") else: self.write(node.arg) self.write("=") self.traverse(node.value)
def visit_Lambda(self, node): with self.require_parens(_Precedence.TEST, node): self.write("lambda ") self.traverse(node.args) self.write(": ") self.set_precedence(_Precedence.TEST, node.body) self.traverse(node.body)
def visit_alias(self, node): self.write(node.name) if node.asname: self.write(" as " + node.asname)
def visit_withitem(self, node): self.traverse(node.context_expr) if node.optional_vars: self.write(" as ") self.traverse(node.optional_vars)
def visit_match_case(self, node): self.fill("case ") self.traverse(node.pattern) if node.guard: self.write(" if ") self.traverse(node.guard) with self.block(): self.traverse(node.body)
def visit_MatchValue(self, node): self.traverse(node.value)
def visit_MatchSingleton(self, node): self._write_constant(node.value)
def visit_MatchSequence(self, node): with self.delimit("[", "]"): self.interleave( lambda: self.write(", "), self.traverse, node.patterns )
def visit_MatchStar(self, node): name = node.name if name is None: name = "_" self.write(f"*{name}")
def visit_MatchMapping(self, node): def write_key_pattern_pair(pair): k, p = pair self.traverse(k) self.write(": ") self.traverse(p)
with self.delimit("{", "}"): keys = node.keys self.interleave( lambda: self.write(", "), write_key_pattern_pair, zip(keys, node.patterns, strict=True), ) rest = node.rest if rest is not None: if keys: self.write(", ") self.write(f"**{rest}")
def visit_MatchClass(self, node): self.set_precedence(_Precedence.ATOM, node.cls) self.traverse(node.cls) with self.delimit("(", ")"): patterns = node.patterns self.interleave( lambda: self.write(", "), self.traverse, patterns ) attrs = node.kwd_attrs if attrs: def write_attr_pattern(pair): attr, pattern = pair self.write(f"{attr}=") self.traverse(pattern)
if patterns: self.write(", ") self.interleave( lambda: self.write(", "), write_attr_pattern, zip(attrs, node.kwd_patterns, strict=True), )
def visit_MatchAs(self, node): name = node.name pattern = node.pattern if name is None: self.write("_") elif pattern is None: self.write(node.name) else: with self.require_parens(_Precedence.TEST, node): self.set_precedence(_Precedence.BOR, node.pattern) self.traverse(node.pattern) self.write(f" as {node.name}")
def visit_MatchOr(self, node): with self.require_parens(_Precedence.BOR, node): self.set_precedence(_Precedence.BOR.next(), *node.patterns) self.interleave(lambda: self.write(" | "), self.traverse, node.patterns)
def unparse(ast_obj): unparser = _Unparser() return unparser.visit(ast_obj)
def main(): import argparse
parser = argparse.ArgumentParser(prog='python -m ast') parser.add_argument('infile', type=argparse.FileType(mode='rb'), nargs='?', default='-', help='the file to parse; defaults to stdin') parser.add_argument('-m', '--mode', default='exec', choices=('exec', 'single', 'eval', 'func_type'), help='specify what kind of code must be parsed') parser.add_argument('--no-type-comments', default=True, action='store_false', help="don't add information about type comments") parser.add_argument('-a', '--include-attributes', action='store_true', help='include attributes such as line numbers and ' 'column offsets') parser.add_argument('-i', '--indent', type=int, default=3, help='indentation of nodes (number of spaces)') args = parser.parse_args()
with args.infile as infile: source = infile.read() tree = parse(source, args.infile.name, args.mode, type_comments=args.no_type_comments) print(dump(tree, include_attributes=args.include_attributes, indent=args.indent))
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315# -*- 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 sidesends a 'command', and the other sends a response (examples would bethe 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 itsreceipt.
for example:Say you build an async nntp client using this class. At the startof the connection, you'll have self.terminator set to '\r\n', inorder 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 LISTcommand will be accumulated (using your own 'collect_incoming_data'method) up to the terminator, and then control will be returned toyou - by calling your self.found_terminator() method."""import asyncorefrom collections import deque
from warnings import warnwarn( 'The asynchat module is deprecated and will be removed in Python 3.12. ' 'The recommended replacement is asyncio', DeprecationWarning, stacklevel=2)
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 = 65536 ac_out_buffer_size = 65536
# we don't want to enable the use of encoding by default, because that is a # sign of an application bug that we don't want to pass silently
use_encoding = 0 encoding = 'latin-1'
def __init__(self, sock=None, map=None): # for string terminator matching self.ac_in_buffer = b''
# we use a list here rather than io.BytesIO for a few reasons... # del lst[:] is faster than bio.truncate(0) # lst = [] is faster than bio.truncate(0) self.incoming = []
# we toss the use of the "simple producer" and replace it with # a pure deque, which the original fifo was a wrapping of self.producer_fifo = deque() asyncore.dispatcher.__init__(self, sock, map)
def collect_incoming_data(self, data): raise NotImplementedError("must be implemented in subclass")
def _collect_incoming_data(self, data): self.incoming.append(data)
def _get_data(self): d = b''.join(self.incoming) del self.incoming[:] return d
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. """ if isinstance(term, str) and self.use_encoding: term = bytes(term, self.encoding) elif isinstance(term, int) and term < 0: raise ValueError('the number of received bytes must be positive') 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 BlockingIOError: return except OSError: self.handle_error() return
if isinstance(data, str) and self.use_encoding: data = bytes(str, self.encoding) 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(4096).
while self.ac_in_buffer: lb = len(self.ac_in_buffer) terminator = self.get_terminator() if not terminator: # no terminator, collect it all self.collect_incoming_data(self.ac_in_buffer) self.ac_in_buffer = b'' elif isinstance(terminator, int): # numeric terminator n = terminator if lb < n: self.collect_incoming_data(self.ac_in_buffer) self.ac_in_buffer = b'' 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 = b''
def handle_write(self): self.initiate_send()
def handle_close(self): self.close()
def push(self, data): if not isinstance(data, (bytes, bytearray, memoryview)): raise TypeError('data argument must be byte-ish (%r)', type(data)) sabs = self.ac_out_buffer_size if len(data) > sabs: for i in range(0, len(data), sabs): self.producer_fifo.append(data[i:i+sabs]) else: self.producer_fifo.append(data) self.initiate_send()
def push_with_producer(self, producer): self.producer_fifo.append(producer) self.initiate_send()
def readable(self): "predicate for inclusion in the readable for select()" # cannot use the old predicate, it violates the claim of the # set_terminator method.
# return (len(self.ac_in_buffer) <= self.ac_in_buffer_size) return 1
def writable(self): "predicate for inclusion in the writable for select()" return self.producer_fifo or (not self.connected)
def close_when_done(self): "automatically close this channel once the outgoing queue is empty" self.producer_fifo.append(None)
def initiate_send(self): while self.producer_fifo and self.connected: first = self.producer_fifo[0] # handle empty string/buffer or None entry if not first: del self.producer_fifo[0] if first is None: self.handle_close() return
# handle classic producer behavior obs = self.ac_out_buffer_size try: data = first[:obs] except TypeError: data = first.more() if data: self.producer_fifo.appendleft(data) else: del self.producer_fifo[0] continue
if isinstance(data, str) and self.use_encoding: data = bytes(data, self.encoding)
# send the data try: num_sent = self.send(data) except OSError: self.handle_error() return
if num_sent: if num_sent < len(data) or obs < len(first): self.producer_fifo[0] = first[num_sent:] else: del self.producer_fifo[0] # we tried to send some actual data return
def discard_buffers(self): # Emergencies only! self.ac_in_buffer = b'' del self.incoming[:] self.producer_fifo.clear()
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 = b'' return result
# 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 l123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649# -*- Mode: Python -*-# Id: asyncore.py,v 2.51 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.# ======================================================================
"""Basic infrastructure for asynchronous socket service clients and servers.
There are only two ways to have a program on a single processor do "morethan one thing at a time". Multi-threaded programming is the simplest andmost popular way to do it, but there is another very different technique,that lets you have nearly all the advantages of multi-threading, withoutactually using multiple threads. it's really only practical if your programis largely I/O bound. If your program is CPU bound, then pre-emptivescheduled threads are probably what you really need. Network servers arerarely CPU-bound, however.
If your operating system supports the select() system call in its I/Olibrary (and nearly all do), then you can use it to juggle multiplecommunication channels at once; doing other work while your I/O is takingplace in the "background." Although this strategy can seem strange andcomplex, especially at first, it is in many ways easier to understand andcontrol than multi-threaded programming. The module documented here solvesmany of the difficult problems for you, making the task of buildingsophisticated high-performance network servers and clients a snap."""
import selectimport socketimport sysimport timeimport warnings
import osfrom errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, EINVAL, \ ENOTCONN, ESHUTDOWN, EISCONN, EBADF, ECONNABORTED, EPIPE, EAGAIN, \ errorcode
warnings.warn( 'The asyncore module is deprecated and will be removed in Python 3.12. ' 'The recommended replacement is asyncio', DeprecationWarning, stacklevel=2)
_DISCONNECTED = frozenset({ECONNRESET, ENOTCONN, ESHUTDOWN, ECONNABORTED, EPIPE, EBADF})
try: socket_mapexcept NameError: socket_map = {}
def _strerror(err): try: return os.strerror(err) except (ValueError, OverflowError, NameError): if err in errorcode: return errorcode[err] return "Unknown error %s" %err
class ExitNow(Exception): pass
_reraised_exceptions = (ExitNow, KeyboardInterrupt, SystemExit)
def read(obj): try: obj.handle_read_event() except _reraised_exceptions: raise except: obj.handle_error()
def write(obj): try: obj.handle_write_event() except _reraised_exceptions: raise except: obj.handle_error()
def _exception(obj): try: obj.handle_expt_event() except _reraised_exceptions: raise except: obj.handle_error()
def readwrite(obj, flags): try: if flags & select.POLLIN: obj.handle_read_event() if flags & select.POLLOUT: obj.handle_write_event() if flags & select.POLLPRI: obj.handle_expt_event() if flags & (select.POLLHUP | select.POLLERR | select.POLLNVAL): obj.handle_close() except OSError as e: if e.errno not in _DISCONNECTED: obj.handle_error() else: obj.handle_close() except _reraised_exceptions: raise except: obj.handle_error()
def poll(timeout=0.0, map=None): if map is None: map = socket_map if map: r = []; w = []; e = [] for fd, obj in list(map.items()): is_r = obj.readable() is_w = obj.writable() if is_r: r.append(fd) # accepting sockets should not be writable if is_w and not obj.accepting: w.append(fd) if is_r or is_w: e.append(fd) if [] == r == w == e: time.sleep(timeout) return
r, w, e = select.select(r, w, e, timeout)
for fd in r: obj = map.get(fd) if obj is None: continue read(obj)
for fd in w: obj = map.get(fd) if obj is None: continue write(obj)
for fd in e: obj = map.get(fd) if obj is None: continue _exception(obj)
def poll2(timeout=0.0, map=None): # Use the poll() support added to the select module in Python 2.0 if map is None: map = socket_map if timeout is not None: # timeout is in milliseconds timeout = int(timeout*1000) pollster = select.poll() if map: for fd, obj in list(map.items()): flags = 0 if obj.readable(): flags |= select.POLLIN | select.POLLPRI # accepting sockets should not be writable if obj.writable() and not obj.accepting: flags |= select.POLLOUT if flags: pollster.register(fd, flags)
r = pollster.poll(timeout) for fd, flags in r: obj = map.get(fd) if obj is None: continue readwrite(obj, flags)
poll3 = poll2 # Alias for backward compatibility
def loop(timeout=30.0, use_poll=False, map=None, count=None): if map is None: map = socket_map
if use_poll and hasattr(select, 'poll'): poll_fun = poll2 else: poll_fun = poll
if count is None: while map: poll_fun(timeout, map)
else: while map and count > 0: poll_fun(timeout, map) count = count - 1
class dispatcher:
debug = False connected = False accepting = False connecting = False closing = False addr = None ignore_log_types = frozenset({'warning'})
def __init__(self, sock=None, map=None): if map is None: self._map = socket_map else: self._map = map
self._fileno = None
if sock: # Set to nonblocking just to make sure for cases where we # get a socket from a blocking source. sock.setblocking(False) self.set_socket(sock, map) self.connected = True # The constructor no longer requires that the socket # passed be connected. try: self.addr = sock.getpeername() except OSError as err: if err.errno in (ENOTCONN, EINVAL): # To handle the case where we got an unconnected # socket. self.connected = False else: # The socket is broken in some unknown way, alert # the user and remove it from the map (to prevent # polling of broken sockets). self.del_channel(map) raise else: self.socket = None
def __repr__(self): status = [self.__class__.__module__+"."+self.__class__.__qualname__] if self.accepting and self.addr: status.append('listening') elif self.connected: status.append('connected') if self.addr is not None: try: status.append('%s:%d' % self.addr) except TypeError: status.append(repr(self.addr)) return '<%s at %#x>' % (' '.join(status), id(self))
def add_channel(self, map=None): #self.log_info('adding channel %s' % self) if map is None: map = self._map map[self._fileno] = self
def del_channel(self, map=None): fd = self._fileno if map is None: map = self._map if fd in map: #self.log_info('closing channel %d:%s' % (fd, self)) del map[fd] self._fileno = None
def create_socket(self, family=socket.AF_INET, type=socket.SOCK_STREAM): self.family_and_type = family, type sock = socket.socket(family, type) sock.setblocking(False) self.set_socket(sock)
def set_socket(self, sock, map=None): self.socket = sock self._fileno = sock.fileno() self.add_channel(map)
def set_reuse_addr(self): # try to re-use a server port if possible try: self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1 ) except OSError: pass
# ================================================== # predicates for select() # these are used as filters for the lists of sockets # to pass to select(). # ==================================================
def readable(self): return True
def writable(self): return True
# ================================================== # socket object methods. # ==================================================
def listen(self, num): self.accepting = True if os.name == 'nt' and num > 5: num = 5 return self.socket.listen(num)
def bind(self, addr): self.addr = addr return self.socket.bind(addr)
def connect(self, address): self.connected = False self.connecting = True err = self.socket.connect_ex(address) if err in (EINPROGRESS, EALREADY, EWOULDBLOCK) \ or err == EINVAL and os.name == 'nt': self.addr = address return if err in (0, EISCONN): self.addr = address self.handle_connect_event() else: raise OSError(err, errorcode[err])
def accept(self): # XXX can return either an address pair or None try: conn, addr = self.socket.accept() except TypeError: return None except OSError as why: if why.errno in (EWOULDBLOCK, ECONNABORTED, EAGAIN): return None else: raise else: return conn, addr
def send(self, data): try: result = self.socket.send(data) return result except OSError as why: if why.errno == EWOULDBLOCK: return 0 elif why.errno in _DISCONNECTED: self.handle_close() return 0 else: raise
def recv(self, buffer_size): try: data = self.socket.recv(buffer_size) if not data: # a closed connection is indicated by signaling # a read condition, and having recv() return 0. self.handle_close() return b'' else: return data except OSError as why: # winsock sometimes raises ENOTCONN if why.errno in _DISCONNECTED: self.handle_close() return b'' else: raise
def close(self): self.connected = False self.accepting = False self.connecting = False self.del_channel() if self.socket is not None: try: self.socket.close() except OSError as why: if why.errno not in (ENOTCONN, EBADF): raise
# log and log_info may be overridden to provide more sophisticated # logging and warning methods. In general, log is for 'hit' logging # and 'log_info' is for informational, warning and error logging.
def log(self, message): sys.stderr.write('log: %s\n' % str(message))
def log_info(self, message, type='info'): if type not in self.ignore_log_types: print('%s: %s' % (type, message))
def handle_read_event(self): if self.accepting: # accepting sockets are never connected, they "spawn" new # sockets that are connected self.handle_accept() elif not self.connected: if self.connecting: self.handle_connect_event() self.handle_read() else: self.handle_read()
def handle_connect_event(self): err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: raise OSError(err, _strerror(err)) self.handle_connect() self.connected = True self.connecting = False
def handle_write_event(self): if self.accepting: # Accepting sockets shouldn't get a write event. # We will pretend it didn't happen. return
if not self.connected: if self.connecting: self.handle_connect_event() self.handle_write()
def handle_expt_event(self): # handle_expt_event() is called if there might be an error on the # socket, or if there is OOB data # check for the error condition first err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # we can get here when select.select() says that there is an # exceptional condition on the socket # since there is an error, we'll go ahead and close the socket # like we would in a subclassed handle_read() that received no # data self.handle_close() else: self.handle_expt()
def handle_error(self): nil, t, v, tbinfo = compact_traceback()
# sometimes a user repr method will crash. try: self_repr = repr(self) except: self_repr = '<__repr__(self) failed for object at %0x>' % id(self)
self.log_info( 'uncaptured python exception, closing channel %s (%s:%s %s)' % ( self_repr, t, v, tbinfo ), 'error' ) self.handle_close()
def handle_expt(self): self.log_info('unhandled incoming priority event', 'warning')
def handle_read(self): self.log_info('unhandled read event', 'warning')
def handle_write(self): self.log_info('unhandled write event', 'warning')
def handle_connect(self): self.log_info('unhandled connect event', 'warning')
def handle_accept(self): pair = self.accept() if pair is not None: self.handle_accepted(*pair)
def handle_accepted(self, sock, addr): sock.close() self.log_info('unhandled accepted event', 'warning')
def handle_close(self): self.log_info('unhandled close event', 'warning') self.close()
# ---------------------------------------------------------------------------# adds simple buffered output capability, useful for simple clients.# [for more sophisticated usage use asynchat.async_chat]# ---------------------------------------------------------------------------
class dispatcher_with_send(dispatcher):
def __init__(self, sock=None, map=None): dispatcher.__init__(self, sock, map) self.out_buffer = b''
def initiate_send(self): num_sent = 0 num_sent = dispatcher.send(self, self.out_buffer[:65536]) self.out_buffer = self.out_buffer[num_sent:]
def handle_write(self): self.initiate_send()
def writable(self): return (not self.connected) or len(self.out_buffer)
def send(self, data): if self.debug: self.log_info('sending %s' % repr(data)) self.out_buffer = self.out_buffer + data self.initiate_send()
# ---------------------------------------------------------------------------# used for debugging.# ---------------------------------------------------------------------------
def compact_traceback(): t, v, tb = sys.exc_info() tbinfo = [] if not tb: # Must have a traceback raise AssertionError("traceback does not exist") while tb: tbinfo.append(( tb.tb_frame.f_code.co_filename, tb.tb_frame.f_code.co_name, str(tb.tb_lineno) )) tb = tb.tb_next
# just to be safe del tb
file, function, line = tbinfo[-1] info = ' '.join(['[%s|%s|%s]' % x for x in tbinfo]) return (file, function, line), t, v, info
def close_all(map=None, ignore_all=False): if map is None: map = socket_map for x in list(map.values()): try: x.close() except OSError as x: if x.errno == EBADF: pass elif not ignore_all: raise except _reraised_exceptions: raise except: if not ignore_all: raise map.clear()
# Asynchronous File I/O:## After a little research (reading man pages on various unixen, and# digging through the linux kernel), I've determined that select()# isn't meant for doing asynchronous file i/o.# Heartening, though - reading linux/mm/filemap.c shows that linux# supports asynchronous read-ahead. So _MOST_ of the time, the data# will be sitting in memory for us already when we go to read it.## What other OS's (besides NT) support async file i/o? [VMS?]## Regardless, this is useful for pipes, and stdin/stdout...
if os.name == 'posix': class file_wrapper: # Here we override just enough to make a file # look like a socket for the purposes of asyncore. # The passed fd is automatically os.dup()'d
def __init__(self, fd): self.fd = os.dup(fd)
def __del__(self): if self.fd >= 0: warnings.warn("unclosed file %r" % self, ResourceWarning, source=self) self.close()
def recv(self, *args): return os.read(self.fd, *args)
def send(self, *args): return os.write(self.fd, *args)
def getsockopt(self, level, optname, buflen=None): if (level == socket.SOL_SOCKET and optname == socket.SO_ERROR and not buflen): return 0 raise NotImplementedError("Only asyncore specific behaviour " "implemented.")
read = recv write = send
def close(self): if self.fd < 0: return fd = self.fd self.fd = -1 os.close(fd)
def fileno(self): return self.fd
class file_dispatcher(dispatcher):
def __init__(self, fd, map=None): dispatcher.__init__(self, None, map) self.connected = True try: fd = fd.fileno() except AttributeError: pass self.set_file(fd) # set it to non-blocking mode os.set_blocking(fd, False)
def set_file(self, fd): self.socket = file_wrapper(fd) self._fileno = self.socket.fileno() self.add_channel()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603#! /usr/bin/env python3
"""Base16, Base32, Base64 (RFC 3548), Base85 and Ascii85 data encodings"""
# Modified 04-Oct-1995 by Jack Jansen to use binascii module# Modified 30-Dec-2003 by Barry Warsaw to add full RFC 3548 support# Modified 22-May-2007 by Guido van Rossum to use bytes everywhere
import reimport structimport binascii
__all__ = [ # Legacy interface exports traditional RFC 2045 Base64 encodings 'encode', 'decode', 'encodebytes', 'decodebytes', # Generalized interface for other encodings 'b64encode', 'b64decode', 'b32encode', 'b32decode', 'b32hexencode', 'b32hexdecode', 'b16encode', 'b16decode', # Base85 and Ascii85 encodings 'b85encode', 'b85decode', 'a85encode', 'a85decode', # Standard Base64 encoding 'standard_b64encode', 'standard_b64decode', # Some common Base64 alternatives. As referenced by RFC 3458, see thread # starting at: # # http://zgp.org/pipermail/p2p-hackers/2001-September/000316.html 'urlsafe_b64encode', 'urlsafe_b64decode', ]
bytes_types = (bytes, bytearray) # Types acceptable as binary data
def _bytes_from_decode_data(s): if isinstance(s, str): try: return s.encode('ascii') except UnicodeEncodeError: raise ValueError('string argument should contain only ASCII characters') if isinstance(s, bytes_types): return s try: return memoryview(s).tobytes() except TypeError: raise TypeError("argument should be a bytes-like object or ASCII " "string, not %r" % s.__class__.__name__) from None
# Base64 encoding/decoding uses binascii
def b64encode(s, altchars=None): """Encode the bytes-like object s using Base64 and return a bytes object.
Optional altchars should be a byte string of length 2 which specifies an alternative alphabet for the '+' and '/' characters. This allows an application to e.g. generate url or filesystem safe Base64 strings. """ encoded = binascii.b2a_base64(s, newline=False) if altchars is not None: assert len(altchars) == 2, repr(altchars) return encoded.translate(bytes.maketrans(b'+/', altchars)) return encoded
def b64decode(s, altchars=None, validate=False): """Decode the Base64 encoded bytes-like object or ASCII string s.
Optional altchars must be a bytes-like object or ASCII string of length 2 which specifies the alternative alphabet used instead of the '+' and '/' characters.
The result is returned as a bytes object. A binascii.Error is raised if s is incorrectly padded.
If validate is False (the default), characters that are neither in the normal base-64 alphabet nor the alternative alphabet are discarded prior to the padding check. If validate is True, these non-alphabet characters in the input result in a binascii.Error. """ s = _bytes_from_decode_data(s) if altchars is not None: altchars = _bytes_from_decode_data(altchars) assert len(altchars) == 2, repr(altchars) s = s.translate(bytes.maketrans(altchars, b'+/')) if validate and not re.fullmatch(b'[A-Za-z0-9+/]*={0,2}', s): raise binascii.Error('Non-base64 digit found') return binascii.a2b_base64(s)
def standard_b64encode(s): """Encode bytes-like object s using the standard Base64 alphabet.
The result is returned as a bytes object. """ return b64encode(s)
def standard_b64decode(s): """Decode bytes encoded with the standard Base64 alphabet.
Argument s is a bytes-like object or ASCII string to decode. The result is returned as a bytes object. A binascii.Error is raised if the input is incorrectly padded. Characters that are not in the standard alphabet are discarded prior to the padding check. """ return b64decode(s)
_urlsafe_encode_translation = bytes.maketrans(b'+/', b'-_')_urlsafe_decode_translation = bytes.maketrans(b'-_', b'+/')
def urlsafe_b64encode(s): """Encode bytes using the URL- and filesystem-safe Base64 alphabet.
Argument s is a bytes-like object to encode. The result is returned as a bytes object. The alphabet uses '-' instead of '+' and '_' instead of '/'. """ return b64encode(s).translate(_urlsafe_encode_translation)
def urlsafe_b64decode(s): """Decode bytes using the URL- and filesystem-safe Base64 alphabet.
Argument s is a bytes-like object or ASCII string to decode. The result is returned as a bytes object. A binascii.Error is raised if the input is incorrectly padded. Characters that are not in the URL-safe base-64 alphabet, and are not a plus '+' or slash '/', are discarded prior to the padding check.
The alphabet uses '-' instead of '+' and '_' instead of '/'. """ s = _bytes_from_decode_data(s) s = s.translate(_urlsafe_decode_translation) return b64decode(s)
# Base32 encoding/decoding must be done in Python_B32_ENCODE_DOCSTRING = '''Encode the bytes-like objects using {encoding} and return a bytes object.'''_B32_DECODE_DOCSTRING = '''Decode the {encoding} encoded bytes-like object or ASCII string s.
Optional casefold is a flag specifying whether a lowercase alphabet isacceptable as input. For security purposes, the default is False.{extra_args}The result is returned as a bytes object. A binascii.Error is raised ifthe input is incorrectly padded or if there are non-alphabetcharacters present in the input.'''_B32_DECODE_MAP01_DOCSTRING = '''RFC 3548 allows for optional mapping of the digit 0 (zero) to theletter O (oh), and for optional mapping of the digit 1 (one) toeither the letter I (eye) or letter L (el). The optional argumentmap01 when not None, specifies which letter the digit 1 should bemapped to (when map01 is not None, the digit 0 is always mapped tothe letter O). For security purposes the default is None, so that0 and 1 are not allowed in the input.'''_b32alphabet = b'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'_b32hexalphabet = b'0123456789ABCDEFGHIJKLMNOPQRSTUV'_b32tab2 = {}_b32rev = {}
def _b32encode(alphabet, s): global _b32tab2 # Delay the initialization of the table to not waste memory # if the function is never called if alphabet not in _b32tab2: b32tab = [bytes((i,)) for i in alphabet] _b32tab2[alphabet] = [a + b for a in b32tab for b in b32tab] b32tab = None
if not isinstance(s, bytes_types): s = memoryview(s).tobytes() leftover = len(s) % 5 # Pad the last quantum with zero bits if necessary if leftover: s = s + b'\0' * (5 - leftover) # Don't use += ! encoded = bytearray() from_bytes = int.from_bytes b32tab2 = _b32tab2[alphabet] for i in range(0, len(s), 5): c = from_bytes(s[i: i + 5], 'big') encoded += (b32tab2[c >> 30] + # bits 1 - 10 b32tab2[(c >> 20) & 0x3ff] + # bits 11 - 20 b32tab2[(c >> 10) & 0x3ff] + # bits 21 - 30 b32tab2[c & 0x3ff] # bits 31 - 40 ) # Adjust for any leftover partial quanta if leftover == 1: encoded[-6:] = b'======' elif leftover == 2: encoded[-4:] = b'====' elif leftover == 3: encoded[-3:] = b'===' elif leftover == 4: encoded[-1:] = b'=' return bytes(encoded)
def _b32decode(alphabet, s, casefold=False, map01=None): global _b32rev # Delay the initialization of the table to not waste memory # if the function is never called if alphabet not in _b32rev: _b32rev[alphabet] = {v: k for k, v in enumerate(alphabet)} s = _bytes_from_decode_data(s) if len(s) % 8: raise binascii.Error('Incorrect padding') # Handle section 2.4 zero and one mapping. The flag map01 will be either # False, or the character to map the digit 1 (one) to. It should be # either L (el) or I (eye). if map01 is not None: map01 = _bytes_from_decode_data(map01) assert len(map01) == 1, repr(map01) s = s.translate(bytes.maketrans(b'01', b'O' + map01)) if casefold: s = s.upper() # Strip off pad characters from the right. We need to count the pad # characters because this will tell us how many null bytes to remove from # the end of the decoded string. l = len(s) s = s.rstrip(b'=') padchars = l - len(s) # Now decode the full quanta decoded = bytearray() b32rev = _b32rev[alphabet] for i in range(0, len(s), 8): quanta = s[i: i + 8] acc = 0 try: for c in quanta: acc = (acc << 5) + b32rev[c] except KeyError: raise binascii.Error('Non-base32 digit found') from None decoded += acc.to_bytes(5, 'big') # Process the last, partial quanta if l % 8 or padchars not in {0, 1, 3, 4, 6}: raise binascii.Error('Incorrect padding') if padchars and decoded: acc <<= 5 * padchars last = acc.to_bytes(5, 'big') leftover = (43 - 5 * padchars) // 8 # 1: 4, 3: 3, 4: 2, 6: 1 decoded[-5:] = last[:leftover] return bytes(decoded)
def b32encode(s): return _b32encode(_b32alphabet, s)b32encode.__doc__ = _B32_ENCODE_DOCSTRING.format(encoding='base32')
def b32decode(s, casefold=False, map01=None): return _b32decode(_b32alphabet, s, casefold, map01)b32decode.__doc__ = _B32_DECODE_DOCSTRING.format(encoding='base32', extra_args=_B32_DECODE_MAP01_DOCSTRING)
def b32hexencode(s): return _b32encode(_b32hexalphabet, s)b32hexencode.__doc__ = _B32_ENCODE_DOCSTRING.format(encoding='base32hex')
def b32hexdecode(s, casefold=False): # base32hex does not have the 01 mapping return _b32decode(_b32hexalphabet, s, casefold)b32hexdecode.__doc__ = _B32_DECODE_DOCSTRING.format(encoding='base32hex', extra_args='')
# RFC 3548, Base 16 Alphabet specifies uppercase, but hexlify() returns# lowercase. The RFC also recommends against accepting input case# insensitively.def b16encode(s): """Encode the bytes-like object s using Base16 and return a bytes object. """ return binascii.hexlify(s).upper()
def b16decode(s, casefold=False): """Decode the Base16 encoded bytes-like object or ASCII string s.
Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False.
The result is returned as a bytes object. A binascii.Error is raised if s is incorrectly padded or if there are non-alphabet characters present in the input. """ s = _bytes_from_decode_data(s) if casefold: s = s.upper() if re.search(b'[^0-9A-F]', s): raise binascii.Error('Non-base16 digit found') return binascii.unhexlify(s)
## Ascii85 encoding/decoding#
_a85chars = None_a85chars2 = None_A85START = b"<~"_A85END = b"~>"
def _85encode(b, chars, chars2, pad=False, foldnuls=False, foldspaces=False): # Helper function for a85encode and b85encode if not isinstance(b, bytes_types): b = memoryview(b).tobytes()
padding = (-len(b)) % 4 if padding: b = b + b'\0' * padding words = struct.Struct('!%dI' % (len(b) // 4)).unpack(b)
chunks = [b'z' if foldnuls and not word else b'y' if foldspaces and word == 0x20202020 else (chars2[word // 614125] + chars2[word // 85 % 7225] + chars[word % 85]) for word in words]
if padding and not pad: if chunks[-1] == b'z': chunks[-1] = chars[0] * 5 chunks[-1] = chunks[-1][:-padding]
return b''.join(chunks)
def a85encode(b, *, foldspaces=False, wrapcol=0, pad=False, adobe=False): """Encode bytes-like object b using Ascii85 and return a bytes object.
foldspaces is an optional flag that uses the special short sequence 'y' instead of 4 consecutive spaces (ASCII 0x20) as supported by 'btoa'. This feature is not supported by the "standard" Adobe encoding.
wrapcol controls whether the output should have newline (b'\\n') characters added to it. If this is non-zero, each output line will be at most this many characters long.
pad controls whether the input is padded to a multiple of 4 before encoding. Note that the btoa implementation always pads.
adobe controls whether the encoded byte sequence is framed with <~ and ~>, which is used by the Adobe implementation. """ global _a85chars, _a85chars2 # Delay the initialization of tables to not waste memory # if the function is never called if _a85chars2 is None: _a85chars = [bytes((i,)) for i in range(33, 118)] _a85chars2 = [(a + b) for a in _a85chars for b in _a85chars]
result = _85encode(b, _a85chars, _a85chars2, pad, True, foldspaces)
if adobe: result = _A85START + result if wrapcol: wrapcol = max(2 if adobe else 1, wrapcol) chunks = [result[i: i + wrapcol] for i in range(0, len(result), wrapcol)] if adobe: if len(chunks[-1]) + 2 > wrapcol: chunks.append(b'') result = b'\n'.join(chunks) if adobe: result += _A85END
return result
def a85decode(b, *, foldspaces=False, adobe=False, ignorechars=b' \t\n\r\v'): """Decode the Ascii85 encoded bytes-like object or ASCII string b.
foldspaces is a flag that specifies whether the 'y' short sequence should be accepted as shorthand for 4 consecutive spaces (ASCII 0x20). This feature is not supported by the "standard" Adobe encoding.
adobe controls whether the input sequence is in Adobe Ascii85 format (i.e. is framed with <~ and ~>).
ignorechars should be a byte string containing characters to ignore from the input. This should only contain whitespace characters, and by default contains all whitespace characters in ASCII.
The result is returned as a bytes object. """ b = _bytes_from_decode_data(b) if adobe: if not b.endswith(_A85END): raise ValueError( "Ascii85 encoded byte sequences must end " "with {!r}".format(_A85END) ) if b.startswith(_A85START): b = b[2:-2] # Strip off start/end markers else: b = b[:-2] # # We have to go through this stepwise, so as to ignore spaces and handle # special short sequences # packI = struct.Struct('!I').pack decoded = [] decoded_append = decoded.append curr = [] curr_append = curr.append curr_clear = curr.clear for x in b + b'u' * 4: if b'!'[0] <= x <= b'u'[0]: curr_append(x) if len(curr) == 5: acc = 0 for x in curr: acc = 85 * acc + (x - 33) try: decoded_append(packI(acc)) except struct.error: raise ValueError('Ascii85 overflow') from None curr_clear() elif x == b'z'[0]: if curr: raise ValueError('z inside Ascii85 5-tuple') decoded_append(b'\0\0\0\0') elif foldspaces and x == b'y'[0]: if curr: raise ValueError('y inside Ascii85 5-tuple') decoded_append(b'\x20\x20\x20\x20') elif x in ignorechars: # Skip whitespace continue else: raise ValueError('Non-Ascii85 digit found: %c' % x)
result = b''.join(decoded) padding = 4 - len(curr) if padding: # Throw away the extra padding result = result[:-padding] return result
# The following code is originally taken (with permission) from Mercurial
_b85alphabet = (b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" b"abcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~")_b85chars = None_b85chars2 = None_b85dec = None
def b85encode(b, pad=False): """Encode bytes-like object b in base85 format and return a bytes object.
If pad is true, the input is padded with b'\\0' so its length is a multiple of 4 bytes before encoding. """ global _b85chars, _b85chars2 # Delay the initialization of tables to not waste memory # if the function is never called if _b85chars2 is None: _b85chars = [bytes((i,)) for i in _b85alphabet] _b85chars2 = [(a + b) for a in _b85chars for b in _b85chars] return _85encode(b, _b85chars, _b85chars2, pad)
def b85decode(b): """Decode the base85-encoded bytes-like object or ASCII string b
The result is returned as a bytes object. """ global _b85dec # Delay the initialization of tables to not waste memory # if the function is never called if _b85dec is None: _b85dec = [None] * 256 for i, c in enumerate(_b85alphabet): _b85dec[c] = i
b = _bytes_from_decode_data(b) padding = (-len(b)) % 5 b = b + b'~' * padding out = [] packI = struct.Struct('!I').pack for i in range(0, len(b), 5): chunk = b[i:i + 5] acc = 0 try: for c in chunk: acc = acc * 85 + _b85dec[c] except TypeError: for j, c in enumerate(chunk): if _b85dec[c] is None: raise ValueError('bad base85 character at position %d' % (i + j)) from None raise try: out.append(packI(acc)) except struct.error: raise ValueError('base85 overflow in hunk starting at byte %d' % i) from None
result = b''.join(out) if padding: result = result[:-padding] return result
# Legacy interface. This code could be cleaned up since I don't believe# binascii has any line length limitations. It just doesn't seem worth it# though. The files should be opened in binary mode.
MAXLINESIZE = 76 # Excluding the CRLFMAXBINSIZE = (MAXLINESIZE//4)*3
def encode(input, output): """Encode a file; input and output are binary files.""" while True: s = input.read(MAXBINSIZE) if not s: break while len(s) < MAXBINSIZE: ns = input.read(MAXBINSIZE-len(s)) if not ns: break s += ns line = binascii.b2a_base64(s) output.write(line)
def decode(input, output): """Decode a file; input and output are binary files.""" while True: line = input.readline() if not line: break s = binascii.a2b_base64(line) output.write(s)
def _input_type_check(s): try: m = memoryview(s) except TypeError as err: msg = "expected bytes-like object, not %s" % s.__class__.__name__ raise TypeError(msg) from err if m.format not in ('c', 'b', 'B'): msg = ("expected single byte elements, not %r from %s" % (m.format, s.__class__.__name__)) raise TypeError(msg) if m.ndim != 1: msg = ("expected 1-D data, not %d-D data from %s" % (m.ndim, s.__class__.__name__)) raise TypeError(msg)
def encodebytes(s): """Encode a bytestring into a bytes object containing multiple lines of base-64 data.""" _input_type_check(s) pieces = [] for i in range(0, len(s), MAXBINSIZE): chunk = s[i : i + MAXBINSIZE] pieces.append(binascii.b2a_base64(chunk)) return b"".join(pieces)
def decodebytes(s): """Decode a bytestring of base-64 data into a bytes object.""" _input_type_check(s) return binascii.a2b_base64(s)
# Usable as a script...def main(): """Small main program""" import sys, getopt try: opts, args = getopt.getopt(sys.argv[1:], 'deut') except getopt.error as msg: sys.stdout = sys.stderr print(msg) print("""usage: %s [-d|-e|-u|-t] [file|-] -d, -u: decode -e: encode (default) -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]) sys.exit(2) func = encode for o, a in opts: if o == '-e': func = encode if o == '-d': func = decode if o == '-u': func = decode if o == '-t': test(); return if args and args[0] != '-': with open(args[0], 'rb') as f: func(f, sys.stdout.buffer) else: func(sys.stdin.buffer, sys.stdout.buffer)
def test(): s0 = b"Aladdin:open sesame" print(repr(s0)) s1 = encodebytes(s0) print(repr(s1)) s2 = decodebytes(s1) print(repr(s2)) assert s0 == s2
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891"""Debugger basics"""
import fnmatchimport sysimport osfrom inspect import CO_GENERATOR, CO_COROUTINE, CO_ASYNC_GENERATOR
__all__ = ["BdbQuit", "Bdb", "Breakpoint"]
GENERATOR_AND_COROUTINE_FLAGS = CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR
class BdbQuit(Exception): """Exception to give up completely."""
class Bdb: """Generic Python debugger base class.
This class takes care of details of the trace facility; a derived class should implement user interaction. The standard debugger class (pdb.Pdb) is an example.
The optional skip argument must be an iterable of glob-style module name patterns. The debugger will not step into frames that originate in a module that matches one of these patterns. Whether a frame is considered to originate in a certain module is determined by the __name__ in the frame globals. """
def __init__(self, skip=None): self.skip = set(skip) if skip else None self.breaks = {} self.fncache = {} self.frame_returning = None
self._load_breaks()
def canonic(self, filename): """Return canonical form of filename.
For real filenames, the canonical form is a case-normalized (on case insensitive filesystems) absolute path. 'Filenames' with angle brackets, such as "<stdin>", generated in interactive mode, are returned unchanged. """ if filename == "<" + filename[1:-1] + ">": return filename canonic = self.fncache.get(filename) if not canonic: canonic = os.path.abspath(filename) canonic = os.path.normcase(canonic) self.fncache[filename] = canonic return canonic
def reset(self): """Set values of attributes as ready to start debugging.""" import linecache linecache.checkcache() self.botframe = None self._set_stopinfo(None, None)
def trace_dispatch(self, frame, event, arg): """Dispatch a trace function for debugged frames based on the event.
This function is installed as the trace function for debugged frames. Its return value is the new trace function, which is usually itself. The default implementation decides how to dispatch a frame, depending on the type of event (passed in as a string) that is about to be executed.
The event can be one of the following: line: A new line of code is going to be executed. call: A function is about to be called or another code block is entered. return: A function or other code block is about to return. exception: An exception has occurred. c_call: A C function is about to be called. c_return: A C function has returned. c_exception: A C function has raised an exception.
For the Python events, specialized functions (see the dispatch_*() methods) are called. For the C events, no action is taken.
The arg parameter depends on the previous event. """ if self.quitting: return # None if event == 'line': return self.dispatch_line(frame) if event == 'call': return self.dispatch_call(frame, arg) if event == 'return': return self.dispatch_return(frame, arg) if event == 'exception': return self.dispatch_exception(frame, arg) if event == 'c_call': return self.trace_dispatch if event == 'c_exception': return self.trace_dispatch if event == 'c_return': return self.trace_dispatch print('bdb.Bdb.dispatch: unknown debugging event:', repr(event)) return self.trace_dispatch
def dispatch_line(self, frame): """Invoke user function and return trace function for line event.
If the debugger stops on the current line, invoke self.user_line(). Raise BdbQuit if self.quitting is set. Return self.trace_dispatch to continue tracing in this scope. """ if self.stop_here(frame) or self.break_here(frame): self.user_line(frame) if self.quitting: raise BdbQuit return self.trace_dispatch
def dispatch_call(self, frame, arg): """Invoke user function and return trace function for call event.
If the debugger stops on this function call, invoke self.user_call(). Raise BdbQuit if self.quitting is set. Return self.trace_dispatch to continue tracing in this scope. """ # XXX 'arg' is no longer used if self.botframe is None: # First call of dispatch since reset() self.botframe = frame.f_back # (CT) Note that this may also be None! return self.trace_dispatch if not (self.stop_here(frame) or self.break_anywhere(frame)): # No need to trace this function return # None # Ignore call events in generator except when stepping. if self.stopframe and frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS: return self.trace_dispatch self.user_call(frame, arg) if self.quitting: raise BdbQuit return self.trace_dispatch
def dispatch_return(self, frame, arg): """Invoke user function and return trace function for return event.
If the debugger stops on this function return, invoke self.user_return(). Raise BdbQuit if self.quitting is set. Return self.trace_dispatch to continue tracing in this scope. """ if self.stop_here(frame) or frame == self.returnframe: # Ignore return events in generator except when stepping. if self.stopframe and frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS: return self.trace_dispatch try: self.frame_returning = frame self.user_return(frame, arg) finally: self.frame_returning = None if self.quitting: raise BdbQuit # The user issued a 'next' or 'until' command. if self.stopframe is frame and self.stoplineno != -1: self._set_stopinfo(None, None) return self.trace_dispatch
def dispatch_exception(self, frame, arg): """Invoke user function and return trace function for exception event.
If the debugger stops on this exception, invoke self.user_exception(). Raise BdbQuit if self.quitting is set. Return self.trace_dispatch to continue tracing in this scope. """ if self.stop_here(frame): # When stepping with next/until/return in a generator frame, skip # the internal StopIteration exception (with no traceback) # triggered by a subiterator run with the 'yield from' statement. if not (frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS and arg[0] is StopIteration and arg[2] is None): self.user_exception(frame, arg) if self.quitting: raise BdbQuit # Stop at the StopIteration or GeneratorExit exception when the user # has set stopframe in a generator by issuing a return command, or a # next/until command at the last statement in the generator before the # exception. elif (self.stopframe and frame is not self.stopframe and self.stopframe.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS and arg[0] in (StopIteration, GeneratorExit)): self.user_exception(frame, arg) if self.quitting: raise BdbQuit
return self.trace_dispatch
# Normally derived classes don't override the following # methods, but they may if they want to redefine the # definition of stopping and breakpoints.
def is_skipped_module(self, module_name): "Return True if module_name matches any skip pattern." if module_name is None: # some modules do not have names return False for pattern in self.skip: if fnmatch.fnmatch(module_name, pattern): return True return False
def stop_here(self, frame): "Return True if frame is below the starting frame in the stack." # (CT) stopframe may now also be None, see dispatch_call. # (CT) the former test for None is therefore removed from here. if self.skip and \ self.is_skipped_module(frame.f_globals.get('__name__')): return False if frame is self.stopframe: if self.stoplineno == -1: return False return frame.f_lineno >= self.stoplineno if not self.stopframe: return True return False
def break_here(self, frame): """Return True if there is an effective breakpoint for this line.
Check for line or function breakpoint and if in effect. Delete temporary breakpoints if effective() says to. """ filename = self.canonic(frame.f_code.co_filename) if filename not in self.breaks: return False lineno = frame.f_lineno if lineno not in self.breaks[filename]: # The line itself has no breakpoint, but maybe the line is the # first line of a function with breakpoint set by function name. lineno = frame.f_code.co_firstlineno if lineno not in self.breaks[filename]: return False
# flag says ok to delete temp. bp (bp, flag) = effective(filename, lineno, frame) if bp: self.currentbp = bp.number if (flag and bp.temporary): self.do_clear(str(bp.number)) return True else: return False
def do_clear(self, arg): """Remove temporary breakpoint.
Must implement in derived classes or get NotImplementedError. """ raise NotImplementedError("subclass of bdb must implement do_clear()")
def break_anywhere(self, frame): """Return True if there is any breakpoint for frame's filename. """ return self.canonic(frame.f_code.co_filename) in self.breaks
# Derived classes should override the user_* methods # to gain control.
def user_call(self, frame, argument_list): """Called if we might stop in a function.""" pass
def user_line(self, frame): """Called when we stop or break at a line.""" pass
def user_return(self, frame, return_value): """Called when a return trap is set here.""" pass
def user_exception(self, frame, exc_info): """Called when we stop on an exception.""" pass
def _set_stopinfo(self, stopframe, returnframe, stoplineno=0): """Set the attributes for stopping.
If stoplineno is greater than or equal to 0, then stop at line greater than or equal to the stopline. If stoplineno is -1, then don't stop at all. """ self.stopframe = stopframe self.returnframe = returnframe self.quitting = False # stoplineno >= 0 means: stop at line >= the stoplineno # stoplineno -1 means: don't stop at all self.stoplineno = stoplineno
# Derived classes and clients can call the following methods # to affect the stepping state.
def set_until(self, frame, lineno=None): """Stop when the line with the lineno greater than the current one is reached or when returning from current frame.""" # the name "until" is borrowed from gdb if lineno is None: lineno = frame.f_lineno + 1 self._set_stopinfo(frame, frame, lineno)
def set_step(self): """Stop after one line of code.""" # Issue #13183: pdb skips frames after hitting a breakpoint and running # step commands. # Restore the trace function in the caller (that may not have been set # for performance reasons) when returning from the current frame. if self.frame_returning: caller_frame = self.frame_returning.f_back if caller_frame and not caller_frame.f_trace: caller_frame.f_trace = self.trace_dispatch self._set_stopinfo(None, None)
def set_next(self, frame): """Stop on the next line in or below the given frame.""" self._set_stopinfo(frame, None)
def set_return(self, frame): """Stop when returning from the given frame.""" if frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS: self._set_stopinfo(frame, None, -1) else: self._set_stopinfo(frame.f_back, frame)
def set_trace(self, frame=None): """Start debugging from frame.
If frame is not specified, debugging starts from caller's frame. """ if frame is None: frame = sys._getframe().f_back self.reset() while frame: frame.f_trace = self.trace_dispatch self.botframe = frame frame = frame.f_back self.set_step() sys.settrace(self.trace_dispatch)
def set_continue(self): """Stop only at breakpoints or when finished.
If there are no breakpoints, set the system trace function to None. """ # Don't stop except at breakpoints or when finished self._set_stopinfo(self.botframe, None, -1) if not self.breaks: # no breakpoints; run without debugger overhead sys.settrace(None) frame = sys._getframe().f_back while frame and frame is not self.botframe: del frame.f_trace frame = frame.f_back
def set_quit(self): """Set quitting attribute to True.
Raises BdbQuit exception in the next call to a dispatch_*() method. """ self.stopframe = self.botframe self.returnframe = None self.quitting = True sys.settrace(None)
# Derived classes and clients can call the following methods # to manipulate breakpoints. These methods return an # error message if something went wrong, None if all is well. # Set_break prints out the breakpoint line and file:lineno. # Call self.get_*break*() to see the breakpoints or better # for bp in Breakpoint.bpbynumber: if bp: bp.bpprint().
def _add_to_breaks(self, filename, lineno): """Add breakpoint to breaks, if not already there.""" bp_linenos = self.breaks.setdefault(filename, []) if lineno not in bp_linenos: bp_linenos.append(lineno)
def set_break(self, filename, lineno, temporary=False, cond=None, funcname=None): """Set a new breakpoint for filename:lineno.
If lineno doesn't exist for the filename, return an error message. The filename should be in canonical form. """ filename = self.canonic(filename) import linecache # Import as late as possible line = linecache.getline(filename, lineno) if not line: return 'Line %s:%d does not exist' % (filename, lineno) self._add_to_breaks(filename, lineno) bp = Breakpoint(filename, lineno, temporary, cond, funcname) return None
def _load_breaks(self): """Apply all breakpoints (set in other instances) to this one.
Populates this instance's breaks list from the Breakpoint class's list, which can have breakpoints set by another Bdb instance. This is necessary for interactive sessions to keep the breakpoints active across multiple calls to run(). """ for (filename, lineno) in Breakpoint.bplist.keys(): self._add_to_breaks(filename, lineno)
def _prune_breaks(self, filename, lineno): """Prune breakpoints for filename:lineno.
A list of breakpoints is maintained in the Bdb instance and in the Breakpoint class. If a breakpoint in the Bdb instance no longer exists in the Breakpoint class, then it's removed from the Bdb instance. """ if (filename, lineno) not in Breakpoint.bplist: self.breaks[filename].remove(lineno) if not self.breaks[filename]: del self.breaks[filename]
def clear_break(self, filename, lineno): """Delete breakpoints for filename:lineno.
If no breakpoints were set, return an error message. """ filename = self.canonic(filename) if filename not in self.breaks: return 'There are no breakpoints in %s' % filename if lineno not in self.breaks[filename]: return 'There is no breakpoint at %s:%d' % (filename, lineno) # If there's only one bp in the list for that file,line # pair, then remove the breaks entry for bp in Breakpoint.bplist[filename, lineno][:]: bp.deleteMe() self._prune_breaks(filename, lineno) return None
def clear_bpbynumber(self, arg): """Delete a breakpoint by its index in Breakpoint.bpbynumber.
If arg is invalid, return an error message. """ try: bp = self.get_bpbynumber(arg) except ValueError as err: return str(err) bp.deleteMe() self._prune_breaks(bp.file, bp.line) return None
def clear_all_file_breaks(self, filename): """Delete all breakpoints in filename.
If none were set, return an error message. """ filename = self.canonic(filename) if filename not in self.breaks: return 'There are no breakpoints in %s' % filename for line in self.breaks[filename]: blist = Breakpoint.bplist[filename, line] for bp in blist: bp.deleteMe() del self.breaks[filename] return None
def clear_all_breaks(self): """Delete all existing breakpoints.
If none were set, return an error message. """ if not self.breaks: return 'There are no breakpoints' for bp in Breakpoint.bpbynumber: if bp: bp.deleteMe() self.breaks = {} return None
def get_bpbynumber(self, arg): """Return a breakpoint by its index in Breakpoint.bybpnumber.
For invalid arg values or if the breakpoint doesn't exist, raise a ValueError. """ if not arg: raise ValueError('Breakpoint number expected') try: number = int(arg) except ValueError: raise ValueError('Non-numeric breakpoint number %s' % arg) from None try: bp = Breakpoint.bpbynumber[number] except IndexError: raise ValueError('Breakpoint number %d out of range' % number) from None if bp is None: raise ValueError('Breakpoint %d already deleted' % number) return bp
def get_break(self, filename, lineno): """Return True if there is a breakpoint for filename:lineno.""" filename = self.canonic(filename) return filename in self.breaks and \ lineno in self.breaks[filename]
def get_breaks(self, filename, lineno): """Return all breakpoints for filename:lineno.
If no breakpoints are set, return an empty list. """ filename = self.canonic(filename) return filename in self.breaks and \ lineno in self.breaks[filename] and \ Breakpoint.bplist[filename, lineno] or []
def get_file_breaks(self, filename): """Return all lines with breakpoints for filename.
If no breakpoints are set, return an empty list. """ filename = self.canonic(filename) if filename in self.breaks: return self.breaks[filename] else: return []
def get_all_breaks(self): """Return all breakpoints that are set.""" return self.breaks
# Derived classes and clients can call the following method # to get a data structure representing a stack trace.
def get_stack(self, f, t): """Return a list of (frame, lineno) in a stack trace and a size.
List starts with original calling frame, if there is one. Size may be number of frames above or below f. """ stack = [] if t and t.tb_frame is f: t = t.tb_next while f is not None: stack.append((f, f.f_lineno)) if f is self.botframe: break f = f.f_back stack.reverse() i = max(0, len(stack) - 1) while t is not None: stack.append((t.tb_frame, t.tb_lineno)) t = t.tb_next if f is None: i = max(0, len(stack) - 1) return stack, i
def format_stack_entry(self, frame_lineno, lprefix=': '): """Return a string with information about a stack entry.
The stack entry frame_lineno is a (frame, lineno) tuple. The return string contains the canonical filename, the function name or '<lambda>', the input arguments, the return value, and the line of code (if it exists).
""" import linecache, reprlib frame, lineno = frame_lineno filename = self.canonic(frame.f_code.co_filename) s = '%s(%r)' % (filename, lineno) if frame.f_code.co_name: s += frame.f_code.co_name else: s += "<lambda>" s += '()' if '__return__' in frame.f_locals: rv = frame.f_locals['__return__'] s += '->' s += reprlib.repr(rv) if lineno is not None: line = linecache.getline(filename, lineno, frame.f_globals) if line: s += lprefix + line.strip() return s
# The following methods can be called by clients to use # a debugger to debug a statement or an expression. # Both can be given as a string, or a code object.
def run(self, cmd, globals=None, locals=None): """Debug a statement executed via the exec() function.
globals defaults to __main__.dict; locals defaults to globals. """ if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals self.reset() if isinstance(cmd, str): cmd = compile(cmd, "<string>", "exec") sys.settrace(self.trace_dispatch) try: exec(cmd, globals, locals) except BdbQuit: pass finally: self.quitting = True sys.settrace(None)
def runeval(self, expr, globals=None, locals=None): """Debug an expression executed via the eval() function.
globals defaults to __main__.dict; locals defaults to globals. """ if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals self.reset() sys.settrace(self.trace_dispatch) try: return eval(expr, globals, locals) except BdbQuit: pass finally: self.quitting = True sys.settrace(None)
def runctx(self, cmd, globals, locals): """For backwards-compatibility. Defers to run().""" # B/W compatibility self.run(cmd, globals, locals)
# This method is more useful to debug a single function call.
def runcall(self, func, /, *args, **kwds): """Debug a single function call.
Return the result of the function call. """ self.reset() sys.settrace(self.trace_dispatch) res = None try: res = func(*args, **kwds) except BdbQuit: pass finally: self.quitting = True sys.settrace(None) return res
def set_trace(): """Start debugging with a Bdb instance from the caller's frame.""" Bdb().set_trace()
class Breakpoint: """Breakpoint class.
Implements temporary breakpoints, ignore counts, disabling and (re)-enabling, and conditionals.
Breakpoints are indexed by number through bpbynumber and by the (file, line) tuple using bplist. The former points to a single instance of class Breakpoint. The latter points to a list of such instances since there may be more than one breakpoint per line.
When creating a breakpoint, its associated filename should be in canonical form. If funcname is defined, a breakpoint hit will be counted when the first line of that function is executed. A conditional breakpoint always counts a hit. """
# XXX Keeping state in the class is a mistake -- this means # you cannot have more than one active Bdb instance.
next = 1 # Next bp to be assigned bplist = {} # indexed by (file, lineno) tuple bpbynumber = [None] # Each entry is None or an instance of Bpt # index 0 is unused, except for marking an # effective break .... see effective()
def __init__(self, file, line, temporary=False, cond=None, funcname=None): self.funcname = funcname # Needed if funcname is not None. self.func_first_executable_line = None self.file = file # This better be in canonical form! self.line = line self.temporary = temporary self.cond = cond self.enabled = True self.ignore = 0 self.hits = 0 self.number = Breakpoint.next Breakpoint.next += 1 # Build the two lists self.bpbynumber.append(self) if (file, line) in self.bplist: self.bplist[file, line].append(self) else: self.bplist[file, line] = [self]
@staticmethod def clearBreakpoints(): Breakpoint.next = 1 Breakpoint.bplist = {} Breakpoint.bpbynumber = [None]
def deleteMe(self): """Delete the breakpoint from the list associated to a file:line.
If it is the last breakpoint in that position, it also deletes the entry for the file:line. """
index = (self.file, self.line) self.bpbynumber[self.number] = None # No longer in list self.bplist[index].remove(self) if not self.bplist[index]: # No more bp for this f:l combo del self.bplist[index]
def enable(self): """Mark the breakpoint as enabled.""" self.enabled = True
def disable(self): """Mark the breakpoint as disabled.""" self.enabled = False
def bpprint(self, out=None): """Print the output of bpformat().
The optional out argument directs where the output is sent and defaults to standard output. """ if out is None: out = sys.stdout print(self.bpformat(), file=out)
def bpformat(self): """Return a string with information about the breakpoint.
The information includes the breakpoint number, temporary status, file:line position, break condition, number of times to ignore, and number of times hit.
""" if self.temporary: disp = 'del ' else: disp = 'keep ' if self.enabled: disp = disp + 'yes ' else: disp = disp + 'no ' ret = '%-4dbreakpoint %s at %s:%d' % (self.number, disp, self.file, self.line) if self.cond: ret += '\n\tstop only if %s' % (self.cond,) if self.ignore: ret += '\n\tignore next %d hits' % (self.ignore,) if self.hits: if self.hits > 1: ss = 's' else: ss = '' ret += '\n\tbreakpoint already hit %d time%s' % (self.hits, ss) return ret
def __str__(self): "Return a condensed description of the breakpoint." return 'breakpoint %s at %s:%s' % (self.number, self.file, self.line)
# -----------end of Breakpoint class----------
def checkfuncname(b, frame): """Return True if break should happen here.
Whether a break should happen depends on the way that b (the breakpoint) was set. If it was set via line number, check if b.line is the same as the one in the frame. If it was set via function name, check if this is the right function and if it is on the first executable line. """ if not b.funcname: # Breakpoint was set via line number. if b.line != frame.f_lineno: # Breakpoint was set at a line with a def statement and the function # defined is called: don't break. return False return True
# Breakpoint set via function name. if frame.f_code.co_name != b.funcname: # It's not a function call, but rather execution of def statement. return False
# We are in the right frame. if not b.func_first_executable_line: # The function is entered for the 1st time. b.func_first_executable_line = frame.f_lineno
if b.func_first_executable_line != frame.f_lineno: # But we are not at the first line number: don't break. return False return True
def effective(file, line, frame): """Return (active breakpoint, delete temporary flag) or (None, None) as breakpoint to act upon.
The "active breakpoint" is the first entry in bplist[line, file] (which must exist) that is enabled, for which checkfuncname is True, and that has neither a False condition nor a positive ignore count. The flag, meaning that a temporary breakpoint should be deleted, is False only when the condiion cannot be evaluated (in which case, ignore count is ignored).
If no such entry exists, then (None, None) is returned. """ possibles = Breakpoint.bplist[file, line] for b in possibles: if not b.enabled: continue if not checkfuncname(b, frame): continue # Count every hit when bp is enabled b.hits += 1 if not b.cond: # If unconditional, and ignoring go on to next, else break if b.ignore > 0: b.ignore -= 1 continue else: # breakpoint and marker that it's ok to delete if temporary return (b, True) else: # Conditional bp. # Ignore count applies only to those bpt hits where the # condition evaluates to true. try: val = eval(b.cond, frame.f_globals, frame.f_locals) if val: if b.ignore > 0: b.ignore -= 1 # continue else: return (b, True) # else: # continue except: # if eval fails, most conservative thing is to stop on # breakpoint regardless of ignore count. Don't delete # temporary, as another hint to user. return (b, False) return (None, None)
# -------------------- testing --------------------
class Tdb(Bdb): def user_call(self, frame, args): name = frame.f_code.co_name if not name: name = '???' print('+++ call', name, args) def user_line(self, frame): import linecache name = frame.f_code.co_name if not name: name = '???' fn = self.canonic(frame.f_code.co_filename) line = linecache.getline(fn, frame.f_lineno, frame.f_globals) print('+++', fn, frame.f_lineno, name, ':', line.strip()) def user_return(self, frame, retval): print('+++ return', retval) def user_exception(self, frame, exc_stuff): print('+++ exception', exc_stuff) self.set_continue()
def foo(n): print('foo(', n, ')') x = bar(n*10) print('bar returned', x)
def bar(a): print('bar(', a, ')') return a/2
def test(): t = Tdb() t.run('import bdb; bdb.foo(10)')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502"""Macintosh binhex compression/decompression.
easy interface:binhex(inputfilename, outputfilename)hexbin(inputfilename, outputfilename)"""
## Jack Jansen, CWI, August 1995.## The module is supposed to be as compatible as possible. Especially the# easy interface should work "as expected" on any platform.# XXXX Note: currently, textfiles appear in mac-form on all platforms.# We seem to lack a simple character-translate in python.# (we should probably use ISO-Latin-1 on all but the mac platform).# XXXX The simple routines are too simple: they expect to hold the complete# files in-core. Should be fixed.# XXXX It would be nice to handle AppleDouble format on unix# (for servers serving macs).# XXXX I don't understand what happens when you get 0x90 times the same byte on# input. The resulting code (xx 90 90) would appear to be interpreted as an# escaped *value* of 0x90. All coders I've seen appear to ignore this nicety...#import binasciiimport contextlibimport ioimport osimport structimport warnings
warnings.warn('the binhex module is deprecated', DeprecationWarning, stacklevel=2)
__all__ = ["binhex","hexbin","Error"]
class Error(Exception): pass
# States (what have we written)_DID_HEADER = 0_DID_DATA = 1
# Various constantsREASONABLY_LARGE = 32768 # Minimal amount we pass the rle-coderLINELEN = 64RUNCHAR = b"\x90"
## This code is no longer byte-order dependent
class FInfo: def __init__(self): self.Type = '????' self.Creator = '????' self.Flags = 0
def getfileinfo(name): finfo = FInfo() with io.open(name, 'rb') as fp: # Quick check for textfile data = fp.read(512) if 0 not in data: finfo.Type = 'TEXT' fp.seek(0, 2) dsize = fp.tell() dir, file = os.path.split(name) file = file.replace(':', '-', 1) return file, finfo, dsize, 0
class openrsrc: def __init__(self, *args): pass
def read(self, *args): return b''
def write(self, *args): pass
def close(self): pass
# DeprecationWarning is already emitted on "import binhex". There is no need# to repeat the warning at each call to deprecated binascii functions.@contextlib.contextmanagerdef _ignore_deprecation_warning(): with warnings.catch_warnings(): warnings.filterwarnings('ignore', '', DeprecationWarning) yield
class _Hqxcoderengine: """Write data to the coder in 3-byte chunks"""
def __init__(self, ofp): self.ofp = ofp self.data = b'' self.hqxdata = b'' self.linelen = LINELEN - 1
def write(self, data): self.data = self.data + data datalen = len(self.data) todo = (datalen // 3) * 3 data = self.data[:todo] self.data = self.data[todo:] if not data: return with _ignore_deprecation_warning(): self.hqxdata = self.hqxdata + binascii.b2a_hqx(data) self._flush(0)
def _flush(self, force): first = 0 while first <= len(self.hqxdata) - self.linelen: last = first + self.linelen self.ofp.write(self.hqxdata[first:last] + b'\r') self.linelen = LINELEN first = last self.hqxdata = self.hqxdata[first:] if force: self.ofp.write(self.hqxdata + b':\r')
def close(self): if self.data: with _ignore_deprecation_warning(): self.hqxdata = self.hqxdata + binascii.b2a_hqx(self.data) self._flush(1) self.ofp.close() del self.ofp
class _Rlecoderengine: """Write data to the RLE-coder in suitably large chunks"""
def __init__(self, ofp): self.ofp = ofp self.data = b''
def write(self, data): self.data = self.data + data if len(self.data) < REASONABLY_LARGE: return with _ignore_deprecation_warning(): rledata = binascii.rlecode_hqx(self.data) self.ofp.write(rledata) self.data = b''
def close(self): if self.data: with _ignore_deprecation_warning(): rledata = binascii.rlecode_hqx(self.data) self.ofp.write(rledata) self.ofp.close() del self.ofp
class BinHex: def __init__(self, name_finfo_dlen_rlen, ofp): name, finfo, dlen, rlen = name_finfo_dlen_rlen close_on_error = False if isinstance(ofp, str): ofname = ofp ofp = io.open(ofname, 'wb') close_on_error = True try: ofp.write(b'(This file must be converted with BinHex 4.0)\r\r:') hqxer = _Hqxcoderengine(ofp) self.ofp = _Rlecoderengine(hqxer) self.crc = 0 if finfo is None: finfo = FInfo() self.dlen = dlen self.rlen = rlen self._writeinfo(name, finfo) self.state = _DID_HEADER except: if close_on_error: ofp.close() raise
def _writeinfo(self, name, finfo): nl = len(name) if nl > 63: raise Error('Filename too long') d = bytes([nl]) + name.encode("latin-1") + b'\0' tp, cr = finfo.Type, finfo.Creator if isinstance(tp, str): tp = tp.encode("latin-1") if isinstance(cr, str): cr = cr.encode("latin-1") d2 = tp + cr
# Force all structs to be packed with big-endian d3 = struct.pack('>h', finfo.Flags) d4 = struct.pack('>ii', self.dlen, self.rlen) info = d + d2 + d3 + d4 self._write(info) self._writecrc()
def _write(self, data): self.crc = binascii.crc_hqx(data, self.crc) self.ofp.write(data)
def _writecrc(self): # XXXX Should this be here?? # self.crc = binascii.crc_hqx('\0\0', self.crc) if self.crc < 0: fmt = '>h' else: fmt = '>H' self.ofp.write(struct.pack(fmt, self.crc)) self.crc = 0
def write(self, data): if self.state != _DID_HEADER: raise Error('Writing data at the wrong time') self.dlen = self.dlen - len(data) self._write(data)
def close_data(self): if self.dlen != 0: raise Error('Incorrect data size, diff=%r' % (self.rlen,)) self._writecrc() self.state = _DID_DATA
def write_rsrc(self, data): if self.state < _DID_DATA: self.close_data() if self.state != _DID_DATA: raise Error('Writing resource data at the wrong time') self.rlen = self.rlen - len(data) self._write(data)
def close(self): if self.state is None: return try: if self.state < _DID_DATA: self.close_data() if self.state != _DID_DATA: raise Error('Close at the wrong time') if self.rlen != 0: raise Error("Incorrect resource-datasize, diff=%r" % (self.rlen,)) self._writecrc() finally: self.state = None ofp = self.ofp del self.ofp ofp.close()
def binhex(inp, out): """binhex(infilename, outfilename): create binhex-encoded copy of a file""" finfo = getfileinfo(inp) ofp = BinHex(finfo, out)
with io.open(inp, 'rb') as ifp: # XXXX Do textfile translation on non-mac systems while True: d = ifp.read(128000) if not d: break ofp.write(d) ofp.close_data()
ifp = openrsrc(inp, 'rb') while True: d = ifp.read(128000) if not d: break ofp.write_rsrc(d) ofp.close() ifp.close()
class _Hqxdecoderengine: """Read data via the decoder in 4-byte chunks"""
def __init__(self, ifp): self.ifp = ifp self.eof = 0
def read(self, totalwtd): """Read at least wtd bytes (or until EOF)""" decdata = b'' wtd = totalwtd # # The loop here is convoluted, since we don't really now how # much to decode: there may be newlines in the incoming data. while wtd > 0: if self.eof: return decdata wtd = ((wtd + 2) // 3) * 4 data = self.ifp.read(wtd) # # Next problem: there may not be a complete number of # bytes in what we pass to a2b. Solve by yet another # loop. # while True: try: with _ignore_deprecation_warning(): decdatacur, self.eof = binascii.a2b_hqx(data) break except binascii.Incomplete: pass newdata = self.ifp.read(1) if not newdata: raise Error('Premature EOF on binhex file') data = data + newdata decdata = decdata + decdatacur wtd = totalwtd - len(decdata) if not decdata and not self.eof: raise Error('Premature EOF on binhex file') return decdata
def close(self): self.ifp.close()
class _Rledecoderengine: """Read data via the RLE-coder"""
def __init__(self, ifp): self.ifp = ifp self.pre_buffer = b'' self.post_buffer = b'' self.eof = 0
def read(self, wtd): if wtd > len(self.post_buffer): self._fill(wtd - len(self.post_buffer)) rv = self.post_buffer[:wtd] self.post_buffer = self.post_buffer[wtd:] return rv
def _fill(self, wtd): self.pre_buffer = self.pre_buffer + self.ifp.read(wtd + 4) if self.ifp.eof: with _ignore_deprecation_warning(): self.post_buffer = self.post_buffer + \ binascii.rledecode_hqx(self.pre_buffer) self.pre_buffer = b'' return
# # Obfuscated code ahead. We have to take care that we don't # end up with an orphaned RUNCHAR later on. So, we keep a couple # of bytes in the buffer, depending on what the end of # the buffer looks like: # '\220\0\220' - Keep 3 bytes: repeated \220 (escaped as \220\0) # '?\220' - Keep 2 bytes: repeated something-else # '\220\0' - Escaped \220: Keep 2 bytes. # '?\220?' - Complete repeat sequence: decode all # otherwise: keep 1 byte. # mark = len(self.pre_buffer) if self.pre_buffer[-3:] == RUNCHAR + b'\0' + RUNCHAR: mark = mark - 3 elif self.pre_buffer[-1:] == RUNCHAR: mark = mark - 2 elif self.pre_buffer[-2:] == RUNCHAR + b'\0': mark = mark - 2 elif self.pre_buffer[-2:-1] == RUNCHAR: pass # Decode all else: mark = mark - 1
with _ignore_deprecation_warning(): self.post_buffer = self.post_buffer + \ binascii.rledecode_hqx(self.pre_buffer[:mark]) self.pre_buffer = self.pre_buffer[mark:]
def close(self): self.ifp.close()
class HexBin: def __init__(self, ifp): if isinstance(ifp, str): ifp = io.open(ifp, 'rb') # # Find initial colon. # while True: ch = ifp.read(1) if not ch: raise Error("No binhex data found") # Cater for \r\n terminated lines (which show up as \n\r, hence # all lines start with \r) if ch == b'\r': continue if ch == b':': break
hqxifp = _Hqxdecoderengine(ifp) self.ifp = _Rledecoderengine(hqxifp) self.crc = 0 self._readheader()
def _read(self, len): data = self.ifp.read(len) self.crc = binascii.crc_hqx(data, self.crc) return data
def _checkcrc(self): filecrc = struct.unpack('>h', self.ifp.read(2))[0] & 0xffff #self.crc = binascii.crc_hqx('\0\0', self.crc) # XXXX Is this needed?? self.crc = self.crc & 0xffff if filecrc != self.crc: raise Error('CRC error, computed %x, read %x' % (self.crc, filecrc)) self.crc = 0
def _readheader(self): len = self._read(1) fname = self._read(ord(len)) rest = self._read(1 + 4 + 4 + 2 + 4 + 4) self._checkcrc()
type = rest[1:5] creator = rest[5:9] flags = struct.unpack('>h', rest[9:11])[0] self.dlen = struct.unpack('>l', rest[11:15])[0] self.rlen = struct.unpack('>l', rest[15:19])[0]
self.FName = fname self.FInfo = FInfo() self.FInfo.Creator = creator self.FInfo.Type = type self.FInfo.Flags = flags
self.state = _DID_HEADER
def read(self, *n): if self.state != _DID_HEADER: raise Error('Read data at wrong time') if n: n = n[0] n = min(n, self.dlen) else: n = self.dlen rv = b'' while len(rv) < n: rv = rv + self._read(n-len(rv)) self.dlen = self.dlen - n return rv
def close_data(self): if self.state != _DID_HEADER: raise Error('close_data at wrong time') if self.dlen: dummy = self._read(self.dlen) self._checkcrc() self.state = _DID_DATA
def read_rsrc(self, *n): if self.state == _DID_HEADER: self.close_data() if self.state != _DID_DATA: raise Error('Read resource data at wrong time') if n: n = n[0] n = min(n, self.rlen) else: n = self.rlen self.rlen = self.rlen - n return self._read(n)
def close(self): if self.state is None: return try: if self.rlen: dummy = self.read_rsrc(self.rlen) self._checkcrc() finally: self.state = None self.ifp.close()
def hexbin(inp, out): """hexbin(infilename, outfilename) - Decode binhexed file""" ifp = HexBin(inp) finfo = ifp.FInfo if not out: out = ifp.FName
with io.open(out, 'wb') as ofp: # XXXX Do translation on non-mac systems while True: d = ifp.read(128000) if not d: break ofp.write(d) ifp.close_data()
d = ifp.read_rsrc(128000) if d: ofp = openrsrc(out, 'wb') ofp.write(d) while True: d = ifp.read_rsrc(128000) if not d: break ofp.write(d) ofp.close()
ifp.close()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110"""Bisection algorithms."""
def insort_right(a, x, lo=0, hi=None, *, key=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 key is None: lo = bisect_right(a, x, lo, hi) else: lo = bisect_right(a, key(x), lo, hi, key=key) a.insert(lo, x)
def bisect_right(a, x, lo=0, hi=None, *, key=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, a.insert(i, x) will insert just after the rightmost x already there.
Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. """
if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) # Note, the comparison uses "<" to match the # __lt__() logic in list.sort() and in heapq. if key is None: while lo < hi: mid = (lo + hi) // 2 if x < a[mid]: hi = mid else: lo = mid + 1 else: while lo < hi: mid = (lo + hi) // 2 if x < key(a[mid]): hi = mid else: lo = mid + 1 return lo
def insort_left(a, x, lo=0, hi=None, *, key=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 key is None: lo = bisect_left(a, x, lo, hi) else: lo = bisect_left(a, key(x), lo, hi, key=key) a.insert(lo, x)
def bisect_left(a, x, lo=0, hi=None, *, key=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, a.insert(i, x) will insert 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 lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) # Note, the comparison uses "<" to match the # __lt__() logic in list.sort() and in heapq. if key is None: while lo < hi: mid = (lo + hi) // 2 if a[mid] < x: lo = mid + 1 else: hi = mid else: while lo < hi: mid = (lo + hi) // 2 if key(a[mid]) < x: lo = mid + 1 else: hi = mid return lo
# Overwrite above definitions with a fast C implementationtry: from _bisect import *except ImportError: pass
# Create aliasesbisect = bisect_rightinsort = insort_right123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344"""Interface to the libbzip2 compression library.
This module provides a file interface, classes for incremental(de)compression, and functions for one-shot (de)compression."""
__all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor", "open", "compress", "decompress"]
__author__ = "Nadeem Vawda <nadeem.vawda@gmail.com>"
from builtins import open as _builtin_openimport ioimport osimport _compression
from _bz2 import BZ2Compressor, BZ2Decompressor
_MODE_CLOSED = 0_MODE_READ = 1# Value 2 no longer used_MODE_WRITE = 3
class BZ2File(_compression.BaseStream):
"""A file object providing transparent bzip2 (de)compression.
A BZ2File can act as a wrapper for an existing file object, or refer directly to a named file on disk.
Note that BZ2File provides a *binary* file interface - data read is returned as bytes, and data to be written should be given as bytes. """
def __init__(self, filename, mode="r", *, compresslevel=9): """Open a bzip2-compressed file.
If filename is a str, bytes, or PathLike object, it gives the name of the file to be opened. Otherwise, it should be a file object, which will be used to read or write the compressed data.
mode can be 'r' for reading (default), 'w' for (over)writing, 'x' for creating exclusively, or 'a' for appending. These can equivalently be given as 'rb', 'wb', 'xb', and 'ab'.
If mode is 'w', 'x' or 'a', compresslevel can be a number between 1 and 9 specifying the level of compression: 1 produces the least compression, and 9 (default) produces the most compression.
If mode is 'r', the input file may be the concatenation of multiple compressed streams. """ self._fp = None self._closefp = False self._mode = _MODE_CLOSED
if not (1 <= compresslevel <= 9): raise ValueError("compresslevel must be between 1 and 9")
if mode in ("", "r", "rb"): mode = "rb" mode_code = _MODE_READ elif mode in ("w", "wb"): mode = "wb" mode_code = _MODE_WRITE self._compressor = BZ2Compressor(compresslevel) elif mode in ("x", "xb"): mode = "xb" mode_code = _MODE_WRITE self._compressor = BZ2Compressor(compresslevel) elif mode in ("a", "ab"): mode = "ab" mode_code = _MODE_WRITE self._compressor = BZ2Compressor(compresslevel) else: raise ValueError("Invalid mode: %r" % (mode,))
if isinstance(filename, (str, bytes, os.PathLike)): self._fp = _builtin_open(filename, mode) self._closefp = True self._mode = mode_code elif hasattr(filename, "read") or hasattr(filename, "write"): self._fp = filename self._mode = mode_code else: raise TypeError("filename must be a str, bytes, file or PathLike object")
if self._mode == _MODE_READ: raw = _compression.DecompressReader(self._fp, BZ2Decompressor, trailing_error=OSError) self._buffer = io.BufferedReader(raw) else: self._pos = 0
def close(self): """Flush and close the file.
May be called more than once without error. Once the file is closed, any other operation on it will raise a ValueError. """ if self._mode == _MODE_CLOSED: return try: if self._mode == _MODE_READ: self._buffer.close() elif self._mode == _MODE_WRITE: self._fp.write(self._compressor.flush()) self._compressor = None finally: try: if self._closefp: self._fp.close() finally: self._fp = None self._closefp = False self._mode = _MODE_CLOSED self._buffer = None
@property def closed(self): """True if this file is closed.""" return self._mode == _MODE_CLOSED
def fileno(self): """Return the file descriptor for the underlying file.""" self._check_not_closed() return self._fp.fileno()
def seekable(self): """Return whether the file supports seeking.""" return self.readable() and self._buffer.seekable()
def readable(self): """Return whether the file was opened for reading.""" self._check_not_closed() return self._mode == _MODE_READ
def writable(self): """Return whether the file was opened for writing.""" self._check_not_closed() return self._mode == _MODE_WRITE
def peek(self, n=0): """Return buffered data without advancing the file position.
Always returns at least one byte of data, unless at EOF. The exact number of bytes returned is unspecified. """ self._check_can_read() # Relies on the undocumented fact that BufferedReader.peek() # always returns at least one byte (except at EOF), independent # of the value of n return self._buffer.peek(n)
def read(self, size=-1): """Read up to size uncompressed bytes from the file.
If size is negative or omitted, read until EOF is reached. Returns b'' if the file is already at EOF. """ self._check_can_read() return self._buffer.read(size)
def read1(self, size=-1): """Read up to size uncompressed bytes, while trying to avoid making multiple reads from the underlying stream. Reads up to a buffer's worth of data if size is negative.
Returns b'' if the file is at EOF. """ self._check_can_read() if size < 0: size = io.DEFAULT_BUFFER_SIZE return self._buffer.read1(size)
def readinto(self, b): """Read bytes into b.
Returns the number of bytes read (0 for EOF). """ self._check_can_read() return self._buffer.readinto(b)
def readline(self, size=-1): """Read a line of uncompressed bytes from the file.
The terminating newline (if present) is retained. If size is non-negative, no more than size bytes will be read (in which case the line may be incomplete). Returns b'' if already at EOF. """ if not isinstance(size, int): if not hasattr(size, "__index__"): raise TypeError("Integer argument expected") size = size.__index__() self._check_can_read() return self._buffer.readline(size)
def readlines(self, size=-1): """Read a list of lines of uncompressed bytes from the file.
size can be specified to control the number of lines read: no further lines will be read once the total size of the lines read so far equals or exceeds size. """ if not isinstance(size, int): if not hasattr(size, "__index__"): raise TypeError("Integer argument expected") size = size.__index__() self._check_can_read() return self._buffer.readlines(size)
def write(self, data): """Write a byte string to the file.
Returns the number of uncompressed bytes written, which is always the length of data in bytes. Note that due to buffering, the file on disk may not reflect the data written until close() is called. """ self._check_can_write() if isinstance(data, (bytes, bytearray)): length = len(data) else: # accept any data that supports the buffer protocol data = memoryview(data) length = data.nbytes
compressed = self._compressor.compress(data) self._fp.write(compressed) self._pos += length return length
def writelines(self, seq): """Write a sequence of byte strings to the file.
Returns the number of uncompressed bytes written. seq can be any iterable yielding byte strings.
Line separators are not added between the written byte strings. """ return _compression.BaseStream.writelines(self, seq)
def seek(self, offset, whence=io.SEEK_SET): """Change the file position.
The new position is specified by offset, relative to the position indicated by whence. Values for whence are:
0: start of stream (default); offset must not be negative 1: current stream position 2: end of stream; offset must not be positive
Returns the new file position.
Note that seeking is emulated, so depending on the parameters, this operation may be extremely slow. """ self._check_can_seek() return self._buffer.seek(offset, whence)
def tell(self): """Return the current file position.""" self._check_not_closed() if self._mode == _MODE_READ: return self._buffer.tell() return self._pos
def open(filename, mode="rb", compresslevel=9, encoding=None, errors=None, newline=None): """Open a bzip2-compressed file in binary or text mode.
The filename argument can be an actual filename (a str, bytes, or PathLike object), or an existing file object to read from or write to.
The mode argument can be "r", "rb", "w", "wb", "x", "xb", "a" or "ab" for binary mode, or "rt", "wt", "xt" or "at" for text mode. The default mode is "rb", and the default compresslevel is 9.
For binary mode, this function is equivalent to the BZ2File constructor: BZ2File(filename, mode, compresslevel). In this case, the encoding, errors and newline arguments must not be provided.
For text mode, a BZ2File object is created, and wrapped in an io.TextIOWrapper instance with the specified encoding, error handling behavior, and line ending(s).
""" if "t" in mode: if "b" in mode: raise ValueError("Invalid mode: %r" % (mode,)) else: if encoding is not None: raise ValueError("Argument 'encoding' not supported in binary mode") if errors is not None: raise ValueError("Argument 'errors' not supported in binary mode") if newline is not None: raise ValueError("Argument 'newline' not supported in binary mode")
bz_mode = mode.replace("t", "") binary_file = BZ2File(filename, bz_mode, compresslevel=compresslevel)
if "t" in mode: encoding = io.text_encoding(encoding) return io.TextIOWrapper(binary_file, encoding, errors, newline) else: return binary_file
def compress(data, compresslevel=9): """Compress a block of data.
compresslevel, if given, must be a number between 1 and 9.
For incremental compression, use a BZ2Compressor object instead. """ comp = BZ2Compressor(compresslevel) return comp.compress(data) + comp.flush()
def decompress(data): """Decompress a block of data.
For incremental decompression, use a BZ2Decompressor object instead. """ results = [] while data: decomp = BZ2Decompressor() try: res = decomp.decompress(data) except OSError: if results: break # Leftover data is not a valid bzip2 stream; ignore it. else: raise # Error on the first iteration; bail out. results.append(res) if not decomp.eof: raise ValueError("Compressed data ended before the " "end-of-stream marker was reached") data = decomp.unused_data return b"".join(results)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190#! /usr/bin/env python3
"""Python interface for the 'lsprof' profiler. Compatible with the 'profile' module."""
__all__ = ["run", "runctx", "Profile"]
import _lsprofimport profile as _pyprofile
# ____________________________________________________________# Simple interface
def run(statement, filename=None, sort=-1): return _pyprofile._Utils(Profile).run(statement, filename, sort)
def runctx(statement, globals, locals, filename=None, sort=-1): return _pyprofile._Utils(Profile).runctx(statement, globals, locals, filename, sort)
run.__doc__ = _pyprofile.run.__doc__runctx.__doc__ = _pyprofile.runctx.__doc__
# ____________________________________________________________
class Profile(_lsprof.Profiler): """Profile(timer=None, timeunit=None, subcalls=True, builtins=True)
Builds a profiler object using the specified timer function. The default timer is a fast built-in one based on real time. For custom timer functions returning integers, timeunit can be a float specifying a scale (i.e. how long each integer unit is, in seconds). """
# Most of the functionality is in the base class. # This subclass only adds convenient and backward-compatible methods.
def print_stats(self, sort=-1): import pstats pstats.Stats(self).strip_dirs().sort_stats(sort).print_stats()
def dump_stats(self, file): import marshal with open(file, 'wb') as f: self.create_stats() marshal.dump(self.stats, f)
def create_stats(self): self.disable() self.snapshot_stats()
def snapshot_stats(self): entries = self.getstats() self.stats = {} callersdicts = {} # call information for entry in entries: func = label(entry.code) nc = entry.callcount # ncalls column of pstats (before '/') cc = nc - entry.reccallcount # ncalls column of pstats (after '/') tt = entry.inlinetime # tottime column of pstats ct = entry.totaltime # cumtime column of pstats callers = {} callersdicts[id(entry.code)] = callers self.stats[func] = cc, nc, tt, ct, callers # subcall information for entry in entries: if entry.calls: func = label(entry.code) for subentry in entry.calls: try: callers = callersdicts[id(subentry.code)] except KeyError: continue nc = subentry.callcount cc = nc - subentry.reccallcount tt = subentry.inlinetime ct = subentry.totaltime if func in callers: prev = callers[func] nc += prev[0] cc += prev[1] tt += prev[2] ct += prev[3] callers[func] = nc, cc, tt, ct
# The following two methods can be called by clients to use # a profiler to profile a statement, given as a string.
def run(self, cmd): import __main__ dict = __main__.__dict__ return self.runctx(cmd, dict, dict)
def runctx(self, cmd, globals, locals): self.enable() try: exec(cmd, globals, locals) finally: self.disable() return self
# This method is more useful to profile a single function call. def runcall(self, func, /, *args, **kw): self.enable() try: return func(*args, **kw) finally: self.disable()
def __enter__(self): self.enable() return self
def __exit__(self, *exc_info): self.disable()
# ____________________________________________________________
def label(code): if isinstance(code, str): return ('~', 0, code) # built-in functions ('~' sorts at the end) else: return (code.co_filename, code.co_firstlineno, code.co_name)
# ____________________________________________________________
def main(): import os import sys import runpy import pstats from optparse import OptionParser usage = "cProfile.py [-o output_file_path] [-s sort] [-m module | scriptfile] [arg] ..." parser = OptionParser(usage=usage) parser.allow_interspersed_args = False parser.add_option('-o', '--outfile', dest="outfile", help="Save stats to <outfile>", default=None) parser.add_option('-s', '--sort', dest="sort", help="Sort order when printing to stdout, based on pstats.Stats class", default=-1, choices=sorted(pstats.Stats.sort_arg_dict_default)) parser.add_option('-m', dest="module", action="store_true", help="Profile a library module", default=False)
if not sys.argv[1:]: parser.print_usage() sys.exit(2)
(options, args) = parser.parse_args() sys.argv[:] = args
# The script that we're profiling may chdir, so capture the absolute path # to the output file at startup. if options.outfile is not None: options.outfile = os.path.abspath(options.outfile)
if len(args) > 0: if options.module: code = "run_module(modname, run_name='__main__')" globs = { 'run_module': runpy.run_module, 'modname': args[0] } else: progname = args[0] sys.path.insert(0, os.path.dirname(progname)) with open(progname, 'rb') as fp: code = compile(fp.read(), progname, 'exec') globs = { '__file__': progname, '__name__': '__main__', '__package__': None, '__cached__': None, } try: runctx(code, globs, None, options.outfile, options.sort) except BrokenPipeError as exc: # Prevent "Exception ignored" during interpreter shutdown. sys.stdout = None sys.exit(exc.errno) else: parser.print_usage() return parser
# When invoked as main program, invoke the profiler on a scriptif __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759"""Calendar printing functions
Note when comparing these calendars to the ones printed by cal(1): Bydefault, these calendars have Monday as the first day of the week, andSunday as the last (the European convention). Use setfirstweekday() toset the first day of the week (0=Monday, 6=Sunday)."""
import sysimport datetimeimport locale as _localefrom itertools import repeat
__all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday", "firstweekday", "isleap", "leapdays", "weekday", "monthrange", "monthcalendar", "prmonth", "month", "prcal", "calendar", "timegm", "month_name", "month_abbr", "day_name", "day_abbr", "Calendar", "TextCalendar", "HTMLCalendar", "LocaleTextCalendar", "LocaleHTMLCalendar", "weekheader", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"]
# Exception raised for bad input (with string parameter for details)error = ValueError
# Exceptions raised for bad inputclass IllegalMonthError(ValueError): def __init__(self, month): self.month = month def __str__(self): return "bad month number %r; must be 1-12" % self.month
class IllegalWeekdayError(ValueError): def __init__(self, weekday): self.weekday = weekday def __str__(self): return "bad weekday number %r; must be 0 (Monday) to 6 (Sunday)" % self.weekday
# Constants for months referenced laterJanuary = 1February = 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 weekdaysday_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)
def isleap(year): """Return True for leap years, False 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, month (1-12), day (1-31).""" if not datetime.MINYEAR <= year <= datetime.MAXYEAR: year = 2000 + year % 400 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 IllegalMonthError(month) day1 = weekday(year, month, 1) ndays = mdays[month] + (month == February and isleap(year)) return day1, ndays
def _monthlen(year, month): return mdays[month] + (month == February and isleap(year))
def _prevmonth(year, month): if month == 1: return year-1, 12 else: return year, month-1
def _nextmonth(year, month): if month == 12: return year+1, 1 else: return year, month+1
class Calendar(object): """ Base calendar class. This class doesn't do any formatting. It simply provides data to subclasses. """
def __init__(self, firstweekday=0): self.firstweekday = firstweekday # 0 = Monday, 6 = Sunday
def getfirstweekday(self): return self._firstweekday % 7
def setfirstweekday(self, firstweekday): self._firstweekday = firstweekday
firstweekday = property(getfirstweekday, setfirstweekday)
def iterweekdays(self): """ Return an iterator for one week of weekday numbers starting with the configured first one. """ for i in range(self.firstweekday, self.firstweekday + 7): yield i%7
def itermonthdates(self, year, month): """ Return an iterator for one month. The iterator will yield datetime.date values and will always iterate through complete weeks, so it will yield dates outside the specified month. """ for y, m, d in self.itermonthdays3(year, month): yield datetime.date(y, m, d)
def itermonthdays(self, year, month): """ Like itermonthdates(), but will yield day numbers. For days outside the specified month the day number is 0. """ day1, ndays = monthrange(year, month) days_before = (day1 - self.firstweekday) % 7 yield from repeat(0, days_before) yield from range(1, ndays + 1) days_after = (self.firstweekday - day1 - ndays) % 7 yield from repeat(0, days_after)
def itermonthdays2(self, year, month): """ Like itermonthdates(), but will yield (day number, weekday number) tuples. For days outside the specified month the day number is 0. """ for i, d in enumerate(self.itermonthdays(year, month), self.firstweekday): yield d, i % 7
def itermonthdays3(self, year, month): """ Like itermonthdates(), but will yield (year, month, day) tuples. Can be used for dates outside of datetime.date range. """ day1, ndays = monthrange(year, month) days_before = (day1 - self.firstweekday) % 7 days_after = (self.firstweekday - day1 - ndays) % 7 y, m = _prevmonth(year, month) end = _monthlen(y, m) + 1 for d in range(end-days_before, end): yield y, m, d for d in range(1, ndays + 1): yield year, month, d y, m = _nextmonth(year, month) for d in range(1, days_after + 1): yield y, m, d
def itermonthdays4(self, year, month): """ Like itermonthdates(), but will yield (year, month, day, day_of_week) tuples. Can be used for dates outside of datetime.date range. """ for i, (y, m, d) in enumerate(self.itermonthdays3(year, month)): yield y, m, d, (self.firstweekday + i) % 7
def monthdatescalendar(self, year, month): """ Return a matrix (list of lists) representing a month's calendar. Each row represents a week; week entries are datetime.date values. """ dates = list(self.itermonthdates(year, month)) return [ dates[i:i+7] for i in range(0, len(dates), 7) ]
def monthdays2calendar(self, year, month): """ Return a matrix representing a month's calendar. Each row represents a week; week entries are (day number, weekday number) tuples. Day numbers outside this month are zero. """ days = list(self.itermonthdays2(year, month)) return [ days[i:i+7] for i in range(0, len(days), 7) ]
def monthdayscalendar(self, year, month): """ Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero. """ days = list(self.itermonthdays(year, month)) return [ days[i:i+7] for i in range(0, len(days), 7) ]
def yeardatescalendar(self, year, width=3): """ Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months. Each month contains between 4 and 6 weeks and each week contains 1-7 days. Days are datetime.date objects. """ months = [ self.monthdatescalendar(year, i) for i in range(January, January+12) ] return [months[i:i+width] for i in range(0, len(months), width) ]
def yeardays2calendar(self, year, width=3): """ Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are (day number, weekday number) tuples. Day numbers outside this month are zero. """ months = [ self.monthdays2calendar(year, i) for i in range(January, January+12) ] return [months[i:i+width] for i in range(0, len(months), width) ]
def yeardayscalendar(self, year, width=3): """ Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero. """ months = [ self.monthdayscalendar(year, i) for i in range(January, January+12) ] return [months[i:i+width] for i in range(0, len(months), width) ]
class TextCalendar(Calendar): """ Subclass of Calendar that outputs a calendar as a simple plain text similar to the UNIX program cal. """
def prweek(self, theweek, width): """ Print a single week (no newline). """ print(self.formatweek(theweek, width), end='')
def formatday(self, day, weekday, width): """ Returns a formatted day. """ if day == 0: s = '' else: s = '%2i' % day # right-align single-digit days return s.center(width)
def formatweek(self, theweek, width): """ Returns a single week in a string (no newline). """ return ' '.join(self.formatday(d, wd, width) for (d, wd) in theweek)
def formatweekday(self, day, width): """ Returns a formatted week day name. """ if width >= 9: names = day_name else: names = day_abbr return names[day][:width].center(width)
def formatweekheader(self, width): """ Return a header for a week. """ return ' '.join(self.formatweekday(i, width) for i in self.iterweekdays())
def formatmonthname(self, theyear, themonth, width, withyear=True): """ Return a formatted month name. """ s = month_name[themonth] if withyear: s = "%s %r" % (s, theyear) return s.center(width)
def prmonth(self, theyear, themonth, w=0, l=0): """ Print a month's calendar. """ print(self.formatmonth(theyear, themonth, w, l), end='')
def formatmonth(self, theyear, themonth, w=0, l=0): """ Return a month's calendar string (multi-line). """ w = max(2, w) l = max(1, l) s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1) s = s.rstrip() s += '\n' * l s += self.formatweekheader(w).rstrip() s += '\n' * l for week in self.monthdays2calendar(theyear, themonth): s += self.formatweek(week, w).rstrip() s += '\n' * l return s
def formatyear(self, theyear, w=2, l=1, c=6, m=3): """ 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 v = [] a = v.append a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip()) a('\n'*l) header = self.formatweekheader(w) for (i, row) in enumerate(self.yeardays2calendar(theyear, m)): # months in this row months = range(m*i+1, min(m*(i+1)+1, 13)) a('\n'*l) names = (self.formatmonthname(theyear, k, colwidth, False) for k in months) a(formatstring(names, colwidth, c).rstrip()) a('\n'*l) headers = (header for k in months) a(formatstring(headers, colwidth, c).rstrip()) a('\n'*l) # max number of weeks for this row height = max(len(cal) for cal in row) for j in range(height): weeks = [] for cal in row: if j >= len(cal): weeks.append('') else: weeks.append(self.formatweek(cal[j], w)) a(formatstring(weeks, colwidth, c).rstrip()) a('\n' * l) return ''.join(v)
def pryear(self, theyear, w=0, l=0, c=6, m=3): """Print a year's calendar.""" print(self.formatyear(theyear, w, l, c, m), end='')
class HTMLCalendar(Calendar): """ This calendar returns complete HTML pages. """
# CSS classes for the day <td>s cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
# CSS classes for the day <th>s cssclasses_weekday_head = cssclasses
# CSS class for the days before and after current month cssclass_noday = "noday"
# CSS class for the month's head cssclass_month_head = "month"
# CSS class for the month cssclass_month = "month"
# CSS class for the year's table head cssclass_year_head = "year"
# CSS class for the whole year table cssclass_year = "year"
def formatday(self, day, weekday): """ Return a day as a table cell. """ if day == 0: # day outside month return '<td class="%s"> </td>' % self.cssclass_noday else: return '<td class="%s">%d</td>' % (self.cssclasses[weekday], day)
def formatweek(self, theweek): """ Return a complete week as a table row. """ s = ''.join(self.formatday(d, wd) for (d, wd) in theweek) return '<tr>%s</tr>' % s
def formatweekday(self, day): """ Return a weekday name as a table header. """ return '<th class="%s">%s</th>' % ( self.cssclasses_weekday_head[day], day_abbr[day])
def formatweekheader(self): """ Return a header for a week as a table row. """ s = ''.join(self.formatweekday(i) for i in self.iterweekdays()) return '<tr>%s</tr>' % s
def formatmonthname(self, theyear, themonth, withyear=True): """ Return a month name as a table row. """ if withyear: s = '%s %s' % (month_name[themonth], theyear) else: s = '%s' % month_name[themonth] return '<tr><th colspan="7" class="%s">%s</th></tr>' % ( self.cssclass_month_head, s)
def formatmonth(self, theyear, themonth, withyear=True): """ Return a formatted month as a table. """ v = [] a = v.append a('<table border="0" cellpadding="0" cellspacing="0" class="%s">' % ( self.cssclass_month)) a('\n') a(self.formatmonthname(theyear, themonth, withyear=withyear)) a('\n') a(self.formatweekheader()) a('\n') for week in self.monthdays2calendar(theyear, themonth): a(self.formatweek(week)) a('\n') a('</table>') a('\n') return ''.join(v)
def formatyear(self, theyear, width=3): """ Return a formatted year as a table of tables. """ v = [] a = v.append width = max(width, 1) a('<table border="0" cellpadding="0" cellspacing="0" class="%s">' % self.cssclass_year) a('\n') a('<tr><th colspan="%d" class="%s">%s</th></tr>' % ( width, self.cssclass_year_head, theyear)) for i in range(January, January+12, width): # months in this row months = range(i, min(i+width, 13)) a('<tr>') for m in months: a('<td>') a(self.formatmonth(theyear, m, withyear=False)) a('</td>') a('</tr>') a('</table>') return ''.join(v)
def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None): """ Return a formatted year as a complete HTML page. """ if encoding is None: encoding = sys.getdefaultencoding() v = [] a = v.append a('<?xml version="1.0" encoding="%s"?>\n' % encoding) a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n') a('<html>\n') a('<head>\n') a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding) if css is not None: a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css) a('<title>Calendar for %d</title>\n' % theyear) a('</head>\n') a('<body>\n') a(self.formatyear(theyear, width)) a('</body>\n') a('</html>\n') return ''.join(v).encode(encoding, "xmlcharrefreplace")
class different_locale: def __init__(self, locale): self.locale = locale
def __enter__(self): self.oldlocale = _locale.getlocale(_locale.LC_TIME) _locale.setlocale(_locale.LC_TIME, self.locale)
def __exit__(self, *args): _locale.setlocale(_locale.LC_TIME, self.oldlocale)
class LocaleTextCalendar(TextCalendar): """ This class can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode. """
def __init__(self, firstweekday=0, locale=None): TextCalendar.__init__(self, firstweekday) if locale is None: locale = _locale.getdefaultlocale() self.locale = locale
def formatweekday(self, day, width): with different_locale(self.locale): return super().formatweekday(day, width)
def formatmonthname(self, theyear, themonth, width, withyear=True): with different_locale(self.locale): return super().formatmonthname(theyear, themonth, width, withyear)
class LocaleHTMLCalendar(HTMLCalendar): """ This class can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode. """ def __init__(self, firstweekday=0, locale=None): HTMLCalendar.__init__(self, firstweekday) if locale is None: locale = _locale.getdefaultlocale() self.locale = locale
def formatweekday(self, day): with different_locale(self.locale): return super().formatweekday(day)
def formatmonthname(self, theyear, themonth, withyear=True): with different_locale(self.locale): return super().formatmonthname(theyear, themonth, withyear)
# Support for old module level interfacec = TextCalendar()
firstweekday = c.getfirstweekday
def setfirstweekday(firstweekday): if not MONDAY <= firstweekday <= SUNDAY: raise IllegalWeekdayError(firstweekday) c.firstweekday = firstweekday
monthcalendar = c.monthdayscalendarprweek = c.prweekweek = c.formatweekweekheader = c.formatweekheaderprmonth = c.prmonthmonth = c.formatmonthcalendar = c.formatyearprcal = c.pryear
# Spacing of month columns for multi-column year calendar_colwidth = 7*3 - 1 # Amount printed by prweek()_spacing = 6 # Number of spaces between columns
def format(cols, colwidth=_colwidth, spacing=_spacing): """Prints multi-column formatting for year calendars""" print(formatstring(cols, colwidth, spacing))
def formatstring(cols, colwidth=_colwidth, spacing=_spacing): """Returns a string formatted from n strings, centered within n columns.""" spacing *= ' ' return spacing.join(c.center(colwidth) for c in cols)
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
def main(args): import argparse parser = argparse.ArgumentParser() textgroup = parser.add_argument_group('text only arguments') htmlgroup = parser.add_argument_group('html only arguments') textgroup.add_argument( "-w", "--width", type=int, default=2, help="width of date column (default 2)" ) textgroup.add_argument( "-l", "--lines", type=int, default=1, help="number of lines for each week (default 1)" ) textgroup.add_argument( "-s", "--spacing", type=int, default=6, help="spacing between months (default 6)" ) textgroup.add_argument( "-m", "--months", type=int, default=3, help="months per row (default 3)" ) htmlgroup.add_argument( "-c", "--css", default="calendar.css", help="CSS to use for page" ) parser.add_argument( "-L", "--locale", default=None, help="locale to be used from month and weekday names" ) parser.add_argument( "-e", "--encoding", default=None, help="encoding to use for output" ) parser.add_argument( "-t", "--type", default="text", choices=("text", "html"), help="output type (text or html)" ) parser.add_argument( "year", nargs='?', type=int, help="year number (1-9999)" ) parser.add_argument( "month", nargs='?', type=int, help="month number (1-12, text only)" )
options = parser.parse_args(args[1:])
if options.locale and not options.encoding: parser.error("if --locale is specified --encoding is required") sys.exit(1)
locale = options.locale, options.encoding
if options.type == "html": if options.locale: cal = LocaleHTMLCalendar(locale=locale) else: cal = HTMLCalendar() encoding = options.encoding if encoding is None: encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) write = sys.stdout.buffer.write if options.year is None: write(cal.formatyearpage(datetime.date.today().year, **optdict)) elif options.month is None: write(cal.formatyearpage(options.year, **optdict)) else: parser.error("incorrect number of arguments") sys.exit(1) else: if options.locale: cal = LocaleTextCalendar(locale=locale) else: cal = TextCalendar() optdict = dict(w=options.width, l=options.lines) if options.month is None: optdict["c"] = options.spacing optdict["m"] = options.months if options.year is None: result = cal.formatyear(datetime.date.today().year, **optdict) elif options.month is None: result = cal.formatyear(options.year, **optdict) else: result = cal.formatmonth(options.year, options.month, **optdict) write = sys.stdout.write if options.encoding: result = result.encode(options.encoding) write = sys.stdout.buffer.write write(result)
if __name__ == "__main__": main(sys.argv)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004#! /usr/local/bin/python
# NOTE: the above "/usr/local/bin/python" is NOT a mistake. It is# intentionally NOT "/usr/bin/env python". On many systems# (e.g. Solaris), /usr/local/bin is not in $PATH as passed to CGI# scripts, and /usr/local/bin is the default directory where Python is# installed, so /usr/bin/env would be unable to find python. Granted,# binary installations by Linux vendors often install Python in# /usr/bin. So let those vendors patch cgi.py to match their choice# of installation.
"""Support module for CGI (Common Gateway Interface) scripts.
This module defines a number of utilities for use by CGI scriptswritten in Python."""
# History# -------## Michael McLay started this module. Steve Majewski changed the# interface to SvFormContentDict and FormContentDict. The multipart# parsing was inspired by code submitted by Andreas Paepcke. Guido van# Rossum rewrote, reformatted and documented the module and is currently# responsible for its maintenance.#
__version__ = "2.6"
# Imports# =======
from io import StringIO, BytesIO, TextIOWrapperfrom collections.abc import Mappingimport sysimport osimport urllib.parsefrom email.parser import FeedParserfrom email.message import Messageimport htmlimport localeimport tempfileimport warnings
__all__ = ["MiniFieldStorage", "FieldStorage", "parse", "parse_multipart", "parse_header", "test", "print_exception", "print_environ", "print_form", "print_directory", "print_arguments", "print_environ_usage"]
# Logging support# ===============
logfile = "" # Filename to log to, if not emptylogfp = None # File object to log to, if not None
def initlog(*allargs): """Write a log message, if there is a log file.
Even though this function is called initlog(), you should always use log(); log is a variable that is set either to initlog (initially), to dolog (once the log file has been opened), or to nolog (when logging is disabled).
The first argument is a format string; the remaining arguments (if any) are arguments to the % operator, so e.g. log("%s: %s", "a", "b") will write "a: b" to the log file, followed by a newline.
If the global logfp is not None, it should be a file object to which log data is written.
If the global logfp is None, the global logfile may be a string giving a filename to open, in append mode. This file should be world writable!!! If the file can't be opened, logging is silently disabled (since there is no safe place where we could send an error message).
""" global log, logfile, logfp warnings.warn("cgi.log() is deprecated as of 3.10. Use logging instead", DeprecationWarning, stacklevel=2) if logfile and not logfp: try: logfp = open(logfile, "a", encoding="locale") except OSError: pass if not logfp: log = nolog else: log = dolog log(*allargs)
def dolog(fmt, *args): """Write a log message to the log file. See initlog() for docs.""" logfp.write(fmt%args + "\n")
def nolog(*allargs): """Dummy function, assigned to log when logging is disabled.""" pass
def closelog(): """Close the log file.""" global log, logfile, logfp logfile = '' if logfp: logfp.close() logfp = None log = initlog
log = initlog # The current logging function
# Parsing functions# =================
# Maximum input we will accept when REQUEST_METHOD is POST# 0 ==> unlimited inputmaxlen = 0
def parse(fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0, separator='&'): """Parse a query in the environment or from a file (default stdin)
Arguments, all optional:
fp : file pointer; default: sys.stdin.buffer
environ : environment dictionary; default: os.environ
keep_blank_values: flag indicating whether blank values in percent-encoded forms should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included.
strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception.
separator: str. The symbol to use for separating the query arguments. Defaults to &. """ if fp is None: fp = sys.stdin
# field keys and values (except for files) are returned as strings # an encoding is required to decode the bytes read from self.fp if hasattr(fp,'encoding'): encoding = fp.encoding else: encoding = 'latin-1'
# fp.read() must return bytes if isinstance(fp, TextIOWrapper): fp = fp.buffer
if not 'REQUEST_METHOD' in environ: environ['REQUEST_METHOD'] = 'GET' # For testing stand-alone if environ['REQUEST_METHOD'] == 'POST': ctype, pdict = parse_header(environ['CONTENT_TYPE']) if ctype == 'multipart/form-data': return parse_multipart(fp, pdict, separator=separator) elif ctype == 'application/x-www-form-urlencoded': clength = int(environ['CONTENT_LENGTH']) if maxlen and clength > maxlen: raise ValueError('Maximum content length exceeded') qs = fp.read(clength).decode(encoding) else: qs = '' # Unknown content-type if 'QUERY_STRING' in environ: if qs: qs = qs + '&' qs = qs + environ['QUERY_STRING'] elif sys.argv[1:]: if qs: qs = qs + '&' qs = qs + sys.argv[1] environ['QUERY_STRING'] = qs # XXX Shouldn't, really elif 'QUERY_STRING' in environ: qs = environ['QUERY_STRING'] else: if sys.argv[1:]: qs = sys.argv[1] else: qs = "" environ['QUERY_STRING'] = qs # XXX Shouldn't, really return urllib.parse.parse_qs(qs, keep_blank_values, strict_parsing, encoding=encoding, separator=separator)
def parse_multipart(fp, pdict, encoding="utf-8", errors="replace", separator='&'): """Parse multipart input.
Arguments: fp : input file pdict: dictionary containing other parameters of content-type header encoding, errors: request encoding and error handler, passed to FieldStorage
Returns a dictionary just like parse_qs(): keys are the field names, each value is a list of values for that field. For non-file fields, the value is a list of strings. """ # RFC 2046, Section 5.1 : The "multipart" boundary delimiters are always # represented as 7bit US-ASCII. boundary = pdict['boundary'].decode('ascii') ctype = "multipart/form-data; boundary={}".format(boundary) headers = Message() headers.set_type(ctype) try: headers['Content-Length'] = pdict['CONTENT-LENGTH'] except KeyError: pass fs = FieldStorage(fp, headers=headers, encoding=encoding, errors=errors, environ={'REQUEST_METHOD': 'POST'}, separator=separator) return {k: fs.getlist(k) for k in fs}
def _parseparam(s): while s[:1] == ';': s = s[1:] end = s.find(';') while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2: end = s.find(';', end + 1) if end < 0: end = len(s) f = s[:end] yield f.strip() s = s[end:]
def parse_header(line): """Parse a Content-type like header.
Return the main content-type and a dictionary of options.
""" parts = _parseparam(';' + line) key = parts.__next__() pdict = {} for p in parts: i = p.find('=') if i >= 0: name = p[:i].strip().lower() value = p[i+1:].strip() if len(value) >= 2 and value[0] == value[-1] == '"': value = value[1:-1] value = value.replace('\\\\', '\\').replace('\\"', '"') pdict[name] = value return key, pdict
# Classes for field storage# =========================
class MiniFieldStorage:
"""Like FieldStorage, for use when no file uploads are possible."""
# Dummy attributes filename = None list = None type = None file = None type_options = {} disposition = None disposition_options = {} headers = {}
def __init__(self, name, value): """Constructor from field name and value.""" self.name = name self.value = value # self.file = StringIO(value)
def __repr__(self): """Return printable representation.""" return "MiniFieldStorage(%r, %r)" % (self.name, self.value)
class FieldStorage:
"""Store a sequence of fields, reading multipart/form-data.
This class provides naming, typing, files stored on disk, and more. At the top level, it is accessible like a dictionary, whose keys are the field names. (Note: None can occur as a field name.) The items are either a Python list (if there's multiple values) or another FieldStorage or MiniFieldStorage object. If it's a single object, it has the following attributes:
name: the field name, if specified; otherwise None
filename: the filename, if specified; otherwise None; this is the client side filename, *not* the file name on which it is stored (that's a temporary file you don't deal with)
value: the value as a *string*; for file uploads, this transparently reads the file every time you request the value and returns *bytes*
file: the file(-like) object from which you can read the data *as bytes* ; None if the data is stored a simple string
type: the content-type, or None if not specified
type_options: dictionary of options specified on the content-type line
disposition: content-disposition, or None if not specified
disposition_options: dictionary of corresponding options
headers: a dictionary(-like) object (sometimes email.message.Message or a subclass thereof) containing *all* headers
The class is subclassable, mostly for the purpose of overriding the make_file() method, which is called internally to come up with a file open for reading and writing. This makes it possible to override the default choice of storing all files in a temporary directory and unlinking them as soon as they have been opened.
""" def __init__(self, fp=None, headers=None, outerboundary=b'', environ=os.environ, keep_blank_values=0, strict_parsing=0, limit=None, encoding='utf-8', errors='replace', max_num_fields=None, separator='&'): """Constructor. Read multipart/* until last part.
Arguments, all optional:
fp : file pointer; default: sys.stdin.buffer (not used when the request method is GET) Can be : 1. a TextIOWrapper object 2. an object whose read() and readline() methods return bytes
headers : header dictionary-like object; default: taken from environ as per CGI spec
outerboundary : terminating multipart boundary (for internal use only)
environ : environment dictionary; default: os.environ
keep_blank_values: flag indicating whether blank values in percent-encoded forms should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included.
strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception.
limit : used internally to read parts of multipart/form-data forms, to exit from the reading loop when reached. It is the difference between the form content-length and the number of bytes already read
encoding, errors : the encoding and error handler used to decode the binary stream to strings. Must be the same as the charset defined for the page sending the form (content-type : meta http-equiv or header)
max_num_fields: int. If set, then __init__ throws a ValueError if there are more than n fields read by parse_qsl().
""" method = 'GET' self.keep_blank_values = keep_blank_values self.strict_parsing = strict_parsing self.max_num_fields = max_num_fields self.separator = separator if 'REQUEST_METHOD' in environ: method = environ['REQUEST_METHOD'].upper() self.qs_on_post = None if method == 'GET' or method == 'HEAD': if 'QUERY_STRING' in environ: qs = environ['QUERY_STRING'] elif sys.argv[1:]: qs = sys.argv[1] else: qs = "" qs = qs.encode(locale.getpreferredencoding(), 'surrogateescape') fp = BytesIO(qs) if headers is None: headers = {'content-type': "application/x-www-form-urlencoded"} if headers is None: headers = {} if method == 'POST': # Set default content-type for POST to what's traditional headers['content-type'] = "application/x-www-form-urlencoded" if 'CONTENT_TYPE' in environ: headers['content-type'] = environ['CONTENT_TYPE'] if 'QUERY_STRING' in environ: self.qs_on_post = environ['QUERY_STRING'] if 'CONTENT_LENGTH' in environ: headers['content-length'] = environ['CONTENT_LENGTH'] else: if not (isinstance(headers, (Mapping, Message))): raise TypeError("headers must be mapping or an instance of " "email.message.Message") self.headers = headers if fp is None: self.fp = sys.stdin.buffer # self.fp.read() must return bytes elif isinstance(fp, TextIOWrapper): self.fp = fp.buffer else: if not (hasattr(fp, 'read') and hasattr(fp, 'readline')): raise TypeError("fp must be file pointer") self.fp = fp
self.encoding = encoding self.errors = errors
if not isinstance(outerboundary, bytes): raise TypeError('outerboundary must be bytes, not %s' % type(outerboundary).__name__) self.outerboundary = outerboundary
self.bytes_read = 0 self.limit = limit
# Process content-disposition header cdisp, pdict = "", {} if 'content-disposition' in self.headers: cdisp, pdict = parse_header(self.headers['content-disposition']) self.disposition = cdisp self.disposition_options = pdict self.name = None if 'name' in pdict: self.name = pdict['name'] self.filename = None if 'filename' in pdict: self.filename = pdict['filename'] self._binary_file = self.filename is not None
# Process content-type header # # Honor any existing content-type header. But if there is no # content-type header, use some sensible defaults. Assume # outerboundary is "" at the outer level, but something non-false # inside a multi-part. The default for an inner part is text/plain, # but for an outer part it should be urlencoded. This should catch # bogus clients which erroneously forget to include a content-type # header. # # See below for what we do if there does exist a content-type header, # but it happens to be something we don't understand. if 'content-type' in self.headers: ctype, pdict = parse_header(self.headers['content-type']) elif self.outerboundary or method != 'POST': ctype, pdict = "text/plain", {} else: ctype, pdict = 'application/x-www-form-urlencoded', {} self.type = ctype self.type_options = pdict if 'boundary' in pdict: self.innerboundary = pdict['boundary'].encode(self.encoding, self.errors) else: self.innerboundary = b""
clen = -1 if 'content-length' in self.headers: try: clen = int(self.headers['content-length']) except ValueError: pass if maxlen and clen > maxlen: raise ValueError('Maximum content length exceeded') self.length = clen if self.limit is None and clen >= 0: self.limit = clen
self.list = self.file = None self.done = 0 if ctype == 'application/x-www-form-urlencoded': self.read_urlencoded() elif ctype[:10] == 'multipart/': self.read_multi(environ, keep_blank_values, strict_parsing) else: self.read_single()
def __del__(self): try: self.file.close() except AttributeError: pass
def __enter__(self): return self
def __exit__(self, *args): self.file.close()
def __repr__(self): """Return a printable representation.""" return "FieldStorage(%r, %r, %r)" % ( self.name, self.filename, self.value)
def __iter__(self): return iter(self.keys())
def __getattr__(self, name): if name != 'value': raise AttributeError(name) if self.file: self.file.seek(0) value = self.file.read() self.file.seek(0) elif self.list is not None: value = self.list else: value = None return value
def __getitem__(self, key): """Dictionary style indexing.""" if self.list is None: raise TypeError("not indexable") found = [] for item in self.list: if item.name == key: found.append(item) if not found: raise KeyError(key) if len(found) == 1: return found[0] else: return found
def getvalue(self, key, default=None): """Dictionary style get() method, including 'value' lookup.""" if key in self: value = self[key] if isinstance(value, list): return [x.value for x in value] else: return value.value else: return default
def getfirst(self, key, default=None): """ Return the first value received.""" if key in self: value = self[key] if isinstance(value, list): return value[0].value else: return value.value else: return default
def getlist(self, key): """ Return list of received values.""" if key in self: value = self[key] if isinstance(value, list): return [x.value for x in value] else: return [value.value] else: return []
def keys(self): """Dictionary style keys() method.""" if self.list is None: raise TypeError("not indexable") return list(set(item.name for item in self.list))
def __contains__(self, key): """Dictionary style __contains__ method.""" if self.list is None: raise TypeError("not indexable") return any(item.name == key for item in self.list)
def __len__(self): """Dictionary style len(x) support.""" return len(self.keys())
def __bool__(self): if self.list is None: raise TypeError("Cannot be converted to bool.") return bool(self.list)
def read_urlencoded(self): """Internal: read data in query string format.""" qs = self.fp.read(self.length) if not isinstance(qs, bytes): raise ValueError("%s should return bytes, got %s" \ % (self.fp, type(qs).__name__)) qs = qs.decode(self.encoding, self.errors) if self.qs_on_post: qs += '&' + self.qs_on_post query = urllib.parse.parse_qsl( qs, self.keep_blank_values, self.strict_parsing, encoding=self.encoding, errors=self.errors, max_num_fields=self.max_num_fields, separator=self.separator) self.list = [MiniFieldStorage(key, value) for key, value in query] self.skip_lines()
FieldStorageClass = None
def read_multi(self, environ, keep_blank_values, strict_parsing): """Internal: read a part that is itself multipart.""" ib = self.innerboundary if not valid_boundary(ib): raise ValueError('Invalid boundary in multipart form: %r' % (ib,)) self.list = [] if self.qs_on_post: query = urllib.parse.parse_qsl( self.qs_on_post, self.keep_blank_values, self.strict_parsing, encoding=self.encoding, errors=self.errors, max_num_fields=self.max_num_fields, separator=self.separator) self.list.extend(MiniFieldStorage(key, value) for key, value in query)
klass = self.FieldStorageClass or self.__class__ first_line = self.fp.readline() # bytes if not isinstance(first_line, bytes): raise ValueError("%s should return bytes, got %s" \ % (self.fp, type(first_line).__name__)) self.bytes_read += len(first_line)
# Ensure that we consume the file until we've hit our inner boundary while (first_line.strip() != (b"--" + self.innerboundary) and first_line): first_line = self.fp.readline() self.bytes_read += len(first_line)
# Propagate max_num_fields into the sub class appropriately max_num_fields = self.max_num_fields if max_num_fields is not None: max_num_fields -= len(self.list)
while True: parser = FeedParser() hdr_text = b"" while True: data = self.fp.readline() hdr_text += data if not data.strip(): break if not hdr_text: break # parser takes strings, not bytes self.bytes_read += len(hdr_text) parser.feed(hdr_text.decode(self.encoding, self.errors)) headers = parser.close()
# Some clients add Content-Length for part headers, ignore them if 'content-length' in headers: del headers['content-length']
limit = None if self.limit is None \ else self.limit - self.bytes_read part = klass(self.fp, headers, ib, environ, keep_blank_values, strict_parsing, limit, self.encoding, self.errors, max_num_fields, self.separator)
if max_num_fields is not None: max_num_fields -= 1 if part.list: max_num_fields -= len(part.list) if max_num_fields < 0: raise ValueError('Max number of fields exceeded')
self.bytes_read += part.bytes_read self.list.append(part) if part.done or self.bytes_read >= self.length > 0: break self.skip_lines()
def read_single(self): """Internal: read an atomic part.""" if self.length >= 0: self.read_binary() self.skip_lines() else: self.read_lines() self.file.seek(0)
bufsize = 8*1024 # I/O buffering size for copy to file
def read_binary(self): """Internal: read binary data.""" self.file = self.make_file() todo = self.length if todo >= 0: while todo > 0: data = self.fp.read(min(todo, self.bufsize)) # bytes if not isinstance(data, bytes): raise ValueError("%s should return bytes, got %s" % (self.fp, type(data).__name__)) self.bytes_read += len(data) if not data: self.done = -1 break self.file.write(data) todo = todo - len(data)
def read_lines(self): """Internal: read lines until EOF or outerboundary.""" if self._binary_file: self.file = self.__file = BytesIO() # store data as bytes for files else: self.file = self.__file = StringIO() # as strings for other fields if self.outerboundary: self.read_lines_to_outerboundary() else: self.read_lines_to_eof()
def __write(self, line): """line is always bytes, not string""" if self.__file is not None: if self.__file.tell() + len(line) > 1000: self.file = self.make_file() data = self.__file.getvalue() self.file.write(data) self.__file = None if self._binary_file: # keep bytes self.file.write(line) else: # decode to string self.file.write(line.decode(self.encoding, self.errors))
def read_lines_to_eof(self): """Internal: read lines until EOF.""" while 1: line = self.fp.readline(1<<16) # bytes self.bytes_read += len(line) if not line: self.done = -1 break self.__write(line)
def read_lines_to_outerboundary(self): """Internal: read lines until outerboundary. Data is read as bytes: boundaries and line ends must be converted to bytes for comparisons. """ next_boundary = b"--" + self.outerboundary last_boundary = next_boundary + b"--" delim = b"" last_line_lfend = True _read = 0 while 1:
if self.limit is not None and 0 <= self.limit <= _read: break line = self.fp.readline(1<<16) # bytes self.bytes_read += len(line) _read += len(line) if not line: self.done = -1 break if delim == b"\r": line = delim + line delim = b"" if line.startswith(b"--") and last_line_lfend: strippedline = line.rstrip() if strippedline == next_boundary: break if strippedline == last_boundary: self.done = 1 break odelim = delim if line.endswith(b"\r\n"): delim = b"\r\n" line = line[:-2] last_line_lfend = True elif line.endswith(b"\n"): delim = b"\n" line = line[:-1] last_line_lfend = True elif line.endswith(b"\r"): # We may interrupt \r\n sequences if they span the 2**16 # byte boundary delim = b"\r" line = line[:-1] last_line_lfend = False else: delim = b"" last_line_lfend = False self.__write(odelim + line)
def skip_lines(self): """Internal: skip lines until outer boundary if defined.""" if not self.outerboundary or self.done: return next_boundary = b"--" + self.outerboundary last_boundary = next_boundary + b"--" last_line_lfend = True while True: line = self.fp.readline(1<<16) self.bytes_read += len(line) if not line: self.done = -1 break if line.endswith(b"--") and last_line_lfend: strippedline = line.strip() if strippedline == next_boundary: break if strippedline == last_boundary: self.done = 1 break last_line_lfend = line.endswith(b'\n')
def make_file(self): """Overridable: return a readable & writable file.
The file will be used as follows: - data is written to it - seek(0) - data is read from it
The file is opened in binary mode for files, in text mode for other fields
This version opens a temporary file for reading and writing, and immediately deletes (unlinks) it. The trick (on Unix!) is that the file can still be used, but it can't be opened by another process, and it will automatically be deleted when it is closed or when the current process terminates.
If you want a more permanent file, you derive a class which overrides this method. If you want a visible temporary file that is nevertheless automatically deleted when the script terminates, try defining a __del__ method in a derived class which unlinks the temporary files you have created.
""" if self._binary_file: return tempfile.TemporaryFile("wb+") else: return tempfile.TemporaryFile("w+", encoding=self.encoding, newline = '\n')
# Test/debug code# ===============
def test(environ=os.environ): """Robust test CGI script, usable as main program.
Write minimal HTTP headers and dump all information provided to the script in HTML form.
""" print("Content-type: text/html") print() sys.stderr = sys.stdout try: form = FieldStorage() # Replace with other classes to test those print_directory() print_arguments() print_form(form) print_environ(environ) print_environ_usage() def f(): exec("testing print_exception() -- <I>italics?</I>") def g(f=f): f() print("<H3>What follows is a test, not an actual exception:</H3>") g() except: print_exception()
print("<H1>Second try with a small maxlen...</H1>")
global maxlen maxlen = 50 try: form = FieldStorage() # Replace with other classes to test those print_directory() print_arguments() print_form(form) print_environ(environ) except: print_exception()
def print_exception(type=None, value=None, tb=None, limit=None): if type is None: type, value, tb = sys.exc_info() import traceback print() print("<H3>Traceback (most recent call last):</H3>") list = traceback.format_tb(tb, limit) + \ traceback.format_exception_only(type, value) print("<PRE>%s<B>%s</B></PRE>" % ( html.escape("".join(list[:-1])), html.escape(list[-1]), )) del tb
def print_environ(environ=os.environ): """Dump the shell environment as HTML.""" keys = sorted(environ.keys()) print() print("<H3>Shell Environment:</H3>") print("<DL>") for key in keys: print("<DT>", html.escape(key), "<DD>", html.escape(environ[key])) print("</DL>") print()
def print_form(form): """Dump the contents of a form as HTML.""" keys = sorted(form.keys()) print() print("<H3>Form Contents:</H3>") if not keys: print("<P>No form fields.") print("<DL>") for key in keys: print("<DT>" + html.escape(key) + ":", end=' ') value = form[key] print("<i>" + html.escape(repr(type(value))) + "</i>") print("<DD>" + html.escape(repr(value))) print("</DL>") print()
def print_directory(): """Dump the current directory as HTML.""" print() print("<H3>Current Working Directory:</H3>") try: pwd = os.getcwd() except OSError as msg: print("OSError:", html.escape(str(msg))) else: print(html.escape(pwd)) print()
def print_arguments(): print() print("<H3>Command Line Arguments:</H3>") print() print(sys.argv) print()
def print_environ_usage(): """Dump a list of environment variables used by CGI as HTML.""" print("""<H3>These environment variables could have been set:</H3><UL><LI>AUTH_TYPE<LI>CONTENT_LENGTH<LI>CONTENT_TYPE<LI>DATE_GMT<LI>DATE_LOCAL<LI>DOCUMENT_NAME<LI>DOCUMENT_ROOT<LI>DOCUMENT_URI<LI>GATEWAY_INTERFACE<LI>LAST_MODIFIED<LI>PATH<LI>PATH_INFO<LI>PATH_TRANSLATED<LI>QUERY_STRING<LI>REMOTE_ADDR<LI>REMOTE_HOST<LI>REMOTE_IDENT<LI>REMOTE_USER<LI>REQUEST_METHOD<LI>SCRIPT_NAME<LI>SERVER_NAME<LI>SERVER_PORT<LI>SERVER_PROTOCOL<LI>SERVER_ROOT<LI>SERVER_SOFTWARE</UL>In addition, HTTP headers sent by the server may be passed in theenvironment as well. Here are some common variable names:<UL><LI>HTTP_ACCEPT<LI>HTTP_CONNECTION<LI>HTTP_HOST<LI>HTTP_PRAGMA<LI>HTTP_REFERER<LI>HTTP_USER_AGENT</UL>""")
# Utilities# =========
def valid_boundary(s): import re if isinstance(s, bytes): _vb_pattern = b"^[ -~]{0,200}[!-~]$" else: _vb_pattern = "^[ -~]{0,200}[!-~]$" return re.match(_vb_pattern, s)
# Invoke mainline# ===============
# Call test() when this file is run as a script (not imported as a module)if __name__ == '__main__': test()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321"""More comprehensive traceback formatting for Python scripts.
To enable this module, do:
import cgitb; cgitb.enable()
at the top of your script. The optional arguments to enable() are:
display - if true, tracebacks are displayed in the web browser logdir - if set, tracebacks are written to files in this directory context - number of lines of source code to show for each stack frame format - 'text' or 'html' controls the output format
By default, tracebacks are displayed but not saved, the context is 5 linesand the output format is 'html' (for backwards compatibility with theoriginal use of this module)
Alternatively, if you have caught an exception and want cgitb to display itfor you, call cgitb.handler(). The optional argument to handler() is a3-item tuple (etype, evalue, etb) just like the value of sys.exc_info().The default handler displays output as HTML.
"""import inspectimport keywordimport linecacheimport osimport pydocimport sysimport tempfileimport timeimport tokenizeimport traceback
def reset(): """Return a string that resets the CGI and browser to a known state.""" return '''<!--: spamContent-Type: text/html
<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --><body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> --></font> </font> </font> </script> </object> </blockquote> </pre></table> </table> </table> </table> </table> </font> </font> </font>'''
__UNDEF__ = [] # a special sentinel objectdef small(text): if text: return '<small>' + text + '</small>' else: return ''
def strong(text): if text: return '<strong>' + text + '</strong>' else: return ''
def grey(text): if text: return '<font color="#909090">' + text + '</font>' else: return ''
def lookup(name, frame, locals): """Find the value for a given name in the given environment.""" if name in locals: return 'local', locals[name] if name in frame.f_globals: return 'global', frame.f_globals[name] if '__builtins__' in frame.f_globals: builtins = frame.f_globals['__builtins__'] if type(builtins) is type({}): if name in builtins: return 'builtin', builtins[name] else: if hasattr(builtins, name): return 'builtin', getattr(builtins, name) return None, __UNDEF__
def scanvars(reader, frame, locals): """Scan one logical line of Python and look up values of variables used.""" vars, lasttoken, parent, prefix, value = [], None, None, '', __UNDEF__ for ttype, token, start, end, line in tokenize.generate_tokens(reader): if ttype == tokenize.NEWLINE: break if ttype == tokenize.NAME and token not in keyword.kwlist: if lasttoken == '.': if parent is not __UNDEF__: value = getattr(parent, token, __UNDEF__) vars.append((prefix + token, prefix, value)) else: where, value = lookup(token, frame, locals) vars.append((token, where, value)) elif token == '.': prefix += lasttoken + '.' parent = value else: parent, prefix = None, '' lasttoken = token return vars
def html(einfo, context=5): """Return a nice HTML document describing a given traceback.""" etype, evalue, etb = einfo if isinstance(etype, type): etype = etype.__name__ pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable date = time.ctime(time.time()) head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading( '<big><big>%s</big></big>' % strong(pydoc.html.escape(str(etype))), '#ffffff', '#6622aa', pyver + '<br>' + date) + '''<p>A problem occurred in a Python script. Here is the sequence offunction calls leading up to the error, in the order they occurred.</p>'''
indent = '<tt>' + small(' ' * 5) + ' </tt>' frames = [] records = inspect.getinnerframes(etb, context) for frame, file, lnum, func, lines, index in records: if file: file = os.path.abspath(file) link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file)) else: file = link = '?' args, varargs, varkw, locals = inspect.getargvalues(frame) call = '' if func != '?': call = 'in ' + strong(pydoc.html.escape(func)) if func != "<module>": call += inspect.formatargvalues(args, varargs, varkw, locals, formatvalue=lambda value: '=' + pydoc.html.repr(value))
highlight = {} def reader(lnum=[lnum]): highlight[lnum[0]] = 1 try: return linecache.getline(file, lnum[0]) finally: lnum[0] += 1 vars = scanvars(reader, frame, locals)
rows = ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' % ('<big> </big>', link, call)] if index is not None: i = lnum - index for line in lines: num = small(' ' * (5-len(str(i))) + str(i)) + ' ' if i in highlight: line = '<tt>=>%s%s</tt>' % (num, pydoc.html.preformat(line)) rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line) else: line = '<tt> %s%s</tt>' % (num, pydoc.html.preformat(line)) rows.append('<tr><td>%s</td></tr>' % grey(line)) i += 1
done, dump = {}, [] for name, where, value in vars: if name in done: continue done[name] = 1 if value is not __UNDEF__: if where in ('global', 'builtin'): name = ('<em>%s</em> ' % where) + strong(name) elif where == 'local': name = strong(name) else: name = where + strong(name.split('.')[-1]) dump.append('%s = %s' % (name, pydoc.html.repr(value))) else: dump.append(name + ' <em>undefined</em>')
rows.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump)))) frames.append('''<table width="100%%" cellspacing=0 cellpadding=0 border=0>%s</table>''' % '\n'.join(rows))
exception = ['<p>%s: %s' % (strong(pydoc.html.escape(str(etype))), pydoc.html.escape(str(evalue)))] for name in dir(evalue): if name[:1] == '_': continue value = pydoc.html.repr(getattr(evalue, name)) exception.append('\n<br>%s%s =\n%s' % (indent, name, value))
return head + ''.join(frames) + ''.join(exception) + '''
<!-- The above is a description of an error in a Python program, formatted for a web browser because the 'cgitb' module was enabled. In case you are not reading this in a web browser, here is the original traceback:
%s-->''' % pydoc.html.escape( ''.join(traceback.format_exception(etype, evalue, etb)))
def text(einfo, context=5): """Return a plain text document describing a given traceback.""" etype, evalue, etb = einfo if isinstance(etype, type): etype = etype.__name__ pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable date = time.ctime(time.time()) head = "%s\n%s\n%s\n" % (str(etype), pyver, date) + '''A problem occurred in a Python script. Here is the sequence offunction calls leading up to the error, in the order they occurred.'''
frames = [] records = inspect.getinnerframes(etb, context) for frame, file, lnum, func, lines, index in records: file = file and os.path.abspath(file) or '?' args, varargs, varkw, locals = inspect.getargvalues(frame) call = '' if func != '?': call = 'in ' + func if func != "<module>": call += inspect.formatargvalues(args, varargs, varkw, locals, formatvalue=lambda value: '=' + pydoc.text.repr(value))
highlight = {} def reader(lnum=[lnum]): highlight[lnum[0]] = 1 try: return linecache.getline(file, lnum[0]) finally: lnum[0] += 1 vars = scanvars(reader, frame, locals)
rows = [' %s %s' % (file, call)] if index is not None: i = lnum - index for line in lines: num = '%5d ' % i rows.append(num+line.rstrip()) i += 1
done, dump = {}, [] for name, where, value in vars: if name in done: continue done[name] = 1 if value is not __UNDEF__: if where == 'global': name = 'global ' + name elif where != 'local': name = where + name.split('.')[-1] dump.append('%s = %s' % (name, pydoc.text.repr(value))) else: dump.append(name + ' undefined')
rows.append('\n'.join(dump)) frames.append('\n%s\n' % '\n'.join(rows))
exception = ['%s: %s' % (str(etype), str(evalue))] for name in dir(evalue): value = pydoc.text.repr(getattr(evalue, name)) exception.append('\n%s%s = %s' % (" "*4, name, value))
return head + ''.join(frames) + ''.join(exception) + '''
The above is a description of an error in a Python program. Here isthe original traceback:
%s''' % ''.join(traceback.format_exception(etype, evalue, etb))
class Hook: """A hook to replace sys.excepthook that shows tracebacks in HTML."""
def __init__(self, display=1, logdir=None, context=5, file=None, format="html"): self.display = display # send tracebacks to browser if true self.logdir = logdir # log tracebacks to files if not None self.context = context # number of source code lines per frame self.file = file or sys.stdout # place to send the output self.format = format
def __call__(self, etype, evalue, etb): self.handle((etype, evalue, etb))
def handle(self, info=None): info = info or sys.exc_info() if self.format == "html": self.file.write(reset())
formatter = (self.format=="html") and html or text plain = False try: doc = formatter(info, self.context) except: # just in case something goes wrong doc = ''.join(traceback.format_exception(*info)) plain = True
if self.display: if plain: doc = pydoc.html.escape(doc) self.file.write('<pre>' + doc + '</pre>\n') else: self.file.write(doc + '\n') else: self.file.write('<p>A problem occurred in a Python script.\n')
if self.logdir is not None: suffix = ['.txt', '.html'][self.format=="html"] (fd, path) = tempfile.mkstemp(suffix=suffix, dir=self.logdir)
try: with os.fdopen(fd, 'w') as file: file.write(doc) msg = '%s contains the description of this error.' % path except: msg = 'Tried to save traceback to %s, but failed.' % path
if self.format == 'html': self.file.write('<p>%s</p>\n' % msg) else: self.file.write(msg + '\n') try: self.file.flush() except: pass
handler = Hook().handledef enable(display=1, logdir=None, context=5, format="html"): """Install an exception handler that formats tracebacks as HTML.
The optional argument 'display' can be set to 0 to suppress sending the traceback to the browser, and 'logdir' can be set to a directory to cause tracebacks to be written to files there.""" sys.excepthook = Hook(display=display, logdir=logdir, context=context, format=format)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169"""Simple class to read IFF chunks.
An IFF chunk (used in formats such as AIFF, TIFF, RMFF (RealMedia FileFormat)) 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 proposedusage of the Chunk class defined here is to instantiate an instance atthe start of each chunk and read from the instance until it reachesthe end, after which a new instance can be instantiated. At the endof the file, creating a new instance will fail with an EOFErrorexception.
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 whichspecifies whether or not chunks are aligned on 2-byte boundaries. Thedefault 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_from(strflag+'L', file.read(4))[0] except struct.error: raise EOFError from None if inclheader: self.chunksize = self.chunksize - 8 # subtract header self.size_read = 0 try: self.offset = self.file.tell() except (AttributeError, OSError): 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: try: self.skip() finally: 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 OSError("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 b'' 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 OSError: pass while self.size_read < self.chunksize: n = min(8192, self.chunksize - self.size_read) dummy = self.read(n) if not dummy: raise EOFError123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401"""A generic class to build line-oriented command interpreters.
Interpreters constructed with this class obey the following conventions:
1. End of file on input is processed as the command 'EOF'.2. A command is parsed out of each line by collecting the prefix composed of characters in the identchars member.3. A command `foo' is dispatched to a method 'do_foo()'; the do_ method is passed a single argument consisting of the remainder of the line.4. Typing an empty line repeats the last command. (Actually, it calls the method `emptyline', which may be overridden in a subclass.)5. There is a predefined `help' method. Given an argument `topic', it calls the command `help_topic'. With no arguments, it lists all topics with defined help_ functions, broken into up to three topics; documented commands, miscellaneous help topics, and undocumented commands.6. The command '?' is a synonym for `help'. The command '!' is a synonym for `shell', if a do_shell method exists.7. If completion is enabled, completing commands will be done automatically, and completing of commands args is done by calling complete_foo() with arguments text, line, begidx, endidx. text is string we are matching against, all returned matches must begin with it. line is the current input line (lstripped), begidx and endidx are the beginning and end indexes of the text being matched, which could be used to provide different completion depending upon which position the argument is in.
The `default' method may be overridden to intercept commands for which thereis no do_ method.
The `completedefault' method may be overridden to intercept completions forcommands that have no complete_ method.
The data member `self.ruler' sets the character used to draw separator linesin the help messages. If empty, no ruler line is drawn. It defaults to "=".
If the value of `self.intro' is nonempty when the cmdloop method is called,it is printed out on interpreter startup. This value may be overriddenvia an optional argument to the cmdloop() method.
The data members `self.doc_header', `self.misc_header', and`self.undoc_header' set the headers used for the help function'slistings of documented functions, miscellaneous topics, and undocumentedfunctions respectively."""
import string, sys
__all__ = ["Cmd"]
PROMPT = '(Cmd) 'IDENTCHARS = string.ascii_letters + string.digits + '_'
class Cmd: """A simple framework for writing line-oriented command interpreters.
These are often useful for test harnesses, administrative tools, and prototypes that will later be wrapped in a more sophisticated interface.
A Cmd instance or subclass instance is a line-oriented interpreter framework. There is no good reason to instantiate Cmd itself; rather, it's useful as a superclass of an interpreter class you define yourself in order to inherit Cmd's methods and encapsulate action methods.
""" prompt = PROMPT identchars = IDENTCHARS ruler = '=' lastcmd = '' intro = None doc_leader = "" doc_header = "Documented commands (type help <topic>):" misc_header = "Miscellaneous help topics:" undoc_header = "Undocumented commands:" nohelp = "*** No help on %s" use_rawinput = 1
def __init__(self, completekey='tab', stdin=None, stdout=None): """Instantiate a line-oriented interpreter framework.
The optional argument 'completekey' is the readline name of a completion key; it defaults to the Tab key. If completekey is not None and the readline module is available, command completion is done automatically. The optional arguments stdin and stdout specify alternate input and output file objects; if not specified, sys.stdin and sys.stdout are used.
""" if stdin is not None: self.stdin = stdin else: self.stdin = sys.stdin if stdout is not None: self.stdout = stdout else: self.stdout = sys.stdout self.cmdqueue = [] self.completekey = completekey
def cmdloop(self, intro=None): """Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument.
"""
self.preloop() if self.use_rawinput and self.completekey: try: import readline self.old_completer = readline.get_completer() readline.set_completer(self.complete) readline.parse_and_bind(self.completekey+": complete") except ImportError: pass try: if intro is not None: self.intro = intro if self.intro: self.stdout.write(str(self.intro)+"\n") stop = None while not stop: if self.cmdqueue: line = self.cmdqueue.pop(0) else: if self.use_rawinput: try: line = input(self.prompt) except EOFError: line = 'EOF' else: self.stdout.write(self.prompt) self.stdout.flush() line = self.stdin.readline() if not len(line): line = 'EOF' else: line = line.rstrip('\r\n') line = self.precmd(line) stop = self.onecmd(line) stop = self.postcmd(stop, line) self.postloop() finally: if self.use_rawinput and self.completekey: try: import readline readline.set_completer(self.old_completer) except ImportError: pass
def precmd(self, line): """Hook method executed just before the command line is interpreted, but after the input prompt is generated and issued.
""" return line
def postcmd(self, stop, line): """Hook method executed just after a command dispatch is finished.""" return stop
def preloop(self): """Hook method executed once when the cmdloop() method is called.""" pass
def postloop(self): """Hook method executed once when the cmdloop() method is about to return.
""" pass
def parseline(self, line): """Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). 'command' and 'args' may be None if the line couldn't be parsed. """ line = line.strip() if not line: return None, None, line elif line[0] == '?': line = 'help ' + line[1:] elif line[0] == '!': if hasattr(self, 'do_shell'): line = 'shell ' + line[1:] else: return None, None, line i, n = 0, len(line) while i < n and line[i] in self.identchars: i = i+1 cmd, arg = line[:i], line[i:].strip() return cmd, arg, line
def onecmd(self, line): """Interpret the argument as though it had been typed in response to the prompt.
This may be overridden, but should not normally need to be; see the precmd() and postcmd() methods for useful execution hooks. The return value is a flag indicating whether interpretation of commands by the interpreter should stop.
""" cmd, arg, line = self.parseline(line) if not line: return self.emptyline() if cmd is None: return self.default(line) self.lastcmd = line if line == 'EOF' : self.lastcmd = '' if cmd == '': return self.default(line) else: try: func = getattr(self, 'do_' + cmd) except AttributeError: return self.default(line) return func(arg)
def emptyline(self): """Called when an empty line is entered in response to the prompt.
If this method is not overridden, it repeats the last nonempty command entered.
""" if self.lastcmd: return self.onecmd(self.lastcmd)
def default(self, line): """Called on an input line when the command prefix is not recognized.
If this method is not overridden, it prints an error message and returns.
""" self.stdout.write('*** Unknown syntax: %s\n'%line)
def completedefault(self, *ignored): """Method called to complete an input line when no command-specific complete_*() method is available.
By default, it returns an empty list.
""" return []
def completenames(self, text, *ignored): dotext = 'do_'+text return [a[3:] for a in self.get_names() if a.startswith(dotext)]
def complete(self, text, state): """Return the next possible completion for 'text'.
If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. """ if state == 0: import readline origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped if begidx>0: cmd, args, foo = self.parseline(line) if cmd == '': compfunc = self.completedefault else: try: compfunc = getattr(self, 'complete_' + cmd) except AttributeError: compfunc = self.completedefault else: compfunc = self.completenames self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None
def get_names(self): # This method used to pull in base class attributes # at a time dir() didn't do it yet. return dir(self.__class__)
def complete_help(self, *args): commands = set(self.completenames(*args)) topics = set(a[5:] for a in self.get_names() if a.startswith('help_' + args[0])) return list(commands | topics)
def do_help(self, arg): 'List available commands with "help" or detailed help with "help cmd".' if arg: # XXX check arg syntax try: func = getattr(self, 'help_' + arg) except AttributeError: try: doc=getattr(self, 'do_' + arg).__doc__ if doc: self.stdout.write("%s\n"%str(doc)) return except AttributeError: pass self.stdout.write("%s\n"%str(self.nohelp % (arg,))) return func() else: names = self.get_names() cmds_doc = [] cmds_undoc = [] help = {} for name in names: if name[:5] == 'help_': help[name[5:]]=1 names.sort() # There can be duplicates if routines overridden prevname = '' for name in names: if name[:3] == 'do_': if name == prevname: continue prevname = name cmd=name[3:] if cmd in help: cmds_doc.append(cmd) del help[cmd] elif getattr(self, name).__doc__: cmds_doc.append(cmd) else: cmds_undoc.append(cmd) self.stdout.write("%s\n"%str(self.doc_leader)) self.print_topics(self.doc_header, cmds_doc, 15,80) self.print_topics(self.misc_header, list(help.keys()),15,80) self.print_topics(self.undoc_header, cmds_undoc, 15,80)
def print_topics(self, header, cmds, cmdlen, maxcol): if cmds: self.stdout.write("%s\n"%str(header)) if self.ruler: self.stdout.write("%s\n"%str(self.ruler * len(header))) self.columnize(cmds, maxcol-1) self.stdout.write("\n")
def columnize(self, list, displaywidth=80): """Display a list of strings as a compact set of columns.
Each column is only as wide as necessary. Columns are separated by two spaces (one was not legible enough). """ if not list: self.stdout.write("<empty>\n") return
nonstrings = [i for i in range(len(list)) if not isinstance(list[i], str)] if nonstrings: raise TypeError("list[i] not a string for i in %s" % ", ".join(map(str, nonstrings))) size = len(list) if size == 1: self.stdout.write('%s\n'%str(list[0])) return # Try every row count from 1 upwards for nrows in range(1, len(list)): ncols = (size+nrows-1) // nrows colwidths = [] totwidth = -2 for col in range(ncols): colwidth = 0 for row in range(nrows): i = row + nrows*col if i >= size: break x = list[i] colwidth = max(colwidth, len(x)) colwidths.append(colwidth) totwidth += colwidth + 2 if totwidth > displaywidth: break if totwidth <= displaywidth: break else: nrows = len(list) ncols = 1 colwidths = [0] for row in range(nrows): texts = [] for col in range(ncols): i = row + nrows*col if i >= size: x = "" else: x = list[i] texts.append(x) while texts and not texts[-1]: del texts[-1] for col in range(len(texts)): texts[col] = texts[col].ljust(colwidths[col]) self.stdout.write("%s\n"%str(" ".join(texts)))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315"""Utilities needed to emulate Python's interactive interpreter.
"""
# Inspired by similar code by Jeff Epler and Fredrik Lundh.
import sysimport tracebackfrom codeop import CommandCompiler, compile_command
__all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact", "compile_command"]
class InteractiveInterpreter: """Base class for InteractiveConsole.
This class deals with parsing and interpreter state (the user's namespace); it doesn't deal with input buffering or prompting or input file naming (the filename is always passed in explicitly).
"""
def __init__(self, locals=None): """Constructor.
The optional 'locals' argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key "__name__" set to "__console__" and key "__doc__" set to None.
""" if locals is None: locals = {"__name__": "__console__", "__doc__": None} self.locals = locals self.compile = CommandCompiler()
def runsource(self, source, filename="<input>", symbol="single"): """Compile and run some source in the interpreter.
Arguments are as for compile_command().
One of several things can happen:
1) The input is incorrect; compile_command() raised an exception (SyntaxError or OverflowError). A syntax traceback will be printed by calling the showsyntaxerror() method.
2) The input is incomplete, and more input is required; compile_command() returned None. Nothing happens.
3) The input is complete; compile_command() returned a code object. The code is executed by calling self.runcode() (which also handles run-time exceptions, except for SystemExit).
The return value is True in case 2, False in the other cases (unless an exception is raised). The return value can be used to decide whether to use sys.ps1 or sys.ps2 to prompt the next line.
""" try: code = self.compile(source, filename, symbol) except (OverflowError, SyntaxError, ValueError): # Case 1 self.showsyntaxerror(filename) return False
if code is None: # Case 2 return True
# Case 3 self.runcode(code) return False
def runcode(self, code): """Execute a code object.
When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised.
A note about KeyboardInterrupt: this exception may occur elsewhere in this code, and may not always be caught. The caller should be prepared to deal with it.
""" try: exec(code, self.locals) except SystemExit: raise except: self.showtraceback()
def showsyntaxerror(self, filename=None): """Display the syntax error that just occurred.
This doesn't display a stack trace because there isn't one.
If a filename is given, it is stuffed in the exception instead of what was there before (because Python's parser always uses "<string>" when reading from a string).
The output is written by self.write(), below.
""" type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb if filename and type is SyntaxError: # Work hard to stuff the correct filename in the exception try: msg, (dummy_filename, lineno, offset, line) = value.args except ValueError: # Not the format we expect; leave it alone pass else: # Stuff in the right filename value = SyntaxError(msg, (filename, lineno, offset, line)) sys.last_value = value if sys.excepthook is sys.__excepthook__: lines = traceback.format_exception_only(type, value) self.write(''.join(lines)) else: # If someone has set sys.excepthook, we let that take precedence # over self.write sys.excepthook(type, value, tb)
def showtraceback(self): """Display the exception that just occurred.
We remove the first stack item because it is our own code.
The output is written by self.write(), below.
""" sys.last_type, sys.last_value, last_tb = ei = sys.exc_info() sys.last_traceback = last_tb try: lines = traceback.format_exception(ei[0], ei[1], last_tb.tb_next) if sys.excepthook is sys.__excepthook__: self.write(''.join(lines)) else: # If someone has set sys.excepthook, we let that take precedence # over self.write sys.excepthook(ei[0], ei[1], last_tb) finally: last_tb = ei = None
def write(self, data): """Write a string.
The base implementation writes to sys.stderr; a subclass may replace this with a different implementation.
""" sys.stderr.write(data)
class InteractiveConsole(InteractiveInterpreter): """Closely emulate the behavior of the interactive Python interpreter.
This class builds on InteractiveInterpreter and adds prompting using the familiar sys.ps1 and sys.ps2, and input buffering.
"""
def __init__(self, locals=None, filename="<console>"): """Constructor.
The optional locals argument will be passed to the InteractiveInterpreter base class.
The optional filename argument should specify the (file)name of the input stream; it will show up in tracebacks.
""" InteractiveInterpreter.__init__(self, locals) self.filename = filename self.resetbuffer()
def resetbuffer(self): """Reset the input buffer.""" self.buffer = []
def interact(self, banner=None, exitmsg=None): """Closely emulate the interactive Python console.
The optional banner argument specifies the banner to print before the first interaction; by default it prints a banner similar to the one printed by the real Python interpreter, followed by the current class name in parentheses (so as not to confuse this with the real interpreter -- since it's so close!).
The optional exitmsg argument specifies the exit message printed when exiting. Pass the empty string to suppress printing an exit message. If exitmsg is not given or None, a default message is printed.
""" try: sys.ps1 except AttributeError: sys.ps1 = ">>> " try: sys.ps2 except AttributeError: sys.ps2 = "... " cprt = 'Type "help", "copyright", "credits" or "license" for more information.' if banner is None: self.write("Python %s on %s\n%s\n(%s)\n" % (sys.version, sys.platform, cprt, self.__class__.__name__)) elif banner: self.write("%s\n" % str(banner)) more = 0 while 1: try: if more: prompt = sys.ps2 else: prompt = sys.ps1 try: line = self.raw_input(prompt) except EOFError: self.write("\n") break else: more = self.push(line) except KeyboardInterrupt: self.write("\nKeyboardInterrupt\n") self.resetbuffer() more = 0 if exitmsg is None: self.write('now exiting %s...\n' % self.__class__.__name__) elif exitmsg != '': self.write('%s\n' % exitmsg)
def push(self, line): """Push a line to the interpreter.
The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter's runsource() method is called with the concatenated contents of the buffer as source. If this indicates that the command was executed or invalid, the buffer is reset; otherwise, the command is incomplete, and the buffer is left as it was after the line was appended. The return value is 1 if more input is required, 0 if the line was dealt with in some way (this is the same as runsource()).
""" self.buffer.append(line) source = "\n".join(self.buffer) more = self.runsource(source, self.filename) if not more: self.resetbuffer() return more
def raw_input(self, prompt=""): """Write a prompt and read a line.
The returned line does not include the trailing newline. When the user enters the EOF key sequence, EOFError is raised.
The base implementation uses the built-in function input(); a subclass may replace this with a different implementation.
""" return input(prompt)
def interact(banner=None, readfunc=None, local=None, exitmsg=None): """Closely emulate the interactive Python interpreter.
This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the readline module to enable GNU readline if it is available.
Arguments (all optional, all default to None):
banner -- passed to InteractiveConsole.interact() readfunc -- if not None, replaces InteractiveConsole.raw_input() local -- passed to InteractiveInterpreter.__init__() exitmsg -- passed to InteractiveConsole.interact()
""" console = InteractiveConsole(local) if readfunc is not None: console.raw_input = readfunc else: try: import readline except ImportError: pass console.interact(banner, exitmsg)
if __name__ == "__main__": import argparse
parser = argparse.ArgumentParser() parser.add_argument('-q', action='store_true', help="don't print version and copyright messages") args = parser.parse_args() if args.q or sys.flags.quiet: banner = '' else: banner = None interact(banner)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127""" codecs -- Python Codec Registry, API and helpers.
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""
import builtinsimport sys
### Registry and builtin stateless codec functions
try: from _codecs import *except ImportError as why: raise SystemError('Failed to load the builtin codecs: %s' % why)
__all__ = ["register", "lookup", "open", "EncodedFile", "BOM", "BOM_BE", "BOM_LE", "BOM32_BE", "BOM32_LE", "BOM64_BE", "BOM64_LE", "BOM_UTF8", "BOM_UTF16", "BOM_UTF16_LE", "BOM_UTF16_BE", "BOM_UTF32", "BOM_UTF32_LE", "BOM_UTF32_BE", "CodecInfo", "Codec", "IncrementalEncoder", "IncrementalDecoder", "StreamReader", "StreamWriter", "StreamReaderWriter", "StreamRecoder", "getencoder", "getdecoder", "getincrementalencoder", "getincrementaldecoder", "getreader", "getwriter", "encode", "decode", "iterencode", "iterdecode", "strict_errors", "ignore_errors", "replace_errors", "xmlcharrefreplace_errors", "backslashreplace_errors", "namereplace_errors", "register_error", "lookup_error"]
### Constants
## Byte Order Mark (BOM = ZERO WIDTH NO-BREAK SPACE = U+FEFF)# and its possible byte string values# for UTF8/UTF16/UTF32 output and little/big endian machines#
# UTF-8BOM_UTF8 = b'\xef\xbb\xbf'
# UTF-16, little endianBOM_LE = BOM_UTF16_LE = b'\xff\xfe'
# UTF-16, big endianBOM_BE = BOM_UTF16_BE = b'\xfe\xff'
# UTF-32, little endianBOM_UTF32_LE = b'\xff\xfe\x00\x00'
# UTF-32, big endianBOM_UTF32_BE = b'\x00\x00\xfe\xff'
if sys.byteorder == 'little':
# UTF-16, native endianness BOM = BOM_UTF16 = BOM_UTF16_LE
# UTF-32, native endianness BOM_UTF32 = BOM_UTF32_LE
else:
# UTF-16, native endianness BOM = BOM_UTF16 = BOM_UTF16_BE
# UTF-32, native endianness BOM_UTF32 = BOM_UTF32_BE
# Old broken names (don't use in new code)BOM32_LE = BOM_UTF16_LEBOM32_BE = BOM_UTF16_BEBOM64_LE = BOM_UTF32_LEBOM64_BE = BOM_UTF32_BE
### Codec base classes (defining the API)
class CodecInfo(tuple): """Codec details when looking up the codec registry"""
# Private API to allow Python 3.4 to denylist the known non-Unicode # codecs in the standard library. A more general mechanism to # reliably distinguish test encodings from other codecs will hopefully # be defined for Python 3.5 # # See http://bugs.python.org/issue19619 _is_text_encoding = True # Assume codecs are text encodings by default
def __new__(cls, encode, decode, streamreader=None, streamwriter=None, incrementalencoder=None, incrementaldecoder=None, name=None, *, _is_text_encoding=None): self = tuple.__new__(cls, (encode, decode, streamreader, streamwriter)) self.name = name self.encode = encode self.decode = decode self.incrementalencoder = incrementalencoder self.incrementaldecoder = incrementaldecoder self.streamwriter = streamwriter self.streamreader = streamreader if _is_text_encoding is not None: self._is_text_encoding = _is_text_encoding return self
def __repr__(self): return "<%s.%s object for encoding %s at %#x>" % \ (self.__class__.__module__, self.__class__.__qualname__, self.name, id(self))
class Codec:
""" Defines the interface for stateless encoders/decoders.
The .encode()/.decode() methods may use different error handling schemes by providing the errors argument. These string values are predefined:
'strict' - raise a ValueError error (or a subclass) 'ignore' - ignore the character and continue with the next 'replace' - replace with a suitable replacement character; Python will use the official U+FFFD REPLACEMENT CHARACTER for the builtin Unicode codecs on decoding and '?' on encoding. 'surrogateescape' - replace with private code points U+DCnn. 'xmlcharrefreplace' - Replace with the appropriate XML character reference (only for encoding). 'backslashreplace' - Replace with backslashed escape sequences. 'namereplace' - Replace with \\N{...} escape sequences (only for encoding).
The set of allowed values can be extended via register_error.
""" def encode(self, 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.
The method may not store state in the Codec instance. Use StreamWriter for codecs which have to keep state in order to make encoding efficient.
The encoder must be able to handle zero length input and return an empty object of the output object type in this situation.
""" raise NotImplementedError
def decode(self, 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.
The method may not store state in the Codec instance. Use StreamReader for codecs which have to keep state in order to make decoding efficient.
The decoder must be able to handle zero length input and return an empty object of the output object type in this situation.
""" raise NotImplementedError
class IncrementalEncoder(object): """ An IncrementalEncoder encodes an input in multiple steps. The input can be passed piece by piece to the encode() method. The IncrementalEncoder remembers the state of the encoding process between calls to encode(). """ def __init__(self, errors='strict'): """ Creates an IncrementalEncoder instance.
The IncrementalEncoder may use different error handling schemes by providing the errors keyword argument. See the module docstring for a list of possible values. """ self.errors = errors self.buffer = ""
def encode(self, input, final=False): """ Encodes input and returns the resulting object. """ raise NotImplementedError
def reset(self): """ Resets the encoder to the initial state. """
def getstate(self): """ Return the current state of the encoder. """ return 0
def setstate(self, state): """ Set the current state of the encoder. state must have been returned by getstate(). """
class BufferedIncrementalEncoder(IncrementalEncoder): """ This subclass of IncrementalEncoder can be used as the baseclass for an incremental encoder if the encoder must keep some of the output in a buffer between calls to encode(). """ def __init__(self, errors='strict'): IncrementalEncoder.__init__(self, errors) # unencoded input that is kept between calls to encode() self.buffer = ""
def _buffer_encode(self, input, errors, final): # Overwrite this method in subclasses: It must encode input # and return an (output, length consumed) tuple raise NotImplementedError
def encode(self, input, final=False): # encode input (taking the buffer into account) data = self.buffer + input (result, consumed) = self._buffer_encode(data, self.errors, final) # keep unencoded input until the next call self.buffer = data[consumed:] return result
def reset(self): IncrementalEncoder.reset(self) self.buffer = ""
def getstate(self): return self.buffer or 0
def setstate(self, state): self.buffer = state or ""
class IncrementalDecoder(object): """ An IncrementalDecoder decodes an input in multiple steps. The input can be passed piece by piece to the decode() method. The IncrementalDecoder remembers the state of the decoding process between calls to decode(). """ def __init__(self, errors='strict'): """ Create an IncrementalDecoder instance.
The IncrementalDecoder may use different error handling schemes by providing the errors keyword argument. See the module docstring for a list of possible values. """ self.errors = errors
def decode(self, input, final=False): """ Decode input and returns the resulting object. """ raise NotImplementedError
def reset(self): """ Reset the decoder to the initial state. """
def getstate(self): """ Return the current state of the decoder.
This must be a (buffered_input, additional_state_info) tuple. buffered_input must be a bytes object containing bytes that were passed to decode() that have not yet been converted. additional_state_info must be a non-negative integer representing the state of the decoder WITHOUT yet having processed the contents of buffered_input. In the initial state and after reset(), getstate() must return (b"", 0). """ return (b"", 0)
def setstate(self, state): """ Set the current state of the decoder.
state must have been returned by getstate(). The effect of setstate((b"", 0)) must be equivalent to reset(). """
class BufferedIncrementalDecoder(IncrementalDecoder): """ This subclass of IncrementalDecoder can be used as the baseclass for an incremental decoder if the decoder must be able to handle incomplete byte sequences. """ def __init__(self, errors='strict'): IncrementalDecoder.__init__(self, errors) # undecoded input that is kept between calls to decode() self.buffer = b""
def _buffer_decode(self, input, errors, final): # Overwrite this method in subclasses: It must decode input # and return an (output, length consumed) tuple raise NotImplementedError
def decode(self, input, final=False): # decode input (taking the buffer into account) data = self.buffer + input (result, consumed) = self._buffer_decode(data, self.errors, final) # keep undecoded input until the next call self.buffer = data[consumed:] return result
def reset(self): IncrementalDecoder.reset(self) self.buffer = b""
def getstate(self): # additional state info is always 0 return (self.buffer, 0)
def setstate(self, state): # ignore additional state info self.buffer = state[0]
## The StreamWriter and StreamReader class provide generic working# interfaces which can be used to implement new encoding submodules# very easily. See encodings/utf_8.py for an example on how this is# done.#
class StreamWriter(Codec):
def __init__(self, stream, errors='strict'):
""" Creates a StreamWriter instance.
stream must be a file-like object open for writing.
The StreamWriter may use different error handling schemes by providing the errors keyword argument. These parameters are predefined:
'strict' - raise a ValueError (or a subclass) 'ignore' - ignore the character and continue with the next 'replace'- replace with a suitable replacement character 'xmlcharrefreplace' - Replace with the appropriate XML character reference. 'backslashreplace' - Replace with backslashed escape sequences. 'namereplace' - Replace with \\N{...} escape sequences.
The set of allowed parameter values can be extended via register_error. """ self.stream = stream self.errors = errors
def write(self, object):
""" Writes the object's contents encoded to self.stream. """ data, consumed = self.encode(object, self.errors) self.stream.write(data)
def writelines(self, list):
""" Writes the concatenated list of strings to the stream using .write(). """ self.write(''.join(list))
def reset(self):
""" Resets the codec buffers used for keeping internal state.
Calling this method should ensure that the data on the output is put into a clean state, that allows appending of new fresh data without having to rescan the whole stream to recover state.
""" pass
def seek(self, offset, whence=0): self.stream.seek(offset, whence) if whence == 0 and offset == 0: self.reset()
def __getattr__(self, name, getattr=getattr):
""" Inherit all other methods from the underlying stream. """ return getattr(self.stream, name)
def __enter__(self): return self
def __exit__(self, type, value, tb): self.stream.close()
###
class StreamReader(Codec):
charbuffertype = str
def __init__(self, stream, errors='strict'):
""" Creates a StreamReader instance.
stream must be a file-like object open for reading.
The StreamReader may use different error handling schemes by providing the errors keyword argument. These parameters are predefined:
'strict' - raise a ValueError (or a subclass) 'ignore' - ignore the character and continue with the next 'replace'- replace with a suitable replacement character 'backslashreplace' - Replace with backslashed escape sequences;
The set of allowed parameter values can be extended via register_error. """ self.stream = stream self.errors = errors self.bytebuffer = b"" self._empty_charbuffer = self.charbuffertype() self.charbuffer = self._empty_charbuffer self.linebuffer = None
def decode(self, input, errors='strict'): raise NotImplementedError
def read(self, size=-1, chars=-1, firstline=False):
""" Decodes data from the stream self.stream and returns the resulting object.
chars indicates the number of decoded code points or bytes to return. read() will never return more data than requested, but it might return less, if there is not enough available.
size indicates the approximate maximum number of decoded bytes or code points to read for decoding. The decoder can modify this setting as appropriate. The default value -1 indicates to read and decode as much as possible. size is intended to prevent having to decode huge files in one step.
If firstline is true, and a UnicodeDecodeError happens after the first line terminator in the input only the first line will be returned, the rest of the input will be kept until the next call to read().
The method should use a greedy read strategy, meaning that it should read as much data as is allowed within the definition of the encoding and the given size, e.g. if optional encoding endings or state markers are available on the stream, these should be read too. """ # If we have lines cached, first merge them back into characters if self.linebuffer: self.charbuffer = self._empty_charbuffer.join(self.linebuffer) self.linebuffer = None
if chars < 0: # For compatibility with other read() methods that take a # single argument chars = size
# read until we get the required number of characters (if available) while True: # can the request be satisfied from the character buffer? if chars >= 0: if len(self.charbuffer) >= chars: break # we need more data if size < 0: newdata = self.stream.read() else: newdata = self.stream.read(size) # decode bytes (those remaining from the last call included) data = self.bytebuffer + newdata if not data: break try: newchars, decodedbytes = self.decode(data, self.errors) except UnicodeDecodeError as exc: if firstline: newchars, decodedbytes = \ self.decode(data[:exc.start], self.errors) lines = newchars.splitlines(keepends=True) if len(lines)<=1: raise else: raise # keep undecoded bytes until the next call self.bytebuffer = data[decodedbytes:] # put new characters in the character buffer self.charbuffer += newchars # there was no data available if not newdata: break if chars < 0: # Return everything we've got result = self.charbuffer self.charbuffer = self._empty_charbuffer else: # Return the first chars characters result = self.charbuffer[:chars] self.charbuffer = self.charbuffer[chars:] return result
def readline(self, size=None, keepends=True):
""" Read one line from the input stream and return the decoded data.
size, if given, is passed as size argument to the read() method.
""" # If we have lines cached from an earlier read, return # them unconditionally if self.linebuffer: line = self.linebuffer[0] del self.linebuffer[0] if len(self.linebuffer) == 1: # revert to charbuffer mode; we might need more data # next time self.charbuffer = self.linebuffer[0] self.linebuffer = None if not keepends: line = line.splitlines(keepends=False)[0] return line
readsize = size or 72 line = self._empty_charbuffer # If size is given, we call read() only once while True: data = self.read(readsize, firstline=True) if data: # If we're at a "\r" read one extra character (which might # be a "\n") to get a proper line ending. If the stream is # temporarily exhausted we return the wrong line ending. if (isinstance(data, str) and data.endswith("\r")) or \ (isinstance(data, bytes) and data.endswith(b"\r")): data += self.read(size=1, chars=1)
line += data lines = line.splitlines(keepends=True) if lines: if len(lines) > 1: # More than one line result; the first line is a full line # to return line = lines[0] del lines[0] if len(lines) > 1: # cache the remaining lines lines[-1] += self.charbuffer self.linebuffer = lines self.charbuffer = None else: # only one remaining line, put it back into charbuffer self.charbuffer = lines[0] + self.charbuffer if not keepends: line = line.splitlines(keepends=False)[0] break line0withend = lines[0] line0withoutend = lines[0].splitlines(keepends=False)[0] if line0withend != line0withoutend: # We really have a line end # Put the rest back together and keep it until the next call self.charbuffer = self._empty_charbuffer.join(lines[1:]) + \ self.charbuffer if keepends: line = line0withend else: line = line0withoutend break # we didn't get anything or this was our only try if not data or size is not None: if line and not keepends: line = line.splitlines(keepends=False)[0] break if readsize < 8000: readsize *= 2 return line
def readlines(self, sizehint=None, keepends=True):
""" Read all lines available on the input stream and return them as a list.
Line breaks are implemented using the codec's decoder method and are included in the list entries.
sizehint, if given, is ignored since there is no efficient way to finding the true end-of-line.
""" data = self.read() return data.splitlines(keepends)
def reset(self):
""" Resets the codec buffers used for keeping internal state.
Note that no stream repositioning should take place. This method is primarily intended to be able to recover from decoding errors.
""" self.bytebuffer = b"" self.charbuffer = self._empty_charbuffer self.linebuffer = None
def seek(self, offset, whence=0): """ Set the input stream's current position.
Resets the codec buffers used for keeping state. """ self.stream.seek(offset, whence) self.reset()
def __next__(self):
""" Return the next decoded line from the input stream.""" line = self.readline() if line: return line raise StopIteration
def __iter__(self): return self
def __getattr__(self, name, getattr=getattr):
""" Inherit all other methods from the underlying stream. """ return getattr(self.stream, name)
def __enter__(self): return self
def __exit__(self, type, value, tb): self.stream.close()
###
class StreamReaderWriter:
""" StreamReaderWriter instances allow wrapping streams which work in both read and write modes.
The design is such that one can use the factory functions returned by the codec.lookup() function to construct the instance.
""" # Optional attributes set by the file wrappers below encoding = 'unknown'
def __init__(self, stream, Reader, Writer, errors='strict'):
""" Creates a StreamReaderWriter instance.
stream must be a Stream-like object.
Reader, Writer must be factory functions or classes providing the StreamReader, StreamWriter interface resp.
Error handling is done in the same way as defined for the StreamWriter/Readers.
""" self.stream = stream self.reader = Reader(stream, errors) self.writer = Writer(stream, errors) self.errors = errors
def read(self, size=-1):
return self.reader.read(size)
def readline(self, size=None):
return self.reader.readline(size)
def readlines(self, sizehint=None):
return self.reader.readlines(sizehint)
def __next__(self):
""" Return the next decoded line from the input stream.""" return next(self.reader)
def __iter__(self): return self
def write(self, data):
return self.writer.write(data)
def writelines(self, list):
return self.writer.writelines(list)
def reset(self):
self.reader.reset() self.writer.reset()
def seek(self, offset, whence=0): self.stream.seek(offset, whence) self.reader.reset() if whence == 0 and offset == 0: self.writer.reset()
def __getattr__(self, name, getattr=getattr):
""" Inherit all other methods from the underlying stream. """ return getattr(self.stream, name)
# these are needed to make "with StreamReaderWriter(...)" work properly
def __enter__(self): return self
def __exit__(self, type, value, tb): self.stream.close()
###
class StreamRecoder:
""" StreamRecoder instances translate data from one encoding to another.
They use the complete set of APIs returned by the codecs.lookup() function to implement their task.
Data written to the StreamRecoder is first decoded into an intermediate format (depending on the "decode" codec) and then written to the underlying stream using an instance of the provided Writer class.
In the other direction, data is read from the underlying stream using a Reader instance and then encoded and returned to the caller.
""" # Optional attributes set by the file wrappers below data_encoding = 'unknown' file_encoding = 'unknown'
def __init__(self, stream, encode, decode, Reader, Writer, errors='strict'):
""" Creates a StreamRecoder instance which implements a two-way conversion: encode and decode work on the frontend (the data visible to .read() and .write()) while Reader and Writer work on the backend (the data in stream).
You can use these objects to do transparent transcodings from e.g. latin-1 to utf-8 and back.
stream must be a file-like object.
encode and decode must adhere to the Codec interface; Reader and Writer must be factory functions or classes providing the StreamReader and StreamWriter interfaces resp.
Error handling is done in the same way as defined for the StreamWriter/Readers.
""" self.stream = stream self.encode = encode self.decode = decode self.reader = Reader(stream, errors) self.writer = Writer(stream, errors) self.errors = errors
def read(self, size=-1):
data = self.reader.read(size) data, bytesencoded = self.encode(data, self.errors) return data
def readline(self, size=None):
if size is None: data = self.reader.readline() else: data = self.reader.readline(size) data, bytesencoded = self.encode(data, self.errors) return data
def readlines(self, sizehint=None):
data = self.reader.read() data, bytesencoded = self.encode(data, self.errors) return data.splitlines(keepends=True)
def __next__(self):
""" Return the next decoded line from the input stream.""" data = next(self.reader) data, bytesencoded = self.encode(data, self.errors) return data
def __iter__(self): return self
def write(self, data):
data, bytesdecoded = self.decode(data, self.errors) return self.writer.write(data)
def writelines(self, list):
data = b''.join(list) data, bytesdecoded = self.decode(data, self.errors) return self.writer.write(data)
def reset(self):
self.reader.reset() self.writer.reset()
def seek(self, offset, whence=0): # Seeks must be propagated to both the readers and writers # as they might need to reset their internal buffers. self.reader.seek(offset, whence) self.writer.seek(offset, whence)
def __getattr__(self, name, getattr=getattr):
""" Inherit all other methods from the underlying stream. """ return getattr(self.stream, name)
def __enter__(self): return self
def __exit__(self, type, value, tb): self.stream.close()
### Shortcuts
def open(filename, mode='r', encoding=None, errors='strict', buffering=-1):
""" Open an encoded file using the given mode and return a wrapped version providing transparent encoding/decoding.
Note: The wrapped version will only accept the object format defined by the codecs, i.e. Unicode objects for most builtin codecs. Output is also codec dependent and will usually be Unicode as well.
If encoding is not None, then the underlying encoded files are always opened in binary mode. The default file mode is 'r', meaning to open the file in read mode.
encoding specifies the encoding which is to be used for the file.
errors may be given to define the error handling. It defaults to 'strict' which causes ValueErrors to be raised in case an encoding error occurs.
buffering has the same meaning as for the builtin open() API. It defaults to -1 which means that the default buffer size will be used.
The returned wrapped file object provides an extra attribute .encoding which allows querying the used encoding. This attribute is only available if an encoding was specified as parameter.
""" if encoding is not None and \ 'b' not in mode: # Force opening of the file in binary mode mode = mode + 'b' file = builtins.open(filename, mode, buffering) if encoding is None: return file
try: info = lookup(encoding) srw = StreamReaderWriter(file, info.streamreader, info.streamwriter, errors) # Add attributes to simplify introspection srw.encoding = encoding return srw except: file.close() raise
def EncodedFile(file, data_encoding, file_encoding=None, errors='strict'):
""" Return a wrapped version of file which provides transparent encoding translation.
Data written to the wrapped file is decoded according to the given data_encoding and then encoded to the underlying file using file_encoding. The intermediate data type will usually be Unicode but depends on the specified codecs.
Bytes read from the file are decoded using file_encoding and then passed back to the caller encoded using data_encoding.
If file_encoding is not given, it defaults to data_encoding.
errors may be given to define the error handling. It defaults to 'strict' which causes ValueErrors to be raised in case an encoding error occurs.
The returned wrapped file object provides two extra attributes .data_encoding and .file_encoding which reflect the given parameters of the same name. The attributes can be used for introspection by Python programs.
""" if file_encoding is None: file_encoding = data_encoding data_info = lookup(data_encoding) file_info = lookup(file_encoding) sr = StreamRecoder(file, data_info.encode, data_info.decode, file_info.streamreader, file_info.streamwriter, errors) # Add attributes to simplify introspection sr.data_encoding = data_encoding sr.file_encoding = file_encoding return sr
### Helpers for codec lookup
def getencoder(encoding):
""" Lookup up the codec for the given encoding and return its encoder function.
Raises a LookupError in case the encoding cannot be found.
""" return lookup(encoding).encode
def getdecoder(encoding):
""" Lookup up the codec for the given encoding and return its decoder function.
Raises a LookupError in case the encoding cannot be found.
""" return lookup(encoding).decode
def getincrementalencoder(encoding):
""" Lookup up the codec for the given encoding and return its IncrementalEncoder class or factory function.
Raises a LookupError in case the encoding cannot be found or the codecs doesn't provide an incremental encoder.
""" encoder = lookup(encoding).incrementalencoder if encoder is None: raise LookupError(encoding) return encoder
def getincrementaldecoder(encoding):
""" Lookup up the codec for the given encoding and return its IncrementalDecoder class or factory function.
Raises a LookupError in case the encoding cannot be found or the codecs doesn't provide an incremental decoder.
""" decoder = lookup(encoding).incrementaldecoder if decoder is None: raise LookupError(encoding) return decoder
def getreader(encoding):
""" Lookup up the codec for the given encoding and return its StreamReader class or factory function.
Raises a LookupError in case the encoding cannot be found.
""" return lookup(encoding).streamreader
def getwriter(encoding):
""" Lookup up the codec for the given encoding and return its StreamWriter class or factory function.
Raises a LookupError in case the encoding cannot be found.
""" return lookup(encoding).streamwriter
def iterencode(iterator, encoding, errors='strict', **kwargs): """ Encoding iterator.
Encodes the input strings from the iterator using an IncrementalEncoder.
errors and kwargs are passed through to the IncrementalEncoder constructor. """ encoder = getincrementalencoder(encoding)(errors, **kwargs) for input in iterator: output = encoder.encode(input) if output: yield output output = encoder.encode("", True) if output: yield output
def iterdecode(iterator, encoding, errors='strict', **kwargs): """ Decoding iterator.
Decodes the input strings from the iterator using an IncrementalDecoder.
errors and kwargs are passed through to the IncrementalDecoder constructor. """ decoder = getincrementaldecoder(encoding)(errors, **kwargs) for input in iterator: output = decoder.decode(input) if output: yield output output = decoder.decode(b"", True) if output: yield output
### Helpers for charmap-based codecs
def make_identity_dict(rng):
""" make_identity_dict(rng) -> dict
Return a dictionary where elements of the rng sequence are mapped to themselves.
""" return {i:i for i in rng}
def make_encoding_map(decoding_map):
""" Creates an encoding map from a decoding map.
If a target mapping in the decoding map occurs multiple times, then that target is mapped to None (undefined mapping), causing an exception when encountered by the charmap codec during translation.
One example where this happens is cp875.py which decodes multiple character to \\u001a.
""" m = {} for k,v in decoding_map.items(): if not v in m: m[v] = k else: m[v] = None return m
### error handlers
try: strict_errors = lookup_error("strict") ignore_errors = lookup_error("ignore") replace_errors = lookup_error("replace") xmlcharrefreplace_errors = lookup_error("xmlcharrefreplace") backslashreplace_errors = lookup_error("backslashreplace") namereplace_errors = lookup_error("namereplace")except LookupError: # In --disable-unicode builds, these error handler are missing strict_errors = None ignore_errors = None replace_errors = None xmlcharrefreplace_errors = None backslashreplace_errors = None namereplace_errors = None
# Tell modulefinder that using codecs probably needs the encodings# package_false = 0if _false: import encodings
### Tests
if __name__ == '__main__':
# Make stdout translate Latin-1 output into UTF-8 output sys.stdout = EncodedFile(sys.stdout, 'latin-1', 'utf-8')
# Have stdin translate Latin-1 input into UTF-8 input sys.stdin = EncodedFile(sys.stdin, 'utf-8', 'latin-1')Python/DLLs/_asyncio.pydDeleted
Python/DLLs/_bz2.pydDeleted
Python/DLLs/_ctypes.pydDeleted
Python/DLLs/_ctypes_test.pydDeleted
Python/DLLs/_decimal.pydDeleted
Python/DLLs/_elementtree.pydDeleted
Python/DLLs/_hashlib.pydDeleted
Python/DLLs/_lzma.pydDeleted
Python/DLLs/_msi.pydDeleted
Python/DLLs/_multiprocessing.pydDeleted
Python/DLLs/_overlapped.pydDeleted
Python/DLLs/_queue.pydDeleted
Python/DLLs/_socket.pydDeleted
Python/DLLs/_sqlite3.pydDeleted
Python/DLLs/_ssl.pydDeleted
Python/DLLs/_testbuffer.pydDeleted
Python/DLLs/_testcapi.pydDeleted
Python/DLLs/_testconsole.pydDeleted
Python/DLLs/_testimportmultiple.pydDeleted
Python/DLLs/_testinternalcapi.pydDeleted
Python/DLLs/_testmultiphase.pydDeleted
Python/DLLs/_tkinter.pydDeleted
Python/DLLs/_uuid.pydDeleted
Python/DLLs/_zoneinfo.pydDeleted
Python/DLLs/pyexpat.pydDeleted
Python/DLLs/select.pydDeleted
Python/DLLs/unicodedata.pydDeleted-3
Python/DLLs/winsound.pydDeleted
Python/DLLs/xxlimited.pydDeleted
Python/DLLs/xxlimited_35.pydDeleted
Python/Lib/abc.pyDeleted-188
Python/Lib/aifc.pyDeleted-947
Python/Lib/antigravity.pyDeleted-17
Python/Lib/argparse.pyDeleted
Python/Lib/ast.pyDeleted-1709
Python/Lib/asynchat.pyDeleted-315
Python/Lib/asyncore.pyDeleted-649
Python/Lib/base64.pyDeleted-603
Python/Lib/bdb.pyDeleted-891
Python/Lib/binhex.pyDeleted-502
Python/Lib/bisect.pyDeleted-110
Python/Lib/bz2.pyDeleted-344
Python/Lib/cProfile.pyDeleted-190
Python/Lib/calendar.pyDeleted-759
Python/Lib/cgi.pyDeleted-1004
Python/Lib/cgitb.pyDeleted-321
Python/Lib/chunk.pyDeleted-169
Python/Lib/cmd.pyDeleted-401
Python/Lib/code.pyDeleted-315
Python/Lib/codecs.pyDeleted-1127