code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def format(self, record): """ Format the specified record as text. The record's attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message. """ record.message = record.getMessage() if self.usesTime(): record.asctime = self.formatTime(record, self.datefmt) try: s = self._fmt % record.__dict__ except UnicodeDecodeError as e: # Issue 25664. The logger name may be Unicode. Try again ... try: record.name = record.name.decode('utf-8') s = self._fmt % record.__dict__ except UnicodeDecodeError: raise e if record.exc_info: # Cache the traceback text to avoid converting it multiple times # (it's constant anyway) if not record.exc_text: record.exc_text = self.formatException(record.exc_info) if record.exc_text: if s[-1:] != "\n": s = s + "\n" try: s = s + record.exc_text except UnicodeError: # Sometimes filenames have non-ASCII chars, which can lead # to errors when s is Unicode and record.exc_text is str # See issue 8924. # We also use replace for when there are multiple # encodings, e.g. UTF-8 for the filesystem and latin-1 # for a script. See issue 13232. s = s + record.exc_text.decode(sys.getfilesystemencoding(), 'replace') return s
Format the specified record as text. The record's attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.
format
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def __init__(self, linefmt=None): """ Optionally specify a formatter which will be used to format each individual record. """ if linefmt: self.linefmt = linefmt else: self.linefmt = _defaultFormatter
Optionally specify a formatter which will be used to format each individual record.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def format(self, records): """ Format the specified records and return the result as a string. """ rv = "" if len(records) > 0: rv = rv + self.formatHeader(records) for record in records: rv = rv + self.linefmt.format(record) rv = rv + self.formatFooter(records) return rv
Format the specified records and return the result as a string.
format
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def __init__(self, name=''): """ Initialize a filter. Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event. """ self.name = name self.nlen = len(name)
Initialize a filter. Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def filter(self, record): """ Determine if the specified record is to be logged. Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place. """ if self.nlen == 0: return 1 elif self.name == record.name: return 1 elif record.name.find(self.name, 0, self.nlen) != 0: return 0 return (record.name[self.nlen] == ".")
Determine if the specified record is to be logged. Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place.
filter
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def filter(self, record): """ Determine if a record is loggable by consulting all the filters. The default is to allow the record to be logged; any filter can veto this and the record is then dropped. Returns a zero value if a record is to be dropped, else non-zero. """ rv = 1 for f in self.filters: if not f.filter(record): rv = 0 break return rv
Determine if a record is loggable by consulting all the filters. The default is to allow the record to be logged; any filter can veto this and the record is then dropped. Returns a zero value if a record is to be dropped, else non-zero.
filter
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def _removeHandlerRef(wr): """ Remove a handler reference from the internal cleanup list. """ # This function can be called during module teardown, when globals are # set to None. It can also be called from another thread. So we need to # pre-emptively grab the necessary globals and check if they're None, # to prevent race conditions and failures during interpreter shutdown. acquire, release, handlers = _acquireLock, _releaseLock, _handlerList if acquire and release and handlers: acquire() try: if wr in handlers: handlers.remove(wr) finally: release()
Remove a handler reference from the internal cleanup list.
_removeHandlerRef
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def _addHandlerRef(handler): """ Add a handler to the internal cleanup list using a weak reference. """ _acquireLock() try: _handlerList.append(weakref.ref(handler, _removeHandlerRef)) finally: _releaseLock()
Add a handler to the internal cleanup list using a weak reference.
_addHandlerRef
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def __init__(self, level=NOTSET): """ Initializes the instance - basically setting the formatter to None and the filter list to empty. """ Filterer.__init__(self) self._name = None self.level = _checkLevel(level) self.formatter = None # Add the handler to the global _handlerList (for cleanup on shutdown) _addHandlerRef(self) self.createLock()
Initializes the instance - basically setting the formatter to None and the filter list to empty.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def createLock(self): """ Acquire a thread lock for serializing access to the underlying I/O. """ if thread: self.lock = threading.RLock() else: self.lock = None
Acquire a thread lock for serializing access to the underlying I/O.
createLock
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def format(self, record): """ Format the specified record. If a formatter is set, use it. Otherwise, use the default formatter for the module. """ if self.formatter: fmt = self.formatter else: fmt = _defaultFormatter return fmt.format(record)
Format the specified record. If a formatter is set, use it. Otherwise, use the default formatter for the module.
format
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def emit(self, record): """ Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a NotImplementedError. """ raise NotImplementedError('emit must be implemented ' 'by Handler subclasses')
Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a NotImplementedError.
emit
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def close(self): """ Tidy up any resources used by the handler. This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods. """ #get the module data lock, as we're updating a shared structure. _acquireLock() try: #unlikely to raise an exception, but you never know... if self._name and self._name in _handlers: del _handlers[self._name] finally: _releaseLock()
Tidy up any resources used by the handler. This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods.
close
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def __init__(self, stream=None): """ Initialize the handler. If stream is not specified, sys.stderr is used. """ Handler.__init__(self) if stream is None: stream = sys.stderr self.stream = stream
Initialize the handler. If stream is not specified, sys.stderr is used.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def __init__(self, filename, mode='a', encoding=None, delay=0): """ Open the specified file and use it as the stream for logging. """ #keep the absolute path, otherwise derived classes which use this #may come a cropper when the current directory changes if codecs is None: encoding = None self.baseFilename = os.path.abspath(filename) self.mode = mode self.encoding = encoding self.delay = delay if delay: #We don't open the stream, but we still need to call the #Handler constructor to set level, formatter, lock etc. Handler.__init__(self) self.stream = None else: StreamHandler.__init__(self, self._open())
Open the specified file and use it as the stream for logging.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def _open(self): """ Open the current base file with the (original) mode and encoding. Return the resulting stream. """ if self.encoding is None: stream = open(self.baseFilename, self.mode) else: stream = codecs.open(self.baseFilename, self.mode, self.encoding) return stream
Open the current base file with the (original) mode and encoding. Return the resulting stream.
_open
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def __init__(self, alogger): """ Initialize with the specified logger being a child of this placeholder. """ #self.loggers = [alogger] self.loggerMap = { alogger : None }
Initialize with the specified logger being a child of this placeholder.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def append(self, alogger): """ Add the specified logger as a child of this placeholder. """ #if alogger not in self.loggers: if alogger not in self.loggerMap: #self.loggers.append(alogger) self.loggerMap[alogger] = None
Add the specified logger as a child of this placeholder.
append
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def setLoggerClass(klass): """ Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__() """ if klass != Logger: if not issubclass(klass, Logger): raise TypeError("logger not derived from logging.Logger: " + klass.__name__) global _loggerClass _loggerClass = klass
Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__()
setLoggerClass
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def __init__(self, rootnode): """ Initialize the manager with the root node of the logger hierarchy. """ self.root = rootnode self.disable = 0 self.emittedNoHandlerWarning = 0 self.loggerDict = {} self.loggerClass = None
Initialize the manager with the root node of the logger hierarchy.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def getLogger(self, name): """ Get a logger with the specified name (channel name), creating it if it doesn't yet exist. This name is a dot-separated hierarchical name, such as "a", "a.b", "a.b.c" or similar. If a PlaceHolder existed for the specified name [i.e. the logger didn't exist but a child of it did], replace it with the created logger and fix up the parent/child references which pointed to the placeholder to now point to the logger. """ rv = None if not isinstance(name, basestring): raise TypeError('A logger name must be string or Unicode') if isinstance(name, unicode): name = name.encode('utf-8') _acquireLock() try: if name in self.loggerDict: rv = self.loggerDict[name] if isinstance(rv, PlaceHolder): ph = rv rv = (self.loggerClass or _loggerClass)(name) rv.manager = self self.loggerDict[name] = rv self._fixupChildren(ph, rv) self._fixupParents(rv) else: rv = (self.loggerClass or _loggerClass)(name) rv.manager = self self.loggerDict[name] = rv self._fixupParents(rv) finally: _releaseLock() return rv
Get a logger with the specified name (channel name), creating it if it doesn't yet exist. This name is a dot-separated hierarchical name, such as "a", "a.b", "a.b.c" or similar. If a PlaceHolder existed for the specified name [i.e. the logger didn't exist but a child of it did], replace it with the created logger and fix up the parent/child references which pointed to the placeholder to now point to the logger.
getLogger
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def setLoggerClass(self, klass): """ Set the class to be used when instantiating a logger with this Manager. """ if klass != Logger: if not issubclass(klass, Logger): raise TypeError("logger not derived from logging.Logger: " + klass.__name__) self.loggerClass = klass
Set the class to be used when instantiating a logger with this Manager.
setLoggerClass
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def _fixupParents(self, alogger): """ Ensure that there are either loggers or placeholders all the way from the specified logger to the root of the logger hierarchy. """ name = alogger.name i = name.rfind(".") rv = None while (i > 0) and not rv: substr = name[:i] if substr not in self.loggerDict: self.loggerDict[substr] = PlaceHolder(alogger) else: obj = self.loggerDict[substr] if isinstance(obj, Logger): rv = obj else: assert isinstance(obj, PlaceHolder) obj.append(alogger) i = name.rfind(".", 0, i - 1) if not rv: rv = self.root alogger.parent = rv
Ensure that there are either loggers or placeholders all the way from the specified logger to the root of the logger hierarchy.
_fixupParents
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def _fixupChildren(self, ph, alogger): """ Ensure that children of the placeholder ph are connected to the specified logger. """ name = alogger.name namelen = len(name) for c in ph.loggerMap.keys(): #The if means ... if not c.parent.name.startswith(nm) if c.parent.name[:namelen] != name: alogger.parent = c.parent c.parent = alogger
Ensure that children of the placeholder ph are connected to the specified logger.
_fixupChildren
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def __init__(self, name, level=NOTSET): """ Initialize the logger with a name and an optional level. """ Filterer.__init__(self) self.name = name self.level = _checkLevel(level) self.parent = None self.propagate = 1 self.handlers = [] self.disabled = 0
Initialize the logger with a name and an optional level.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def debug(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.debug("Houston, we have a %s", "thorny problem", exc_info=1) """ if self.isEnabledFor(DEBUG): self._log(DEBUG, msg, args, **kwargs)
Log 'msg % args' with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
debug
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def info(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'INFO'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.info("Houston, we have a %s", "interesting problem", exc_info=1) """ if self.isEnabledFor(INFO): self._log(INFO, msg, args, **kwargs)
Log 'msg % args' with severity 'INFO'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
info
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def warning(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'WARNING'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1) """ if self.isEnabledFor(WARNING): self._log(WARNING, msg, args, **kwargs)
Log 'msg % args' with severity 'WARNING'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
warning
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def error(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'ERROR'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.error("Houston, we have a %s", "major problem", exc_info=1) """ if self.isEnabledFor(ERROR): self._log(ERROR, msg, args, **kwargs)
Log 'msg % args' with severity 'ERROR'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.error("Houston, we have a %s", "major problem", exc_info=1)
error
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def exception(self, msg, *args, **kwargs): """ Convenience method for logging an ERROR with exception information. """ kwargs['exc_info'] = 1 self.error(msg, *args, **kwargs)
Convenience method for logging an ERROR with exception information.
exception
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def critical(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'CRITICAL'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.critical("Houston, we have a %s", "major disaster", exc_info=1) """ if self.isEnabledFor(CRITICAL): self._log(CRITICAL, msg, args, **kwargs)
Log 'msg % args' with severity 'CRITICAL'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.critical("Houston, we have a %s", "major disaster", exc_info=1)
critical
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def log(self, level, msg, *args, **kwargs): """ Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.log(level, "We have a %s", "mysterious problem", exc_info=1) """ if not isinstance(level, int): if raiseExceptions: raise TypeError("level must be an integer") else: return if self.isEnabledFor(level): self._log(level, msg, args, **kwargs)
Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
log
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def findCaller(self): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = currentframe() #On some versions of IronPython, currentframe() returns None if #IronPython isn't run with -X:Frames. if f is not None: f = f.f_back rv = "(unknown file)", 0, "(unknown function)" while hasattr(f, "f_code"): co = f.f_code filename = os.path.normcase(co.co_filename) if filename == _srcfile: f = f.f_back continue rv = (co.co_filename, f.f_lineno, co.co_name) break return rv
Find the stack frame of the caller so that we can note the source file name, line number and function name.
findCaller
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None): """ A factory method which can be overridden in subclasses to create specialized LogRecords. """ rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func) if extra is not None: for key in extra: if (key in ["message", "asctime"]) or (key in rv.__dict__): raise KeyError("Attempt to overwrite %r in LogRecord" % key) rv.__dict__[key] = extra[key] return rv
A factory method which can be overridden in subclasses to create specialized LogRecords.
makeRecord
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def _log(self, level, msg, args, exc_info=None, extra=None): """ Low-level logging routine which creates a LogRecord and then calls all the handlers of this logger to handle the record. """ if _srcfile: #IronPython doesn't track Python frames, so findCaller raises an #exception on some versions of IronPython. We trap it here so that #IronPython can use logging. try: fn, lno, func = self.findCaller() except ValueError: fn, lno, func = "(unknown file)", 0, "(unknown function)" else: fn, lno, func = "(unknown file)", 0, "(unknown function)" if exc_info: if not isinstance(exc_info, tuple): exc_info = sys.exc_info() record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra) self.handle(record)
Low-level logging routine which creates a LogRecord and then calls all the handlers of this logger to handle the record.
_log
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def addHandler(self, hdlr): """ Add the specified handler to this logger. """ _acquireLock() try: if not (hdlr in self.handlers): self.handlers.append(hdlr) finally: _releaseLock()
Add the specified handler to this logger.
addHandler
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def removeHandler(self, hdlr): """ Remove the specified handler from this logger. """ _acquireLock() try: if hdlr in self.handlers: self.handlers.remove(hdlr) finally: _releaseLock()
Remove the specified handler from this logger.
removeHandler
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def callHandlers(self, record): """ Pass a record to all relevant handlers. Loop through all handlers for this logger and its parents in the logger hierarchy. If no handler was found, output a one-off error message to sys.stderr. Stop searching up the hierarchy whenever a logger with the "propagate" attribute set to zero is found - that will be the last logger whose handlers are called. """ c = self found = 0 while c: for hdlr in c.handlers: found = found + 1 if record.levelno >= hdlr.level: hdlr.handle(record) if not c.propagate: c = None #break out else: c = c.parent if (found == 0) and raiseExceptions and not self.manager.emittedNoHandlerWarning: sys.stderr.write("No handlers could be found for logger" " \"%s\"\n" % self.name) self.manager.emittedNoHandlerWarning = 1
Pass a record to all relevant handlers. Loop through all handlers for this logger and its parents in the logger hierarchy. If no handler was found, output a one-off error message to sys.stderr. Stop searching up the hierarchy whenever a logger with the "propagate" attribute set to zero is found - that will be the last logger whose handlers are called.
callHandlers
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def getEffectiveLevel(self): """ Get the effective level for this logger. Loop through this logger and its parents in the logger hierarchy, looking for a non-zero logging level. Return the first one found. """ logger = self while logger: if logger.level: return logger.level logger = logger.parent return NOTSET
Get the effective level for this logger. Loop through this logger and its parents in the logger hierarchy, looking for a non-zero logging level. Return the first one found.
getEffectiveLevel
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def isEnabledFor(self, level): """ Is this logger enabled for level 'level'? """ if self.manager.disable >= level: return 0 return level >= self.getEffectiveLevel()
Is this logger enabled for level 'level'?
isEnabledFor
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def getChild(self, suffix): """ Get a logger which is a descendant to this one. This is a convenience method, such that logging.getLogger('abc').getChild('def.ghi') is the same as logging.getLogger('abc.def.ghi') It's useful, for example, when the parent logger is named using __name__ rather than a literal string. """ if self.root is not self: suffix = '.'.join((self.name, suffix)) return self.manager.getLogger(suffix)
Get a logger which is a descendant to this one. This is a convenience method, such that logging.getLogger('abc').getChild('def.ghi') is the same as logging.getLogger('abc.def.ghi') It's useful, for example, when the parent logger is named using __name__ rather than a literal string.
getChild
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def __init__(self, logger, extra): """ Initialize the adapter with a logger and a dict-like object which provides contextual information. This constructor signature allows easy stacking of LoggerAdapters, if so desired. You can effectively pass keyword arguments as shown in the following example: adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2")) """ self.logger = logger self.extra = extra
Initialize the adapter with a logger and a dict-like object which provides contextual information. This constructor signature allows easy stacking of LoggerAdapters, if so desired. You can effectively pass keyword arguments as shown in the following example: adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def process(self, msg, kwargs): """ Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, the keyword args or both. Return the message and kwargs modified (or not) to suit your needs. Normally, you'll only need to override this one method in a LoggerAdapter subclass for your specific needs. """ kwargs["extra"] = self.extra return msg, kwargs
Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, the keyword args or both. Return the message and kwargs modified (or not) to suit your needs. Normally, you'll only need to override this one method in a LoggerAdapter subclass for your specific needs.
process
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def debug(self, msg, *args, **kwargs): """ Delegate a debug call to the underlying logger, after adding contextual information from this adapter instance. """ msg, kwargs = self.process(msg, kwargs) self.logger.debug(msg, *args, **kwargs)
Delegate a debug call to the underlying logger, after adding contextual information from this adapter instance.
debug
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def info(self, msg, *args, **kwargs): """ Delegate an info call to the underlying logger, after adding contextual information from this adapter instance. """ msg, kwargs = self.process(msg, kwargs) self.logger.info(msg, *args, **kwargs)
Delegate an info call to the underlying logger, after adding contextual information from this adapter instance.
info
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def warning(self, msg, *args, **kwargs): """ Delegate a warning call to the underlying logger, after adding contextual information from this adapter instance. """ msg, kwargs = self.process(msg, kwargs) self.logger.warning(msg, *args, **kwargs)
Delegate a warning call to the underlying logger, after adding contextual information from this adapter instance.
warning
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def error(self, msg, *args, **kwargs): """ Delegate an error call to the underlying logger, after adding contextual information from this adapter instance. """ msg, kwargs = self.process(msg, kwargs) self.logger.error(msg, *args, **kwargs)
Delegate an error call to the underlying logger, after adding contextual information from this adapter instance.
error
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def exception(self, msg, *args, **kwargs): """ Delegate an exception call to the underlying logger, after adding contextual information from this adapter instance. """ msg, kwargs = self.process(msg, kwargs) kwargs["exc_info"] = 1 self.logger.error(msg, *args, **kwargs)
Delegate an exception call to the underlying logger, after adding contextual information from this adapter instance.
exception
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def critical(self, msg, *args, **kwargs): """ Delegate a critical call to the underlying logger, after adding contextual information from this adapter instance. """ msg, kwargs = self.process(msg, kwargs) self.logger.critical(msg, *args, **kwargs)
Delegate a critical call to the underlying logger, after adding contextual information from this adapter instance.
critical
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def log(self, level, msg, *args, **kwargs): """ Delegate a log call to the underlying logger, after adding contextual information from this adapter instance. """ msg, kwargs = self.process(msg, kwargs) self.logger.log(level, msg, *args, **kwargs)
Delegate a log call to the underlying logger, after adding contextual information from this adapter instance.
log
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def basicConfig(**kwargs): """ Do basic configuration for the logging system. This function does nothing if the root logger already has handlers configured. It is a convenience method intended for use by simple scripts to do one-shot configuration of the logging package. The default behaviour is to create a StreamHandler which writes to sys.stderr, set a formatter using the BASIC_FORMAT format string, and add the handler to the root logger. A number of optional keyword arguments may be specified, which can alter the default behaviour. filename Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler. filemode Specifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to 'a'). format Use the specified format string for the handler. datefmt Use the specified date/time format. level Set the root logger level to the specified level. stream Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with 'filename' - if both are present, 'stream' is ignored. Note that you could specify a stream created using open(filename, mode) rather than passing the filename and mode in. However, it should be remembered that StreamHandler does not close its stream (since it may be using sys.stdout or sys.stderr), whereas FileHandler closes its stream when the handler is closed. """ # Add thread safety in case someone mistakenly calls # basicConfig() from multiple threads _acquireLock() try: if len(root.handlers) == 0: filename = kwargs.get("filename") if filename: mode = kwargs.get("filemode", 'a') hdlr = FileHandler(filename, mode) else: stream = kwargs.get("stream") hdlr = StreamHandler(stream) fs = kwargs.get("format", BASIC_FORMAT) dfs = kwargs.get("datefmt", None) fmt = Formatter(fs, dfs) hdlr.setFormatter(fmt) root.addHandler(hdlr) level = kwargs.get("level") if level is not None: root.setLevel(level) finally: _releaseLock()
Do basic configuration for the logging system. This function does nothing if the root logger already has handlers configured. It is a convenience method intended for use by simple scripts to do one-shot configuration of the logging package. The default behaviour is to create a StreamHandler which writes to sys.stderr, set a formatter using the BASIC_FORMAT format string, and add the handler to the root logger. A number of optional keyword arguments may be specified, which can alter the default behaviour. filename Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler. filemode Specifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to 'a'). format Use the specified format string for the handler. datefmt Use the specified date/time format. level Set the root logger level to the specified level. stream Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with 'filename' - if both are present, 'stream' is ignored. Note that you could specify a stream created using open(filename, mode) rather than passing the filename and mode in. However, it should be remembered that StreamHandler does not close its stream (since it may be using sys.stdout or sys.stderr), whereas FileHandler closes its stream when the handler is closed.
basicConfig
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def getLogger(name=None): """ Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger. """ if name: return Logger.manager.getLogger(name) else: return root
Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger.
getLogger
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def critical(msg, *args, **kwargs): """ Log a message with severity 'CRITICAL' on the root logger. """ if len(root.handlers) == 0: basicConfig() root.critical(msg, *args, **kwargs)
Log a message with severity 'CRITICAL' on the root logger.
critical
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def error(msg, *args, **kwargs): """ Log a message with severity 'ERROR' on the root logger. """ if len(root.handlers) == 0: basicConfig() root.error(msg, *args, **kwargs)
Log a message with severity 'ERROR' on the root logger.
error
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def exception(msg, *args, **kwargs): """ Log a message with severity 'ERROR' on the root logger, with exception information. """ kwargs['exc_info'] = 1 error(msg, *args, **kwargs)
Log a message with severity 'ERROR' on the root logger, with exception information.
exception
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def warning(msg, *args, **kwargs): """ Log a message with severity 'WARNING' on the root logger. """ if len(root.handlers) == 0: basicConfig() root.warning(msg, *args, **kwargs)
Log a message with severity 'WARNING' on the root logger.
warning
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def info(msg, *args, **kwargs): """ Log a message with severity 'INFO' on the root logger. """ if len(root.handlers) == 0: basicConfig() root.info(msg, *args, **kwargs)
Log a message with severity 'INFO' on the root logger.
info
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def debug(msg, *args, **kwargs): """ Log a message with severity 'DEBUG' on the root logger. """ if len(root.handlers) == 0: basicConfig() root.debug(msg, *args, **kwargs)
Log a message with severity 'DEBUG' on the root logger.
debug
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def log(level, msg, *args, **kwargs): """ Log 'msg % args' with the integer severity 'level' on the root logger. """ if len(root.handlers) == 0: basicConfig() root.log(level, msg, *args, **kwargs)
Log 'msg % args' with the integer severity 'level' on the root logger.
log
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def shutdown(handlerList=_handlerList): """ Perform any cleanup actions in the logging system (e.g. flushing buffers). Should be called at application exit. """ for wr in reversed(handlerList[:]): #errors might occur, for example, if files are locked #we just ignore them if raiseExceptions is not set try: h = wr() if h: try: h.acquire() h.flush() h.close() except (IOError, ValueError): # Ignore errors which might be caused # because handlers have been closed but # references to them are still around at # application exit. pass finally: h.release() except: if raiseExceptions: raise #else, swallow
Perform any cleanup actions in the logging system (e.g. flushing buffers). Should be called at application exit.
shutdown
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def _showwarning(message, category, filename, lineno, file=None, line=None): """ Implementation of showwarnings which redirects to logging, which will first check to see if the file parameter is None. If a file is specified, it will delegate to the original warnings implementation of showwarning. Otherwise, it will call warnings.formatwarning and will log the resulting string to a warnings logger named "py.warnings" with level logging.WARNING. """ if file is not None: if _warnings_showwarning is not None: _warnings_showwarning(message, category, filename, lineno, file, line) else: s = warnings.formatwarning(message, category, filename, lineno, line) logger = getLogger("py.warnings") if not logger.handlers: logger.addHandler(NullHandler()) logger.warning("%s", s)
Implementation of showwarnings which redirects to logging, which will first check to see if the file parameter is None. If a file is specified, it will delegate to the original warnings implementation of showwarning. Otherwise, it will call warnings.formatwarning and will log the resulting string to a warnings logger named "py.warnings" with level logging.WARNING.
_showwarning
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def captureWarnings(capture): """ If capture is true, redirect all warnings to the logging package. If capture is False, ensure that warnings are not redirected to logging but to their original destinations. """ global _warnings_showwarning if capture: if _warnings_showwarning is None: _warnings_showwarning = warnings.showwarning warnings.showwarning = _showwarning else: if _warnings_showwarning is not None: warnings.showwarning = _warnings_showwarning _warnings_showwarning = None
If capture is true, redirect all warnings to the logging package. If capture is False, ensure that warnings are not redirected to logging but to their original destinations.
captureWarnings
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def change_sequence(seq, action, seqno=_Unspecified, cond = _Unspecified): "Change the sequence number of an action in a sequence list" for i in range(len(seq)): if seq[i][0] == action: if cond is _Unspecified: cond = seq[i][1] if seqno is _Unspecified: seqno = seq[i][2] seq[i] = (action, cond, seqno) return raise ValueError, "Action not found in sequence"
Change the sequence number of an action in a sequence list
change_sequence
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/msilib/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/msilib/__init__.py
MIT
def __init__(self, db, cab, basedir, physical, _logical, default, componentflags=None): """Create a new directory in the Directory table. There is a current component at each point in time for the directory, which is either explicitly created through start_component, or implicitly when files are added for the first time. Files are added into the current component, and into the cab file. To create a directory, a base directory object needs to be specified (can be None), the path to the physical directory, and a logical directory name. Default specifies the DefaultDir slot in the directory table. componentflags specifies the default flags that new components get.""" index = 1 _logical = make_id(_logical) logical = _logical while logical in _directories: logical = "%s%d" % (_logical, index) index += 1 _directories.add(logical) self.db = db self.cab = cab self.basedir = basedir self.physical = physical self.logical = logical self.component = None self.short_names = set() self.ids = set() self.keyfiles = {} self.componentflags = componentflags if basedir: self.absolute = os.path.join(basedir.absolute, physical) blogical = basedir.logical else: self.absolute = physical blogical = None add_data(db, "Directory", [(logical, blogical, default)])
Create a new directory in the Directory table. There is a current component at each point in time for the directory, which is either explicitly created through start_component, or implicitly when files are added for the first time. Files are added into the current component, and into the cab file. To create a directory, a base directory object needs to be specified (can be None), the path to the physical directory, and a logical directory name. Default specifies the DefaultDir slot in the directory table. componentflags specifies the default flags that new components get.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/msilib/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/msilib/__init__.py
MIT
def start_component(self, component = None, feature = None, flags = None, keyfile = None, uuid=None): """Add an entry to the Component table, and make this component the current for this directory. If no component name is given, the directory name is used. If no feature is given, the current feature is used. If no flags are given, the directory's default flags are used. If no keyfile is given, the KeyPath is left null in the Component table.""" if flags is None: flags = self.componentflags if uuid is None: uuid = gen_uuid() else: uuid = uuid.upper() if component is None: component = self.logical self.component = component if Win64: flags |= 256 if keyfile: keyid = self.cab.gen_id(self.absolute, keyfile) self.keyfiles[keyfile] = keyid else: keyid = None add_data(self.db, "Component", [(component, uuid, self.logical, flags, None, keyid)]) if feature is None: feature = current_feature add_data(self.db, "FeatureComponents", [(feature.id, component)])
Add an entry to the Component table, and make this component the current for this directory. If no component name is given, the directory name is used. If no feature is given, the current feature is used. If no flags are given, the directory's default flags are used. If no keyfile is given, the KeyPath is left null in the Component table.
start_component
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/msilib/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/msilib/__init__.py
MIT
def add_file(self, file, src=None, version=None, language=None): """Add a file to the current component of the directory, starting a new one if there is no current component. By default, the file name in the source and the file table will be identical. If the src file is specified, it is interpreted relative to the current directory. Optionally, a version and a language can be specified for the entry in the File table.""" if not self.component: self.start_component(self.logical, current_feature, 0) if not src: # Allow relative paths for file if src is not specified src = file file = os.path.basename(file) absolute = os.path.join(self.absolute, src) assert not re.search(r'[\?|><:/*]"', file) # restrictions on long names if file in self.keyfiles: logical = self.keyfiles[file] else: logical = None sequence, logical = self.cab.append(absolute, file, logical) assert logical not in self.ids self.ids.add(logical) short = self.make_short(file) full = "%s|%s" % (short, file) filesize = os.stat(absolute).st_size # constants.msidbFileAttributesVital # Compressed omitted, since it is the database default # could add r/o, system, hidden attributes = 512 add_data(self.db, "File", [(logical, self.component, full, filesize, version, language, attributes, sequence)]) #if not version: # # Add hash if the file is not versioned # filehash = FileHash(absolute, 0) # add_data(self.db, "MsiFileHash", # [(logical, 0, filehash.IntegerData(1), # filehash.IntegerData(2), filehash.IntegerData(3), # filehash.IntegerData(4))]) # Automatically remove .pyc/.pyo files on uninstall (2) # XXX: adding so many RemoveFile entries makes installer unbelievably # slow. So instead, we have to use wildcard remove entries if file.endswith(".py"): add_data(self.db, "RemoveFile", [(logical+"c", self.component, "%sC|%sc" % (short, file), self.logical, 2), (logical+"o", self.component, "%sO|%so" % (short, file), self.logical, 2)]) return logical
Add a file to the current component of the directory, starting a new one if there is no current component. By default, the file name in the source and the file table will be identical. If the src file is specified, it is interpreted relative to the current directory. Optionally, a version and a language can be specified for the entry in the File table.
add_file
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/msilib/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/msilib/__init__.py
MIT
def glob(self, pattern, exclude = None): """Add a list of files to the current component as specified in the glob pattern. Individual files can be excluded in the exclude list.""" files = glob.glob1(self.absolute, pattern) for f in files: if exclude and f in exclude: continue self.add_file(f) return files
Add a list of files to the current component as specified in the glob pattern. Individual files can be excluded in the exclude list.
glob
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/msilib/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/msilib/__init__.py
MIT
def remove_pyc(self): "Remove .pyc/.pyo files on uninstall" add_data(self.db, "RemoveFile", [(self.component+"c", self.component, "*.pyc", self.logical, 2), (self.component+"o", self.component, "*.pyo", self.logical, 2)])
Remove .pyc/.pyo files on uninstall
remove_pyc
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/msilib/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/msilib/__init__.py
MIT
def arbitrary_address(family): ''' Return an arbitrary free address for the given family ''' if family == 'AF_INET': return ('localhost', 0) elif family == 'AF_UNIX': return tempfile.mktemp(prefix='listener-', dir=get_temp_dir()) elif family == 'AF_PIPE': return tempfile.mktemp(prefix=r'\\.\pipe\pyc-%d-%d-' % (os.getpid(), _mmap_counter.next()), dir="") else: raise ValueError('unrecognized family')
Return an arbitrary free address for the given family
arbitrary_address
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/connection.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/connection.py
MIT
def address_type(address): ''' Return the types of the address This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE' ''' if type(address) == tuple: return 'AF_INET' elif type(address) is str and address.startswith('\\\\'): return 'AF_PIPE' elif type(address) is str: return 'AF_UNIX' else: raise ValueError('address type of %r unrecognized' % address)
Return the types of the address This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE'
address_type
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/connection.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/connection.py
MIT
def accept(self): ''' Accept a connection on the bound socket or named pipe of `self`. Returns a `Connection` object. ''' c = self._listener.accept() if self._authkey: deliver_challenge(c, self._authkey) answer_challenge(c, self._authkey) return c
Accept a connection on the bound socket or named pipe of `self`. Returns a `Connection` object.
accept
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/connection.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/connection.py
MIT
def Client(address, family=None, authkey=None): ''' Returns a connection to the address of a `Listener` ''' family = family or address_type(address) if family == 'AF_PIPE': c = PipeClient(address) else: c = SocketClient(address) if authkey is not None and not isinstance(authkey, bytes): raise TypeError, 'authkey should be a byte string' if authkey is not None: answer_challenge(c, authkey) deliver_challenge(c, authkey) return c
Returns a connection to the address of a `Listener`
Client
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/connection.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/connection.py
MIT
def Pipe(duplex=True): ''' Returns pair of connection objects at either end of a pipe ''' if duplex: s1, s2 = socket.socketpair() s1.setblocking(True) s2.setblocking(True) c1 = _multiprocessing.Connection(os.dup(s1.fileno())) c2 = _multiprocessing.Connection(os.dup(s2.fileno())) s1.close() s2.close() else: fd1, fd2 = os.pipe() c1 = _multiprocessing.Connection(fd1, writable=False) c2 = _multiprocessing.Connection(fd2, readable=False) return c1, c2
Returns pair of connection objects at either end of a pipe
Pipe
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/connection.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/connection.py
MIT
def Pipe(duplex=True): ''' Returns pair of connection objects at either end of a pipe ''' address = arbitrary_address('AF_PIPE') if duplex: openmode = win32.PIPE_ACCESS_DUPLEX access = win32.GENERIC_READ | win32.GENERIC_WRITE obsize, ibsize = BUFSIZE, BUFSIZE else: openmode = win32.PIPE_ACCESS_INBOUND access = win32.GENERIC_WRITE obsize, ibsize = 0, BUFSIZE h1 = win32.CreateNamedPipe( address, openmode, win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE | win32.PIPE_WAIT, 1, obsize, ibsize, win32.NMPWAIT_WAIT_FOREVER, win32.NULL ) h2 = win32.CreateFile( address, access, 0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL ) win32.SetNamedPipeHandleState( h2, win32.PIPE_READMODE_MESSAGE, None, None ) try: win32.ConnectNamedPipe(h1, win32.NULL) except WindowsError, e: if e.args[0] != win32.ERROR_PIPE_CONNECTED: raise c1 = _multiprocessing.PipeConnection(h1, writable=duplex) c2 = _multiprocessing.PipeConnection(h2, readable=duplex) return c1, c2
Returns pair of connection objects at either end of a pipe
Pipe
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/connection.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/connection.py
MIT
def SocketClient(address): ''' Return a connection object connected to the socket given by `address` ''' family = getattr(socket, address_type(address)) t = _init_timeout() while 1: s = socket.socket(family) s.setblocking(True) try: s.connect(address) except socket.error, e: s.close() if e.args[0] != errno.ECONNREFUSED or _check_timeout(t): debug('failed to connect to address %s', address) raise time.sleep(0.01) else: break else: raise fd = duplicate(s.fileno()) conn = _multiprocessing.Connection(fd) s.close() return conn
Return a connection object connected to the socket given by `address`
SocketClient
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/connection.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/connection.py
MIT
def PipeClient(address): ''' Return a connection object connected to the pipe given by `address` ''' t = _init_timeout() while 1: try: win32.WaitNamedPipe(address, 1000) h = win32.CreateFile( address, win32.GENERIC_READ | win32.GENERIC_WRITE, 0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL ) except WindowsError, e: if e.args[0] not in (win32.ERROR_SEM_TIMEOUT, win32.ERROR_PIPE_BUSY) or _check_timeout(t): raise else: break else: raise win32.SetNamedPipeHandleState( h, win32.PIPE_READMODE_MESSAGE, None, None ) return _multiprocessing.PipeConnection(h)
Return a connection object connected to the pipe given by `address`
PipeClient
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/connection.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/connection.py
MIT
def is_forking(argv): ''' Return whether commandline indicates we are forking ''' if len(argv) >= 2 and argv[1] == '--multiprocessing-fork': assert len(argv) == 3 return True else: return False
Return whether commandline indicates we are forking
is_forking
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/forking.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/forking.py
MIT
def get_command_line(): ''' Returns prefix of command line used for spawning a child process ''' if getattr(process.current_process(), '_inheriting', False): raise RuntimeError(''' Attempt to start a new process before the current process has finished its bootstrapping phase. This probably means that you are on Windows and you have forgotten to use the proper idiom in the main module: if __name__ == '__main__': freeze_support() ... The "freeze_support()" line can be omitted if the program is not going to be frozen to produce a Windows executable.''') if getattr(sys, 'frozen', False): return [sys.executable, '--multiprocessing-fork'] else: prog = 'from multiprocessing.forking import main; main()' opts = util._args_from_interpreter_flags() return [_python_exe] + opts + ['-c', prog, '--multiprocessing-fork']
Returns prefix of command line used for spawning a child process
get_command_line
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/forking.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/forking.py
MIT
def main(): ''' Run code specified by data received over pipe ''' assert is_forking(sys.argv) handle = int(sys.argv[-1]) fd = msvcrt.open_osfhandle(handle, os.O_RDONLY) from_parent = os.fdopen(fd, 'rb') process.current_process()._inheriting = True preparation_data = load(from_parent) prepare(preparation_data) self = load(from_parent) process.current_process()._inheriting = False from_parent.close() exitcode = self._bootstrap() exit(exitcode)
Run code specified by data received over pipe
main
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/forking.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/forking.py
MIT
def get_preparation_data(name): ''' Return info about parent needed by child to unpickle process object ''' from .util import _logger, _log_to_stderr d = dict( name=name, sys_path=sys.path, sys_argv=sys.argv, log_to_stderr=_log_to_stderr, orig_dir=process.ORIGINAL_DIR, authkey=process.current_process().authkey, ) if _logger is not None: d['log_level'] = _logger.getEffectiveLevel() if not WINEXE and not WINSERVICE: main_path = getattr(sys.modules['__main__'], '__file__', None) if not main_path and sys.argv[0] not in ('', '-c'): main_path = sys.argv[0] if main_path is not None: if not os.path.isabs(main_path) and \ process.ORIGINAL_DIR is not None: main_path = os.path.join(process.ORIGINAL_DIR, main_path) d['main_path'] = os.path.normpath(main_path) return d
Return info about parent needed by child to unpickle process object
get_preparation_data
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/forking.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/forking.py
MIT
def prepare(data): ''' Try to get current process ready to unpickle process object ''' old_main_modules.append(sys.modules['__main__']) if 'name' in data: process.current_process().name = data['name'] if 'authkey' in data: process.current_process()._authkey = data['authkey'] if 'log_to_stderr' in data and data['log_to_stderr']: util.log_to_stderr() if 'log_level' in data: util.get_logger().setLevel(data['log_level']) if 'sys_path' in data: sys.path = data['sys_path'] if 'sys_argv' in data: sys.argv = data['sys_argv'] if 'dir' in data: os.chdir(data['dir']) if 'orig_dir' in data: process.ORIGINAL_DIR = data['orig_dir'] if 'main_path' in data: # XXX (ncoghlan): The following code makes several bogus # assumptions regarding the relationship between __file__ # and a module's real name. See PEP 302 and issue #10845 # The problem is resolved properly in Python 3.4+, as # described in issue #19946 main_path = data['main_path'] main_name = os.path.splitext(os.path.basename(main_path))[0] if main_name == '__init__': main_name = os.path.basename(os.path.dirname(main_path)) if main_name == '__main__': # For directory and zipfile execution, we assume an implicit # "if __name__ == '__main__':" around the module, and don't # rerun the main module code in spawned processes main_module = sys.modules['__main__'] main_module.__file__ = main_path elif main_name != 'ipython': # Main modules not actually called __main__.py may # contain additional code that should still be executed import imp if main_path is None: dirs = None elif os.path.basename(main_path).startswith('__init__.py'): dirs = [os.path.dirname(os.path.dirname(main_path))] else: dirs = [os.path.dirname(main_path)] assert main_name not in sys.modules, main_name file, path_name, etc = imp.find_module(main_name, dirs) try: # We would like to do "imp.load_module('__main__', ...)" # here. However, that would cause 'if __name__ == # "__main__"' clauses to be executed. main_module = imp.load_module( '__parents_main__', file, path_name, etc ) finally: if file: file.close() sys.modules['__main__'] = main_module main_module.__name__ = '__main__' # Try to make the potentially picklable objects in # sys.modules['__main__'] realize they are in the main # module -- somewhat ugly. for obj in main_module.__dict__.values(): try: if obj.__module__ == '__parents_main__': obj.__module__ = '__main__' except Exception: pass
Try to get current process ready to unpickle process object
prepare
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/forking.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/forking.py
MIT
def dispatch(c, id, methodname, args=(), kwds={}): ''' Send a message to manager using connection `c` and return response ''' c.send((id, methodname, args, kwds)) kind, result = c.recv() if kind == '#RETURN': return result raise convert_to_error(kind, result)
Send a message to manager using connection `c` and return response
dispatch
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def all_methods(obj): ''' Return a list of names of methods of `obj` ''' temp = [] for name in dir(obj): func = getattr(obj, name) if hasattr(func, '__call__'): temp.append(name) return temp
Return a list of names of methods of `obj`
all_methods
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def serve_client(self, conn): ''' Handle requests from the proxies in a particular process/thread ''' 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: try: methodname = obj = None request = recv() ident, methodname, args, kwds = request obj, exposed, gettypeid = id_to_obj[ident] if methodname not in exposed: raise AttributeError( 'method %r of %r object is not in exposed=%r' % (methodname, type(obj), exposed) ) function = getattr(obj, methodname) try: res = function(*args, **kwds) except Exception, e: msg = ('#ERROR', e) else: typeid = gettypeid and gettypeid.get(methodname, None) if typeid: rident, rexposed = self.create(conn, typeid, res) token = Token(typeid, self.address, rident) msg = ('#PROXY', (rexposed, token)) else: msg = ('#RETURN', res) except AttributeError: if methodname is None: msg = ('#TRACEBACK', format_exc()) else: try: fallback_func = self.fallback_mapping[methodname] result = fallback_func( self, conn, ident, obj, *args, **kwds ) msg = ('#RETURN', result) except Exception: msg = ('#TRACEBACK', format_exc()) except EOFError: util.debug('got EOF -- exiting thread serving %r', threading.current_thread().name) sys.exit(0) except Exception: msg = ('#TRACEBACK', format_exc()) try: try: send(msg) except Exception, e: send(('#UNSERIALIZABLE', repr(msg))) except Exception, e: util.info('exception in thread serving %r', threading.current_thread().name) util.info(' ... message was %r', msg) util.info(' ... exception was %r', e) conn.close() sys.exit(1)
Handle requests from the proxies in a particular process/thread
serve_client
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def debug_info(self, c): ''' Return some info --- useful to spot problems with refcounting ''' self.mutex.acquire() try: result = [] keys = 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(self.id_to_obj[ident][0])[:75])) return '\n'.join(result) finally: self.mutex.release()
Return some info --- useful to spot problems with refcounting
debug_info
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def create(self, c, typeid, *args, **kwds): ''' Create a new shared object and return its id ''' 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: exposed = public_methods(obj) if method_to_typeid is not None: assert type(method_to_typeid) is dict exposed = list(exposed) + list(method_to_typeid) ident = '%x' % id(obj) # convert to string because xmlrpclib # only has 32 bit signed integers util.debug('%r callable returned object with id %r', typeid, ident) self.id_to_obj[ident] = (obj, set(exposed), method_to_typeid) if ident not in self.id_to_refcount: self.id_to_refcount[ident] = 0 # increment the reference count immediately, to avoid # this object being garbage collected before a Proxy # object for it can be created. The caller of create() # is responsible for doing a decref once the Proxy object # has been created. self.incref(c, ident) return ident, tuple(exposed) finally: self.mutex.release()
Create a new shared object and return its id
create
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def accept_connection(self, c, name): ''' Spawn a new thread to serve this connection ''' threading.current_thread().name = name c.send(('#RETURN', None)) self.serve_client(c)
Spawn a new thread to serve this connection
accept_connection
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def get_server(self): ''' Return server object with serve_forever() method and address attribute ''' assert self._state.value == State.INITIAL return Server(self._registry, self._address, self._authkey, self._serializer)
Return server object with serve_forever() method and address attribute
get_server
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def connect(self): ''' Connect manager object to the server process ''' Listener, Client = listener_client[self._serializer] conn = Client(self._address, authkey=self._authkey) dispatch(conn, None, 'dummy') self._state.value = State.STARTED
Connect manager object to the server process
connect
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def start(self, initializer=None, initargs=()): ''' Spawn a server process for this manager object ''' assert self._state.value == State.INITIAL if initializer is not None and not hasattr(initializer, '__call__'): raise TypeError('initializer must be a callable') # pipe over which we will retrieve address of server reader, writer = connection.Pipe(duplex=False) # spawn process which runs a server self._process = Process( target=type(self)._run_server, args=(self._registry, self._address, self._authkey, self._serializer, writer, initializer, initargs), ) ident = ':'.join(str(i) for i in self._process._identity) self._process.name = type(self).__name__ + '-' + ident self._process.start() # get address of server writer.close() self._address = reader.recv() reader.close() # register a finalizer self._state.value = State.STARTED self.shutdown = util.Finalize( self, type(self)._finalize_manager, args=(self._process, self._address, self._authkey, self._state, self._Client), exitpriority=0 )
Spawn a server process for this manager object
start
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def _run_server(cls, registry, address, authkey, serializer, writer, initializer=None, initargs=()): ''' Create a server, report its address and run it ''' if initializer is not None: initializer(*initargs) # create server server = cls._Server(registry, address, authkey, serializer) # inform parent process of the server's address writer.send(server.address) writer.close() # run the manager util.info('manager serving at %r', server.address) server.serve_forever()
Create a server, report its address and run it
_run_server
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def _create(self, typeid, *args, **kwds): ''' Create a new shared object; return the token and exposed tuple ''' 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), exposed
Create a new shared object; return the token and exposed tuple
_create
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def _debug_info(self): ''' Return some info about the servers shared objects and connections ''' conn = self._Client(self._address, authkey=self._authkey) try: return dispatch(conn, None, 'debug_info') finally: conn.close()
Return some info about the servers shared objects and connections
_debug_info
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def _number_of_objects(self): ''' Return the number of shared objects ''' conn = self._Client(self._address, authkey=self._authkey) try: return dispatch(conn, None, 'number_of_objects') finally: conn.close()
Return the number of shared objects
_number_of_objects
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def _finalize_manager(process, address, authkey, state, _Client): ''' Shutdown the manager process; will be registered as a finalizer ''' 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 process.join(timeout=0.2) if process.is_alive(): util.info('manager still alive') if hasattr(process, 'terminate'): util.info('trying to `terminate()` manager process') process.terminate() process.join(timeout=0.1) if process.is_alive(): util.info('manager still alive after terminate') state.value = State.SHUTDOWN try: del BaseProxy._address_to_local[address] except KeyError: pass
Shutdown the manager process; will be registered as a finalizer
_finalize_manager
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def register(cls, typeid, callable=None, proxytype=None, exposed=None, method_to_typeid=None, create_method=True): ''' Register a typeid with the manager type ''' 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_typeid: for key, value in method_to_typeid.items(): assert type(key) is str, '%r is not a string' % key assert type(value) is str, '%r is not a string' % value cls._registry[typeid] = ( callable, exposed, method_to_typeid, proxytype ) if create_method: def temp(self, *args, **kwds): util.debug('requesting creation of a shared %r object', typeid) token, exp = self._create(typeid, *args, **kwds) proxy = proxytype( token, self._serializer, manager=self, authkey=self._authkey, exposed=exp ) conn = self._Client(token.address, authkey=self._authkey) dispatch(conn, None, 'decref', (token.id,)) return proxy temp.__name__ = typeid setattr(cls, typeid, temp)
Register a typeid with the manager type
register
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def _callmethod(self, methodname, args=(), kwds={}): ''' Try to call a method of the referrent and return a copy of the result ''' 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.recv() if kind == '#RETURN': return result elif kind == '#PROXY': exposed, token = result proxytype = self._manager._registry[token.typeid][-1] token.address = self._token.address proxy = proxytype( token, self._serializer, manager=self._manager, authkey=self._authkey, exposed=exposed ) conn = self._Client(token.address, authkey=self._authkey) dispatch(conn, None, 'decref', (token.id,)) return proxy raise convert_to_error(kind, result)
Try to call a method of the referrent and return a copy of the result
_callmethod
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def __str__(self): ''' Return representation of the referent (or a fall-back if that fails) ''' try: return self._callmethod('__repr__') except Exception: return repr(self)[:-1] + "; '__str__()' failed>"
Return representation of the referent (or a fall-back if that fails)
__str__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def RebuildProxy(func, token, serializer, kwds): ''' Function used for unpickling proxy objects. If possible the shared object is returned, or otherwise a proxy for it. ''' server = getattr(current_process(), '_manager_server', None) if server and server.address == token.address: return server.id_to_obj[token.id][0] else: incref = ( kwds.pop('incref', True) and not getattr(current_process(), '_inheriting', False) ) return func(token, serializer, incref=incref, **kwds)
Function used for unpickling proxy objects. If possible the shared object is returned, or otherwise a proxy for it.
RebuildProxy
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def MakeProxyType(name, exposed, _cache={}): ''' Return a proxy type whose methods are given by `exposed` ''' exposed = tuple(exposed) try: return _cache[(name, exposed)] except KeyError: pass dic = {} for meth in exposed: exec '''def %s(self, *args, **kwds): return self._callmethod(%r, args, kwds)''' % (meth, meth) in dic ProxyType = type(name, (BaseProxy,), dic) ProxyType._exposed_ = exposed _cache[(name, exposed)] = ProxyType return ProxyType
Return a proxy type whose methods are given by `exposed`
MakeProxyType
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT