desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return formatted timezone offset (+xx:xx) or None.'
def _tzstr(self, sep=':'):
off = self.utcoffset() if (off is not None): if (off.days < 0): sign = '-' off = (- off) else: sign = '+' (hh, mm) = divmod(off, timedelta(hours=1)) assert (not (mm % timedelta(minutes=1))), 'whole minute' mm //= timedelta(minutes=1)...
'Convert to formal string, for repr().'
def __repr__(self):
if (self._microsecond != 0): s = (', %d, %d' % (self._second, self._microsecond)) elif (self._second != 0): s = (', %d' % self._second) else: s = '' s = ('%s(%d, %d%s)' % (('datetime.' + self.__class__.__name__), self._hour, self._minute, s)) if (self._tzinfo is n...
'Return the time formatted according to ISO. This is \'HH:MM:SS.mmmmmm+zz:zz\', or \'HH:MM:SS+zz:zz\' if self.microsecond == 0.'
def isoformat(self):
s = _format_time(self._hour, self._minute, self._second, self._microsecond) tz = self._tzstr() if tz: s += tz return s
'Format using strftime(). The date part of the timestamp passed to underlying strftime should not be used.'
def strftime(self, fmt):
timetuple = (1900, 1, 1, self._hour, self._minute, self._second, 0, 1, (-1)) return _wrap_strftime(self, fmt, timetuple)
'Return the timezone offset in minutes east of UTC (negative west of UTC).'
def utcoffset(self):
if (self._tzinfo is None): return None offset = self._tzinfo.utcoffset(None) _check_utc_offset('utcoffset', offset) return offset
'Return the timezone name. Note that the name is 100% informational -- there\'s no requirement that it mean anything in particular. For example, "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.'
def tzname(self):
if (self._tzinfo is None): return None name = self._tzinfo.tzname(None) _check_tzname(name) return name
'Return 0 if DST is not in effect, or the DST offset (in minutes eastward) if DST is in effect. This is purely informational; the DST offset has already been added to the UTC offset returned by utcoffset() if applicable, so there\'s no need to consult dst() unless you\'re interested in displaying the DST info.'
def dst(self):
if (self._tzinfo is None): return None offset = self._tzinfo.dst(None) _check_utc_offset('dst', offset) return offset
'Return a new time with new values for the specified fields.'
def replace(self, hour=None, minute=None, second=None, microsecond=None, tzinfo=True):
if (hour is None): hour = self.hour if (minute is None): minute = self.minute if (second is None): second = self.second if (microsecond is None): microsecond = self.microsecond if (tzinfo is True): tzinfo = self.tzinfo _check_time_fields(hour, minute, seco...
'hour (0-23)'
@property def hour(self):
return self._hour
'minute (0-59)'
@property def minute(self):
return self._minute
'second (0-59)'
@property def second(self):
return self._second
'microsecond (0-999999)'
@property def microsecond(self):
return self._microsecond
'timezone info object'
@property def tzinfo(self):
return self._tzinfo
'Construct a datetime from a POSIX timestamp (like time.time()). A timezone info object may be passed in as well.'
@classmethod def fromtimestamp(cls, t, tz=None):
_check_tzinfo_arg(tz) converter = (_time.localtime if (tz is None) else _time.gmtime) (t, frac) = divmod(t, 1.0) us = int((frac * 1000000.0)) if (us == 1000000): t += 1 us = 0 (y, m, d, hh, mm, ss, weekday, jday, dst) = converter(t) ss = min(ss, 59) result = cls(y, m, d, ...
'Construct a UTC datetime from a POSIX timestamp (like time.time()).'
@classmethod def utcfromtimestamp(cls, t):
(t, frac) = divmod(t, 1.0) us = int((frac * 1000000.0)) if (us == 1000000): t += 1 us = 0 (y, m, d, hh, mm, ss, weekday, jday, dst) = _time.gmtime(t) ss = min(ss, 59) return cls(y, m, d, hh, mm, ss, us)
'Construct a datetime from time.time() and optional time zone info.'
@classmethod def now(cls, tz=None):
t = _time.time() return cls.fromtimestamp(t, tz)
'Construct a UTC datetime from time.time().'
@classmethod def utcnow(cls):
t = _time.time() return cls.utcfromtimestamp(t)
'Construct a datetime from a given date and a given time.'
@classmethod def combine(cls, date, time):
if (not isinstance(date, _date_class)): raise TypeError('date argument must be a date instance') if (not isinstance(time, _time_class)): raise TypeError('time argument must be a time instance') return cls(date.year, date.month, date.day, time.hour, time.mi...
'Return local time tuple compatible with time.localtime().'
def timetuple(self):
dst = self.dst() if (dst is None): dst = (-1) elif dst: dst = 1 else: dst = 0 return _build_struct_time(self.year, self.month, self.day, self.hour, self.minute, self.second, dst)
'Return POSIX timestamp as float'
def timestamp(self):
if (self._tzinfo is None): return (_time.mktime((self.year, self.month, self.day, self.hour, self.minute, self.second, (-1), (-1), (-1))) + (self.microsecond / 1000000.0)) else: return (self - _EPOCH).total_seconds()
'Return UTC time tuple compatible with time.gmtime().'
def utctimetuple(self):
offset = self.utcoffset() if offset: self -= offset (y, m, d) = (self.year, self.month, self.day) (hh, mm, ss) = (self.hour, self.minute, self.second) return _build_struct_time(y, m, d, hh, mm, ss, 0)
'Return the date part.'
def date(self):
return date(self._year, self._month, self._day)
'Return the time part, with tzinfo None.'
def time(self):
return time(self.hour, self.minute, self.second, self.microsecond)
'Return the time part, with same tzinfo.'
def timetz(self):
return time(self.hour, self.minute, self.second, self.microsecond, self._tzinfo)
'Return a new datetime with new values for the specified fields.'
def replace(self, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=True):
if (year is None): year = self.year if (month is None): month = self.month if (day is None): day = self.day if (hour is None): hour = self.hour if (minute is None): minute = self.minute if (second is None): second = self.second if (microsecond ...
'Return ctime() style string.'
def ctime(self):
weekday = ((self.toordinal() % 7) or 7) return ('%s %s %2d %02d:%02d:%02d %04d' % (_DAYNAMES[weekday], _MONTHNAMES[self._month], self._day, self._hour, self._minute, self._second, self._year))
'Return the time formatted according to ISO. This is \'YYYY-MM-DD HH:MM:SS.mmmmmm\', or \'YYYY-MM-DD HH:MM:SS\' if self.microsecond == 0. If self.tzinfo is not None, the UTC offset is also attached, giving \'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM\' or \'YYYY-MM-DD HH:MM:SS+HH:MM\'. Optional argument sep specifies the separat...
def isoformat(self, sep='T'):
s = (('%04d-%02d-%02d%c' % (self._year, self._month, self._day, sep)) + _format_time(self._hour, self._minute, self._second, self._microsecond)) off = self.utcoffset() if (off is not None): if (off.days < 0): sign = '-' off = (- off) else: sign = '+' ...
'Convert to formal string, for repr().'
def __repr__(self):
L = [self._year, self._month, self._day, self._hour, self._minute, self._second, self._microsecond] if (L[(-1)] == 0): del L[(-1)] if (L[(-1)] == 0): del L[(-1)] s = ', '.join(map(str, L)) s = ('%s(%s)' % (('datetime.' + self.__class__.__name__), s)) if (self._tzinfo is not No...
'Convert to string, for str().'
def __str__(self):
return self.isoformat(sep=' ')
'string, format -> new datetime parsed from a string (like time.strptime()).'
@classmethod def strptime(cls, date_string, format):
import _strptime return _strptime._strptime_datetime(cls, date_string, format)
'Return the timezone offset in minutes east of UTC (negative west of UTC).'
def utcoffset(self):
if (self._tzinfo is None): return None offset = self._tzinfo.utcoffset(self) _check_utc_offset('utcoffset', offset) return offset
'Return the timezone name. Note that the name is 100% informational -- there\'s no requirement that it mean anything in particular. For example, "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.'
def tzname(self):
name = _call_tzinfo_method(self._tzinfo, 'tzname', self) _check_tzname(name) return name
'Return 0 if DST is not in effect, or the DST offset (in minutes eastward) if DST is in effect. This is purely informational; the DST offset has already been added to the UTC offset returned by utcoffset() if applicable, so there\'s no need to consult dst() unless you\'re interested in displaying the DST info.'
def dst(self):
if (self._tzinfo is None): return None offset = self._tzinfo.dst(self) _check_utc_offset('dst', offset) return offset
'Add a datetime and a timedelta.'
def __add__(self, other):
if (not isinstance(other, timedelta)): return NotImplemented delta = timedelta(self.toordinal(), hours=self._hour, minutes=self._minute, seconds=self._second, microseconds=self._microsecond) delta += other (hour, rem) = divmod(delta.seconds, 3600) (minute, second) = divmod(rem, 60) if (0...
'Subtract two datetimes, or a datetime and a timedelta.'
def __sub__(self, other):
if (not isinstance(other, datetime)): if isinstance(other, timedelta): return (self + (- other)) return NotImplemented days1 = self.toordinal() days2 = other.toordinal() secs1 = ((self._second + (self._minute * 60)) + (self._hour * 3600)) secs2 = ((other._second + (other....
'pickle support'
def __getinitargs__(self):
if (self._name is None): return (self._offset,) return (self._offset, self._name)
'Convert to formal string, for repr(). >>> tz = timezone.utc >>> repr(tz) \'datetime.timezone.utc\' >>> tz = timezone(timedelta(hours=-5), \'EST\') >>> repr(tz) "datetime.timezone(datetime.timedelta(-1, 68400), \'EST\')"'
def __repr__(self):
if (self is self.utc): return 'datetime.timezone.utc' if (self._name is None): return ('%s(%r)' % (('datetime.' + self.__class__.__name__), self._offset)) return ('%s(%r, %r)' % (('datetime.' + self.__class__.__name__), self._offset, self._name))
'Run the callback unless it has already been called or cancelled'
def __call__(self, wr=None, _finalizer_registry=_finalizer_registry, sub_debug=sub_debug, getpid=os.getpid):
try: del _finalizer_registry[self._key] except KeyError: sub_debug('finalizer no longer registered') else: if (self._pid != getpid()): sub_debug('finalizer ignored because different process') res = None else: sub_debug(...
'Cancel finalization of the object'
def cancel(self):
try: del _finalizer_registry[self._key] except KeyError: pass else: self._weakref = self._callback = self._args = self._kwargs = self._key = None
'Return whether this finalizer is still waiting to invoke callback'
def still_active(self):
return (self._key in _finalizer_registry)
'Register a reduce function for a type.'
@classmethod def register(cls, type, reduce):
cls._extra_reducers[type] = reduce
'True if the connection is closed'
@property def closed(self):
return (self._handle is None)
'True if the connection is readable'
@property def readable(self):
return self._readable
'True if the connection is writable'
@property def writable(self):
return self._writable
'File descriptor or handle of the connection'
def fileno(self):
self._check_closed() return self._handle
'Close the connection'
def close(self):
if (self._handle is not None): try: self._close() finally: self._handle = None
'Send the bytes data from a bytes-like object'
def send_bytes(self, buf, offset=0, size=None):
self._check_closed() self._check_writable() m = memoryview(buf) if (m.itemsize > 1): m = memoryview(bytes(m)) n = len(m) if (offset < 0): raise ValueError('offset is negative') if (n < offset): raise ValueError('buffer length < offset') if (size is ...
'Send a (picklable) object'
def send(self, obj):
self._check_closed() self._check_writable() self._send_bytes(ForkingPickler.dumps(obj))
'Receive bytes data as a bytes object.'
def recv_bytes(self, maxlength=None):
self._check_closed() self._check_readable() if ((maxlength is not None) and (maxlength < 0)): raise ValueError('negative maxlength') buf = self._recv_bytes(maxlength) if (buf is None): self._bad_message_length() return buf.getvalue()
'Receive bytes data into a writeable buffer-like object. Return the number of bytes read.'
def recv_bytes_into(self, buf, offset=0):
self._check_closed() self._check_readable() with memoryview(buf) as m: itemsize = m.itemsize bytesize = (itemsize * len(m)) if (offset < 0): raise ValueError('negative offset') elif (offset > bytesize): raise ValueError('offset too large') ...
'Receive a (picklable) object'
def recv(self):
self._check_closed() self._check_readable() buf = self._recv_bytes() return ForkingPickler.loads(buf.getbuffer())
'Whether there is any input available to be read'
def poll(self, timeout=0.0):
self._check_closed() self._check_readable() return self._poll(timeout)
'Accept a connection on the bound socket or named pipe of `self`. Returns a `Connection` object.'
def accept(self):
if (self._listener is None): raise OSError('listener is closed') c = self._listener.accept() if self._authkey: deliver_challenge(c, self._authkey) answer_challenge(c, self._authkey) return c
'Close the bound socket or named pipe of `self`.'
def close(self):
if (self._listener is not None): self._listener.close() self._listener = None
'Run the server forever'
def serve_forever(self):
self.stop_event = threading.Event() process.current_process()._manager_server = self try: accepter = threading.Thread(target=self.accepter) accepter.daemon = True accepter.start() try: while (not self.stop_event.is_set()): self.stop_event.wait(1) ...
'Handle a new connection'
def handle_request(self, c):
funcname = result = request = None try: connection.deliver_challenge(c, self.authkey) connection.answer_challenge(c, self.authkey) request = c.recv() (ignore, funcname, args, kwds) = request assert (funcname in self.public), ('%r unrecognized' % funcname) func ...
'Handle requests from the proxies in a particular process/thread'
def serve_client(self, conn):
util.debug('starting server thread to service %r', threading.current_thread().name) recv = conn.recv send = conn.send id_to_obj = self.id_to_obj while (not self.stop_event.is_set()): try: methodname = obj = None request = recv() (ident, meth...
'Return some info --- useful to spot problems with refcounting'
def debug_info(self, c):
self.mutex.acquire() try: result = [] keys = list(self.id_to_obj.keys()) keys.sort() for ident in keys: if (ident != '0'): result.append((' %s: refcount=%s\n %s' % (ident, self.id_to_refcount[ident], str...
'Number of shared objects'
def number_of_objects(self, c):
return (len(self.id_to_obj) - 1)
'Shutdown this process'
def shutdown(self, c):
try: util.debug('manager received shutdown message') c.send(('#RETURN', None)) except: import traceback traceback.print_exc() finally: self.stop_event.set()
'Create a new shared object and return its id'
def create(self, c, typeid, *args, **kwds):
self.mutex.acquire() try: (callable, exposed, method_to_typeid, proxytype) = self.registry[typeid] if (callable is None): assert ((len(args) == 1) and (not kwds)) obj = args[0] else: obj = callable(*args, **kwds) if (exposed is None): ...
'Return the methods of the shared object indicated by token'
def get_methods(self, c, token):
return tuple(self.id_to_obj[token.id][1])
'Spawn a new thread to serve this connection'
def accept_connection(self, c, name):
threading.current_thread().name = name c.send(('#RETURN', None)) self.serve_client(c)
'Return server object with serve_forever() method and address attribute'
def get_server(self):
assert (self._state.value == State.INITIAL) return Server(self._registry, self._address, self._authkey, self._serializer)
'Connect manager object to the server process'
def connect(self):
(Listener, Client) = listener_client[self._serializer] conn = Client(self._address, authkey=self._authkey) dispatch(conn, None, 'dummy') self._state.value = State.STARTED
'Spawn a server process for this manager object'
def start(self, initializer=None, initargs=()):
assert (self._state.value == State.INITIAL) if ((initializer is not None) and (not callable(initializer))): raise TypeError('initializer must be a callable') (reader, writer) = connection.Pipe(duplex=False) self._process = self._ctx.Process(target=type(self)._run_server, args=(self._...
'Create a server, report its address and run it'
@classmethod def _run_server(cls, registry, address, authkey, serializer, writer, initializer=None, initargs=()):
if (initializer is not None): initializer(*initargs) server = cls._Server(registry, address, authkey, serializer) writer.send(server.address) writer.close() util.info('manager serving at %r', server.address) server.serve_forever()
'Create a new shared object; return the token and exposed tuple'
def _create(self, typeid, *args, **kwds):
assert (self._state.value == State.STARTED), 'server not yet started' conn = self._Client(self._address, authkey=self._authkey) try: (id, exposed) = dispatch(conn, None, 'create', ((typeid,) + args), kwds) finally: conn.close() return (Token(typeid, self._address, id), expos...
'Join the manager process (if it has been spawned)'
def join(self, timeout=None):
if (self._process is not None): self._process.join(timeout) if (not self._process.is_alive()): self._process = None
'Return some info about the servers shared objects and connections'
def _debug_info(self):
conn = self._Client(self._address, authkey=self._authkey) try: return dispatch(conn, None, 'debug_info') finally: conn.close()
'Return the number of shared objects'
def _number_of_objects(self):
conn = self._Client(self._address, authkey=self._authkey) try: return dispatch(conn, None, 'number_of_objects') finally: conn.close()
'Shutdown the manager process; will be registered as a finalizer'
@staticmethod def _finalize_manager(process, address, authkey, state, _Client):
if process.is_alive(): util.info('sending shutdown message to manager') try: conn = _Client(address, authkey=authkey) try: dispatch(conn, None, 'shutdown') finally: conn.close() except Exception: pass...
'Register a typeid with the manager type'
@classmethod def register(cls, typeid, callable=None, proxytype=None, exposed=None, method_to_typeid=None, create_method=True):
if ('_registry' not in cls.__dict__): cls._registry = cls._registry.copy() if (proxytype is None): proxytype = AutoProxy exposed = (exposed or getattr(proxytype, '_exposed_', None)) method_to_typeid = (method_to_typeid or getattr(proxytype, '_method_to_typeid_', None)) if method_to_t...
'Try to call a method of the referrent and return a copy of the result'
def _callmethod(self, methodname, args=(), kwds={}):
try: conn = self._tls.connection except AttributeError: util.debug('thread %r does not own a connection', threading.current_thread().name) self._connect() conn = self._tls.connection conn.send((self._id, methodname, args, kwds)) (kind, result) = conn.rec...
'Get a copy of the value of the referent'
def _getvalue(self):
return self._callmethod('#GETVALUE')
'Return representation of the referent (or a fall-back if that fails)'
def __str__(self):
try: return self._callmethod('__repr__') except Exception: return (repr(self)[:(-1)] + "; '__str__()' failed>")
'Register resource, returning an identifier.'
def register(self, send, close):
with self._lock: if (self._address is None): self._start() self._key += 1 self._cache[self._key] = (send, close) return (self._address, self._key)
'Return connection from which to receive identified resource.'
@staticmethod def get_connection(ident):
from .connection import Client (address, key) = ident c = Client(address, authkey=process.current_process().authkey) c.send((key, os.getpid())) return c
'Stop the background thread and clear registered resources.'
def stop(self, timeout=None):
from .connection import Client with self._lock: if (self._address is not None): c = Client(self._address, authkey=process.current_process().authkey) c.send(None) c.close() self._thread.join(timeout) if self._thread.is_alive(): u...
'Cleanup after any worker processes which have exited due to reaching their specified lifetime. Returns True if any workers were cleaned up.'
def _join_exited_workers(self):
cleaned = False for i in reversed(range(len(self._pool))): worker = self._pool[i] if (worker.exitcode is not None): util.debug(('cleaning up worker %d' % i)) worker.join() cleaned = True del self._pool[i] return cleaned
'Bring the number of pool processes up to the specified number, for use after reaping workers which have exited.'
def _repopulate_pool(self):
for i in range((self._processes - len(self._pool))): w = self.Process(target=worker, args=(self._inqueue, self._outqueue, self._initializer, self._initargs, self._maxtasksperchild, self._wrap_exception)) self._pool.append(w) w.name = w.name.replace('Process', 'PoolWorker') w.daemon =...
'Clean up any exited workers and start replacements for them.'
def _maintain_pool(self):
if self._join_exited_workers(): self._repopulate_pool()
'Equivalent of `func(*args, **kwds)`.'
def apply(self, func, args=(), kwds={}):
assert (self._state == RUN) return self.apply_async(func, args, kwds).get()
'Apply `func` to each element in `iterable`, collecting the results in a list that is returned.'
def map(self, func, iterable, chunksize=None):
return self._map_async(func, iterable, mapstar, chunksize).get()
'Like `map()` method but the elements of the `iterable` are expected to be iterables as well and will be unpacked as arguments. Hence `func` and (a, b) becomes func(a, b).'
def starmap(self, func, iterable, chunksize=None):
return self._map_async(func, iterable, starmapstar, chunksize).get()
'Asynchronous version of `starmap()` method.'
def starmap_async(self, func, iterable, chunksize=None, callback=None, error_callback=None):
return self._map_async(func, iterable, starmapstar, chunksize, callback, error_callback)
'Equivalent of `map()` -- can be MUCH slower than `Pool.map()`.'
def imap(self, func, iterable, chunksize=1):
if (self._state != RUN): raise ValueError('Pool not running') if (chunksize == 1): result = IMapIterator(self._cache) self._taskqueue.put((((result._job, i, func, (x,), {}) for (i, x) in enumerate(iterable)), result._set_length)) return result else: assert (chun...
'Like `imap()` method but ordering of results is arbitrary.'
def imap_unordered(self, func, iterable, chunksize=1):
if (self._state != RUN): raise ValueError('Pool not running') if (chunksize == 1): result = IMapUnorderedIterator(self._cache) self._taskqueue.put((((result._job, i, func, (x,), {}) for (i, x) in enumerate(iterable)), result._set_length)) return result else: ass...
'Asynchronous version of `apply()` method.'
def apply_async(self, func, args=(), kwds={}, callback=None, error_callback=None):
if (self._state != RUN): raise ValueError('Pool not running') result = ApplyResult(self._cache, callback, error_callback) self._taskqueue.put(([(result._job, None, func, args, kwds)], None)) return result
'Asynchronous version of `map()` method.'
def map_async(self, func, iterable, chunksize=None, callback=None, error_callback=None):
return self._map_async(func, iterable, mapstar, chunksize, callback, error_callback)
'Helper function to implement map, starmap and their async counterparts.'
def _map_async(self, func, iterable, mapper, chunksize=None, callback=None, error_callback=None):
if (self._state != RUN): raise ValueError('Pool not running') if (not hasattr(iterable, '__len__')): iterable = list(iterable) if (chunksize is None): (chunksize, extra) = divmod(len(iterable), (len(self._pool) * 4)) if extra: chunksize += 1 if (len(iter...
'Make sure that semaphore tracker process is running. This can be run from any process. Usually a child process will use the semaphore created by its parent.'
def ensure_running(self):
with self._lock: if (self._fd is not None): return fds_to_pass = [] try: fds_to_pass.append(sys.stderr.fileno()) except Exception: pass cmd = 'from multiprocessing.semaphore_tracker import main;main(%d)' (r, w) = os.pipe() ...
'Register name of semaphore with semaphore tracker.'
def register(self, name):
self._send('REGISTER', name)
'Unregister name of semaphore with semaphore tracker.'
def unregister(self, name):
self._send('UNREGISTER', name)
'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.'
def __init__(self, locals=None):
if (locals is None): locals = {'__name__': '__console__', '__doc__': None} self.locals = locals self.compile = CommandCompiler()
'Compile and run some source in the interpreter. Arguments are as for compile_command(). One 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...
def runsource(self, source, filename='<input>', symbol='single'):
try: code = self.compile(source, filename, symbol) except (OverflowError, SyntaxError, ValueError): self.showsyntaxerror(filename) return False if (code is None): return True self.runcode(code) return False
'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 ...
def runcode(self, code):
try: exec code in self.locals except SystemExit: raise except: self.showtraceback()
'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.'...
def showsyntaxerror(self, filename=None):
(type, value, tb) = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb if (filename and (type is SyntaxError)): try: (msg, (dummy_filename, lineno, offset, line)) = value.args except ValueError: pass else: va...
'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.'
def showtraceback(self):
try: (type, value, tb) = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb tblist = traceback.extract_tb(tb) del tblist[:1] lines = traceback.format_list(tblist) if lines: lines.insert(0, 'Traceback (most...
'Write a string. The base implementation writes to sys.stderr; a subclass may replace this with a different implementation.'
def write(self, data):
sys.stderr.write(data)