desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return a random int in the range [0,n) Handles the case where n has more bits than returned by a single call to the underlying generator.'
def _randbelow(self, n, _log=_log, int=int, _maxwidth=(1L << BPF), _Method=_MethodType, _BuiltinMethod=_BuiltinMethodType):
try: getrandbits = self.getrandbits except AttributeError: pass else: if ((type(self.random) is _BuiltinMethod) or (type(getrandbits) is _Method)): k = int((1.00001 + _log((n - 1), 2.0))) r = getrandbits(k) while (r >= n): r = getrandbits(k) return r if (n >= _maxwidth): _warn('Underlying random() generator does not supply \nenough bits to choose from a population range this large') return int((self.random() * n))
'Choose a random element from a non-empty sequence.'
def choice(self, seq):
return seq[int((self.random() * len(seq)))]
'x, random=random.random -> shuffle list x in place; return None. Optional arg random is a 0-argument function returning a random float in [0.0, 1.0); by default, the standard random.random.'
def shuffle(self, x, random=None, int=int):
if (random is None): random = self.random for i in reversed(xrange(1, len(x))): j = int((random() * (i + 1))) (x[i], x[j]) = (x[j], x[i])
'Chooses k unique random elements from a population sequence. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. To choose a sample in a range of integers, use xrange as an argument. This is especially fast and space efficient for sampling from a large population: sample(xrange(10000000), 60)'
def sample(self, population, k):
n = len(population) if (not (0 <= k <= n)): raise ValueError('sample larger than population') random = self.random _int = int result = ([None] * k) setsize = 21 if (k > 5): setsize += (4 ** _ceil(_log((k * 3), 4))) if ((n <= setsize) or hasattr(population, 'keys')): pool = list(population) for i in xrange(k): j = _int((random() * (n - i))) result[i] = pool[j] pool[j] = pool[((n - i) - 1)] else: try: selected = set() selected_add = selected.add for i in xrange(k): j = _int((random() * n)) while (j in selected): j = _int((random() * n)) selected_add(j) result[i] = population[j] except (TypeError, KeyError): if isinstance(population, list): raise return self.sample(tuple(population), k) return result
'Get a random number in the range [a, b) or [a, b] depending on rounding.'
def uniform(self, a, b):
return (a + ((b - a) * self.random()))
'Triangular distribution. Continuous distribution bounded by given lower and upper limits, and having a given mode value in-between. http://en.wikipedia.org/wiki/Triangular_distribution'
def triangular(self, low=0.0, high=1.0, mode=None):
u = self.random() c = (0.5 if (mode is None) else ((mode - low) / (high - low))) if (u > c): u = (1.0 - u) c = (1.0 - c) (low, high) = (high, low) return (low + ((high - low) * ((u * c) ** 0.5)))
'Normal distribution. mu is the mean, and sigma is the standard deviation.'
def normalvariate(self, mu, sigma):
random = self.random while 1: u1 = random() u2 = (1.0 - random()) z = ((NV_MAGICCONST * (u1 - 0.5)) / u2) zz = ((z * z) / 4.0) if (zz <= (- _log(u2))): break return (mu + (z * sigma))
'Log normal distribution. If you take the natural logarithm of this distribution, you\'ll get a normal distribution with mean mu and standard deviation sigma. mu can have any value, and sigma must be greater than zero.'
def lognormvariate(self, mu, sigma):
return _exp(self.normalvariate(mu, sigma))
'Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called "lambda", but that is a reserved word in Python.) Returned values range from 0 to positive infinity if lambd is positive, and from negative infinity to 0 if lambd is negative.'
def expovariate(self, lambd):
random = self.random u = random() while (u <= 1e-07): u = random() return ((- _log(u)) / lambd)
'Circular data distribution. mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi.'
def vonmisesvariate(self, mu, kappa):
random = self.random if (kappa <= 1e-06): return (TWOPI * random()) a = (1.0 + _sqrt((1.0 + ((4.0 * kappa) * kappa)))) b = ((a - _sqrt((2.0 * a))) / (2.0 * kappa)) r = ((1.0 + (b * b)) / (2.0 * b)) while 1: u1 = random() z = _cos((_pi * u1)) f = ((1.0 + (r * z)) / (r + z)) c = (kappa * (r - f)) u2 = random() if ((u2 < (c * (2.0 - c))) or (u2 <= (c * _exp((1.0 - c))))): break u3 = random() if (u3 > 0.5): theta = ((mu % TWOPI) + _acos(f)) else: theta = ((mu % TWOPI) - _acos(f)) return theta
'Gamma distribution. Not the gamma function! Conditions on the parameters are alpha > 0 and beta > 0. The probability distribution function is: x ** (alpha - 1) * math.exp(-x / beta) pdf(x) = -------------------------------------- math.gamma(alpha) * beta ** alpha'
def gammavariate(self, alpha, beta):
if ((alpha <= 0.0) or (beta <= 0.0)): raise ValueError, 'gammavariate: alpha and beta must be > 0.0' random = self.random if (alpha > 1.0): ainv = _sqrt(((2.0 * alpha) - 1.0)) bbb = (alpha - LOG4) ccc = (alpha + ainv) while 1: u1 = random() if (not (1e-07 < u1 < 0.9999999)): continue u2 = (1.0 - random()) v = (_log((u1 / (1.0 - u1))) / ainv) x = (alpha * _exp(v)) z = ((u1 * u1) * u2) r = ((bbb + (ccc * v)) - x) if ((((r + SG_MAGICCONST) - (4.5 * z)) >= 0.0) or (r >= _log(z))): return (x * beta) elif (alpha == 1.0): u = random() while (u <= 1e-07): u = random() return ((- _log(u)) * beta) else: while 1: u = random() b = ((_e + alpha) / _e) p = (b * u) if (p <= 1.0): x = (p ** (1.0 / alpha)) else: x = (- _log(((b - p) / alpha))) u1 = random() if (p > 1.0): if (u1 <= (x ** (alpha - 1.0))): break elif (u1 <= _exp((- x))): break return (x * beta)
'Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. Not thread-safe without a lock around calls.'
def gauss(self, mu, sigma):
random = self.random z = self.gauss_next self.gauss_next = None if (z is None): x2pi = (random() * TWOPI) g2rad = _sqrt(((-2.0) * _log((1.0 - random())))) z = (_cos(x2pi) * g2rad) self.gauss_next = (_sin(x2pi) * g2rad) return (mu + (z * sigma))
'Beta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1.'
def betavariate(self, alpha, beta):
y = self.gammavariate(alpha, 1.0) if (y == 0): return 0.0 else: return (y / (y + self.gammavariate(beta, 1.0)))
'Pareto distribution. alpha is the shape parameter.'
def paretovariate(self, alpha):
u = (1.0 - self.random()) return (1.0 / pow(u, (1.0 / alpha)))
'Weibull distribution. alpha is the scale parameter and beta is the shape parameter.'
def weibullvariate(self, alpha, beta):
u = (1.0 - self.random()) return (alpha * pow((- _log(u)), (1.0 / beta)))
'Initialize internal state from hashable object. None or no argument seeds from current time or from an operating system specific randomness source if available. If a is not None or an int or long, hash(a) is used instead. If a is an int or long, a is used directly. Distinct values between 0 and 27814431486575L inclusive are guaranteed to yield distinct internal states (this guarantee is specific to the default Wichmann-Hill generator).'
def seed(self, a=None):
if (a is None): try: a = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time a = long((time.time() * 256)) if (not isinstance(a, (int, long))): a = hash(a) (a, x) = divmod(a, 30268) (a, y) = divmod(a, 30306) (a, z) = divmod(a, 30322) self._seed = ((int(x) + 1), (int(y) + 1), (int(z) + 1)) self.gauss_next = None
'Get the next random number in the range [0.0, 1.0).'
def random(self):
(x, y, z) = self._seed x = ((171 * x) % 30269) y = ((172 * y) % 30307) z = ((170 * z) % 30323) self._seed = (x, y, z) return ((((x / 30269.0) + (y / 30307.0)) + (z / 30323.0)) % 1.0)
'Return internal state; can be passed to setstate() later.'
def getstate(self):
return (self.VERSION, self._seed, self.gauss_next)
'Restore internal state from object returned by getstate().'
def setstate(self, state):
version = state[0] if (version == 1): (version, self._seed, self.gauss_next) = state else: raise ValueError(('state with version %s passed to Random.setstate() of version %s' % (version, self.VERSION)))
'Act as if n calls to random() were made, but quickly. n is an int, greater than or equal to 0. Example use: If you have 2 threads and know that each will consume no more than a million random numbers, create two Random objects r1 and r2, then do r2.setstate(r1.getstate()) r2.jumpahead(1000000) Then r1 and r2 will use guaranteed-disjoint segments of the full period.'
def jumpahead(self, n):
if (not (n >= 0)): raise ValueError('n must be >= 0') (x, y, z) = self._seed x = (int((x * pow(171, n, 30269))) % 30269) y = (int((y * pow(172, n, 30307))) % 30307) z = (int((z * pow(170, n, 30323))) % 30323) self._seed = (x, y, z)
'Set the Wichmann-Hill seed from (x, y, z). These must be integers in the range [0, 256).'
def __whseed(self, x=0, y=0, z=0):
if (not (type(x) == type(y) == type(z) == int)): raise TypeError('seeds must be integers') if (not ((0 <= x < 256) and (0 <= y < 256) and (0 <= z < 256))): raise ValueError('seeds must be in range(0, 256)') if (0 == x == y == z): import time t = long((time.time() * 256)) t = int(((t & 16777215) ^ (t >> 24))) (t, x) = divmod(t, 256) (t, y) = divmod(t, 256) (t, z) = divmod(t, 256) self._seed = ((x or 1), (y or 1), (z or 1)) self.gauss_next = None
'Seed from hashable object\'s hash code. None or no argument seeds from current time. It is not guaranteed that objects with distinct hash codes lead to distinct internal states. This is obsolete, provided for compatibility with the seed routine used prior to Python 2.1. Use the .seed() method instead.'
def whseed(self, a=None):
if (a is None): self.__whseed() return a = hash(a) (a, x) = divmod(a, 256) (a, y) = divmod(a, 256) (a, z) = divmod(a, 256) x = (((x + a) % 256) or 1) y = (((y + a) % 256) or 1) z = (((z + a) % 256) or 1) self.__whseed(x, y, z)
'Get the next random number in the range [0.0, 1.0).'
def random(self):
return ((long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF)
'getrandbits(k) -> x. Generates a long int with k random bits.'
def getrandbits(self, k):
if (k <= 0): raise ValueError('number of bits must be greater than zero') if (k != int(k)): raise TypeError('number of bits should be an integer') bytes = ((k + 7) // 8) x = long(_hexlify(_urandom(bytes)), 16) return (x >> ((bytes * 8) - k))
'Stub method. Not used for a system random number generator.'
def _stub(self, *args, **kwds):
return None
'Method should not be called for a system random number generator.'
def _notimplemented(self, *args, **kwds):
raise NotImplementedError('System entropy source does not have state.')
'This method is called when there is the remote possibility that we ever need to stop in this function.'
def user_call(self, frame, argument_list):
if self._wait_for_mainpyfile: return if self.stop_here(frame): print >>self.stdout, '--Call--' self.interaction(frame, None)
'This function is called when we stop or break at this line.'
def user_line(self, frame):
if self._wait_for_mainpyfile: if ((self.mainpyfile != self.canonic(frame.f_code.co_filename)) or (frame.f_lineno <= 0)): return self._wait_for_mainpyfile = 0 if self.bp_commands(frame): self.interaction(frame, None)
'Call every command that was set for the current active breakpoint (if there is one). Returns True if the normal interaction function must be called, False otherwise.'
def bp_commands(self, frame):
if (getattr(self, 'currentbp', False) and (self.currentbp in self.commands)): currentbp = self.currentbp self.currentbp = 0 lastcmd_back = self.lastcmd self.setup(frame, None) for line in self.commands[currentbp]: self.onecmd(line) self.lastcmd = lastcmd_back if (not self.commands_silent[currentbp]): self.print_stack_entry(self.stack[self.curindex]) if self.commands_doprompt[currentbp]: self.cmdloop() self.forget() return return 1
'This function is called when a return trap is set here.'
def user_return(self, frame, return_value):
if self._wait_for_mainpyfile: return frame.f_locals['__return__'] = return_value print >>self.stdout, '--Return--' self.interaction(frame, None)
'This function is called if an exception occurs, but only if we are to stop at or just below this level.'
def user_exception(self, frame, exc_info):
if self._wait_for_mainpyfile: return (exc_type, exc_value, exc_traceback) = exc_info frame.f_locals['__exception__'] = (exc_type, exc_value) if (type(exc_type) == type('')): exc_type_name = exc_type else: exc_type_name = exc_type.__name__ print >>self.stdout, (exc_type_name + ':'), _saferepr(exc_value) self.interaction(frame, exc_traceback)
'Custom displayhook for the exec in default(), which prevents assignment of the _ variable in the builtins.'
def displayhook(self, obj):
if (obj is not None): print repr(obj)
'Handle alias expansion and \';;\' separator.'
def precmd(self, line):
if (not line.strip()): return line args = line.split() while (args[0] in self.aliases): line = self.aliases[args[0]] ii = 1 for tmpArg in args[1:]: line = line.replace(('%' + str(ii)), tmpArg) ii = (ii + 1) line = line.replace('%*', ' '.join(args[1:])) args = line.split() if (args[0] != 'alias'): marker = line.find(';;') if (marker >= 0): next = line[(marker + 2):].lstrip() self.cmdqueue.append(next) line = line[:marker].rstrip() return line
'Interpret the argument as though it had been typed in response to the prompt. Checks whether this line is typed at the normal prompt or in a breakpoint command list definition.'
def onecmd(self, line):
if (not self.commands_defining): return cmd.Cmd.onecmd(self, line) else: return self.handle_command_def(line)
'Handles one command line during command list definition.'
def handle_command_def(self, line):
(cmd, arg, line) = self.parseline(line) if (not cmd): return if (cmd == 'silent'): self.commands_silent[self.commands_bnum] = True return elif (cmd == 'end'): self.cmdqueue = [] return 1 cmdlist = self.commands[self.commands_bnum] if arg: cmdlist.append(((cmd + ' ') + arg)) else: cmdlist.append(cmd) try: func = getattr(self, ('do_' + cmd)) except AttributeError: func = self.default if (func.func_name in self.commands_resuming): self.commands_doprompt[self.commands_bnum] = False self.cmdqueue = [] return 1 return
'Defines a list of commands associated to a breakpoint. Those commands will be executed whenever the breakpoint causes the program to stop execution.'
def do_commands(self, arg):
if (not arg): bnum = (len(bdb.Breakpoint.bpbynumber) - 1) else: try: bnum = int(arg) except: print >>self.stdout, 'Usage : commands [bnum]\n ...\n end' return self.commands_bnum = bnum self.commands[bnum] = [] self.commands_doprompt[bnum] = True self.commands_silent[bnum] = False prompt_back = self.prompt self.prompt = '(com) ' self.commands_defining = True try: self.cmdloop() finally: self.commands_defining = False self.prompt = prompt_back
'Produce a reasonable default.'
def defaultFile(self):
filename = self.curframe.f_code.co_filename if ((filename == '<string>') and self.mainpyfile): filename = self.mainpyfile return filename
'Check whether specified line seems to be executable. Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank line or EOF). Warning: testing is not comprehensive.'
def checkline(self, filename, lineno):
globs = (self.curframe.f_globals if hasattr(self, 'curframe') else None) line = linecache.getline(filename, lineno, globs) if (not line): print >>self.stdout, 'End of file' return 0 line = line.strip() if ((not line) or (line[0] == '#') or (line[:3] == '"""') or (line[:3] == "'''")): print >>self.stdout, '*** Blank or comment' return 0 return lineno
'arg is bp number followed by ignore count.'
def do_ignore(self, arg):
args = arg.split() try: bpnum = int(args[0].strip()) except ValueError: print >>self.stdout, ('Breakpoint index %r is not a number' % args[0]) return try: count = int(args[1].strip()) except: count = 0 try: bp = bdb.Breakpoint.bpbynumber[bpnum] except IndexError: print >>self.stdout, ('Breakpoint index %r is not valid' % args[0]) return if bp: bp.ignore = count if (count > 0): reply = 'Will ignore next ' if (count > 1): reply = (reply + ('%d crossings' % count)) else: reply = (reply + '1 crossing') print >>self.stdout, (reply + (' of breakpoint %d.' % bpnum)) else: print >>self.stdout, 'Will stop next time breakpoint', print >>self.stdout, bpnum, 'is reached.'
'Three possibilities, tried in this order: clear -> clear all breaks, ask for confirmation clear file:lineno -> clear all breaks at file:lineno clear bpno bpno ... -> clear breakpoints by number'
def do_clear(self, arg):
if (not arg): try: reply = raw_input('Clear all breaks? ') except EOFError: reply = 'no' reply = reply.strip().lower() if (reply in ('y', 'yes')): self.clear_all_breaks() return if (':' in arg): i = arg.rfind(':') filename = arg[:i] arg = arg[(i + 1):] try: lineno = int(arg) except ValueError: err = ('Invalid line number (%s)' % arg) else: err = self.clear_break(filename, lineno) if err: print >>self.stdout, '***', err return numberlist = arg.split() for i in numberlist: try: i = int(i) except ValueError: print >>self.stdout, ('Breakpoint index %r is not a number' % i) continue if (not (0 <= i < len(bdb.Breakpoint.bpbynumber))): print >>self.stdout, 'No breakpoint numbered', i continue err = self.clear_bpbynumber(i) if err: print >>self.stdout, '***', err else: print >>self.stdout, 'Deleted breakpoint', i
'Restart program by raising an exception to be caught in the main debugger loop. If arguments were given, set them in sys.argv.'
def do_run(self, arg):
if arg: import shlex argv0 = sys.argv[0:1] sys.argv = shlex.split(arg) sys.argv[:0] = argv0 raise Restart
'Helper function for break/clear parsing -- may be overridden. lookupmodule() translates (possibly incomplete) file or module name into an absolute file name.'
def lookupmodule(self, filename):
if (os.path.isabs(filename) and os.path.exists(filename)): return filename f = os.path.join(sys.path[0], filename) if (os.path.exists(f) and (self.canonic(f) == self.mainpyfile)): return f (root, ext) = os.path.splitext(filename) if (ext == ''): filename = (filename + '.py') if os.path.isabs(filename): return filename for dirname in sys.path: while os.path.islink(dirname): dirname = os.readlink(dirname) fullname = os.path.join(dirname, filename) if os.path.exists(fullname): return fullname return None
'Install this ImportManager into the specified namespace.'
def install(self, namespace=vars(__builtin__)):
if isinstance(namespace, _ModuleType): namespace = vars(namespace) self.previous_importer = namespace['__import__'] self.namespace = namespace namespace['__import__'] = self._import_hook
'Restore the previous import mechanism.'
def uninstall(self):
self.namespace['__import__'] = self.previous_importer
'Python calls this hook to locate and import a module.'
def _import_hook(self, fqname, globals=None, locals=None, fromlist=None):
parts = fqname.split('.') parent = self._determine_import_context(globals) if parent: module = parent.__importer__._do_import(parent, parts, fromlist) if module: return module try: top_module = sys.modules[parts[0]] except KeyError: top_module = self._import_top_module(parts[0]) if (not top_module): raise ImportError, ('No module named ' + fqname) if (len(parts) == 1): if (not fromlist): return top_module if (not top_module.__dict__.get('__ispkg__')): return top_module importer = top_module.__dict__.get('__importer__') if importer: return importer._finish_import(top_module, parts[1:], fromlist) if ((len(parts) == 2) and hasattr(top_module, parts[1])): if fromlist: return getattr(top_module, parts[1]) else: return top_module raise ImportError, ('No module named ' + fqname)
'Returns the context in which a module should be imported. The context could be a loaded (package) module and the imported module will be looked for within that package. The context could also be None, meaning there is no context -- the module should be looked for as a "top-level" module.'
def _determine_import_context(self, globals):
if ((not globals) or (not globals.get('__importer__'))): return None parent_fqname = globals['__name__'] if globals['__ispkg__']: parent = sys.modules[parent_fqname] assert (globals is parent.__dict__) return parent i = parent_fqname.rfind('.') if (i == (-1)): return None parent_fqname = parent_fqname[:i] parent = sys.modules[parent_fqname] assert (parent.__name__ == parent_fqname) return parent
'Python calls this hook to reload a module.'
def _reload_hook(self, module):
importer = module.__dict__.get('__importer__') if (not importer): pass raise SystemError, 'reload not yet implemented'
'Import a top-level module.'
def import_top(self, name):
return self._import_one(None, name, name)
'Import a single module.'
def _import_one(self, parent, modname, fqname):
try: return sys.modules[fqname] except KeyError: pass result = self.get_code(parent, modname, fqname) if (result is None): return None module = self._process_result(result, fqname) if parent: setattr(parent, modname, module) return module
'Import the rest of the modules, down from the top-level module. Returns the last module in the dotted list of modules.'
def _load_tail(self, m, parts):
for part in parts: fqname = ('%s.%s' % (m.__name__, part)) m = self._import_one(m, part, fqname) if (not m): raise ImportError, ('No module named ' + fqname) return m
'Import any sub-modules in the "from" list.'
def _import_fromlist(self, package, fromlist):
if ('*' in fromlist): fromlist = (list(fromlist) + list(package.__dict__.get('__all__', []))) for sub in fromlist: if ((sub != '*') and (not hasattr(package, sub))): subname = ('%s.%s' % (package.__name__, sub)) submod = self._import_one(package, sub, subname) if (not submod): raise ImportError, ('cannot import name ' + subname)
'Attempt to import the module relative to parent. This method is used when the import context specifies that <self> imported the parent module.'
def _do_import(self, parent, parts, fromlist):
top_name = parts[0] top_fqname = ((parent.__name__ + '.') + top_name) top_module = self._import_one(parent, top_name, top_fqname) if (not top_module): return None return self._finish_import(top_module, parts[1:], fromlist)
'Find and retrieve the code for the given module. parent specifies a parent module to define a context for importing. It may be None, indicating no particular context for the search. modname specifies a single module (not dotted) within the parent. fqname specifies the fully-qualified module name. This is a (potentially) dotted name from the "root" of the module namespace down to the modname. If there is no parent, then modname==fqname. This method should return None, or a 3-tuple. * If the module was not found, then None should be returned. * The first item of the 2- or 3-tuple should be the integer 0 or 1, specifying whether the module that was found is a package or not. * The second item is the code object for the module (it will be executed within the new module\'s namespace). This item can also be a fully-loaded module object (e.g. loaded from a shared lib). * The third item is a dictionary of name/value pairs that will be inserted into new module before the code object is executed. This is provided in case the module\'s code expects certain values (such as where the module was found). When the second item is a module object, then these names/values will be inserted *after* the module has been loaded/initialized.'
def get_code(self, parent, modname, fqname):
raise RuntimeError, 'get_code not implemented'
'Compile a command and determine whether it is incomplete. Arguments: source -- the source string; may contain \n characters filename -- optional filename from which source was read; default "<input>" symbol -- optional grammar start symbol; "single" (default) or "eval" Return value / exceptions raised: - Return a code object if the command is complete and valid - Return None if the command is incomplete - Raise SyntaxError, ValueError or OverflowError if the command is a syntax error (OverflowError and ValueError can be produced by malformed literals).'
def __call__(self, source, filename='<input>', symbol='single'):
return _maybe_compile(self.compiler, source, filename, symbol)
'Write the profile data to a file we know how to load back.'
def dump_stats(self, filename):
f = file(filename, 'wb') try: marshal.dump(self.stats, f) finally: f.close()
'Expand all abbreviations that are unique.'
def get_sort_arg_defs(self):
if (not self.sort_arg_dict): self.sort_arg_dict = dict = {} bad_list = {} for (word, tup) in self.sort_arg_dict_default.iteritems(): fragment = word while fragment: if (not fragment): break if (fragment in dict): bad_list[fragment] = 0 break dict[fragment] = tup fragment = fragment[:(-1)] for word in bad_list: del dict[word] return self.sort_arg_dict
'Initialize a new instance. If specified, `host\' is the name of the remote host to which to connect. If specified, `port\' specifies the port to which to connect. By default, smtplib.SMTP_PORT is used. An SMTPConnectError is raised if the specified `host\' doesn\'t respond correctly. If specified, `local_hostname` is used as the FQDN of the local host. By default, the local hostname is found using socket.getfqdn().'
def __init__(self, host='', port=0, local_hostname=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
self.timeout = timeout self.esmtp_features = {} if host: (code, msg) = self.connect(host, port) if (code != 220): raise SMTPConnectError(code, msg) if (local_hostname is not None): self.local_hostname = local_hostname else: fqdn = socket.getfqdn() if ('.' in fqdn): self.local_hostname = fqdn else: addr = '127.0.0.1' try: addr = socket.gethostbyname(socket.gethostname()) except socket.gaierror: pass self.local_hostname = ('[%s]' % addr)
'Set the debug output level. A non-false value results in debug messages for connection and for all messages sent to and received from the server.'
def set_debuglevel(self, debuglevel):
self.debuglevel = debuglevel
'Connect to a host on a given port. If the hostname ends with a colon (`:\') followed by a number, and there is no port specified, that suffix will be stripped off and the number interpreted as the port number to use. Note: This method is automatically invoked by __init__, if a host is specified during instantiation.'
def connect(self, host='localhost', port=0):
if ((not port) and (host.find(':') == host.rfind(':'))): i = host.rfind(':') if (i >= 0): (host, port) = (host[:i], host[(i + 1):]) try: port = int(port) except ValueError: raise socket.error, 'nonnumeric port' if (not port): port = self.default_port if (self.debuglevel > 0): print >>stderr, 'connect:', (host, port) self.sock = self._get_socket(host, port, self.timeout) (code, msg) = self.getreply() if (self.debuglevel > 0): print >>stderr, 'connect:', msg return (code, msg)
'Send `str\' to the server.'
def send(self, str):
if (self.debuglevel > 0): print >>stderr, 'send:', repr(str) if (hasattr(self, 'sock') and self.sock): try: self.sock.sendall(str) except socket.error: self.close() raise SMTPServerDisconnected('Server not connected') else: raise SMTPServerDisconnected('please run connect() first')
'Send a command to the server.'
def putcmd(self, cmd, args=''):
if (args == ''): str = ('%s%s' % (cmd, CRLF)) else: str = ('%s %s%s' % (cmd, args, CRLF)) self.send(str)
'Get a reply from the server. Returns a tuple consisting of: - server response code (e.g. \'250\', or such, if all goes well) Note: returns -1 if it can\'t read response code. - server response string corresponding to response code (multiline responses are converted to a single, multiline string). Raises SMTPServerDisconnected if end-of-file is reached.'
def getreply(self):
resp = [] if (self.file is None): self.file = self.sock.makefile('rb') while 1: try: line = self.file.readline() except socket.error: line = '' if (line == ''): self.close() raise SMTPServerDisconnected('Connection unexpectedly closed') if (self.debuglevel > 0): print >>stderr, 'reply:', repr(line) resp.append(line[4:].strip()) code = line[:3] try: errcode = int(code) except ValueError: errcode = (-1) break if (line[3:4] != '-'): break errmsg = '\n'.join(resp) if (self.debuglevel > 0): print >>stderr, ('reply: retcode (%s); Msg: %s' % (errcode, errmsg)) return (errcode, errmsg)
'Send a command, and return its response code.'
def docmd(self, cmd, args=''):
self.putcmd(cmd, args) return self.getreply()
'SMTP \'helo\' command. Hostname to send for this command defaults to the FQDN of the local host.'
def helo(self, name=''):
self.putcmd('helo', (name or self.local_hostname)) (code, msg) = self.getreply() self.helo_resp = msg return (code, msg)
'SMTP \'ehlo\' command. Hostname to send for this command defaults to the FQDN of the local host.'
def ehlo(self, name=''):
self.esmtp_features = {} self.putcmd(self.ehlo_msg, (name or self.local_hostname)) (code, msg) = self.getreply() if ((code == (-1)) and (len(msg) == 0)): self.close() raise SMTPServerDisconnected('Server not connected') self.ehlo_resp = msg if (code != 250): return (code, msg) self.does_esmtp = 1 resp = self.ehlo_resp.split('\n') del resp[0] for each in resp: auth_match = OLDSTYLE_AUTH.match(each) if auth_match: self.esmtp_features['auth'] = ((self.esmtp_features.get('auth', '') + ' ') + auth_match.groups(0)[0]) continue m = re.match('(?P<feature>[A-Za-z0-9][A-Za-z0-9\\-]*) ?', each) if m: feature = m.group('feature').lower() params = m.string[m.end('feature'):].strip() if (feature == 'auth'): self.esmtp_features[feature] = ((self.esmtp_features.get(feature, '') + ' ') + params) else: self.esmtp_features[feature] = params return (code, msg)
'Does the server support a given SMTP service extension?'
def has_extn(self, opt):
return (opt.lower() in self.esmtp_features)
'SMTP \'help\' command. Returns help text from server.'
def help(self, args=''):
self.putcmd('help', args) return self.getreply()[1]
'SMTP \'rset\' command -- resets session.'
def rset(self):
return self.docmd('rset')
'SMTP \'noop\' command -- doesn\'t do anything :>'
def noop(self):
return self.docmd('noop')
'SMTP \'mail\' command -- begins mail xfer session.'
def mail(self, sender, options=[]):
optionlist = '' if (options and self.does_esmtp): optionlist = (' ' + ' '.join(options)) self.putcmd('mail', ('FROM:%s%s' % (quoteaddr(sender), optionlist))) return self.getreply()
'SMTP \'rcpt\' command -- indicates 1 recipient for this mail.'
def rcpt(self, recip, options=[]):
optionlist = '' if (options and self.does_esmtp): optionlist = (' ' + ' '.join(options)) self.putcmd('rcpt', ('TO:%s%s' % (quoteaddr(recip), optionlist))) return self.getreply()
'SMTP \'DATA\' command -- sends message data to server. Automatically quotes lines beginning with a period per rfc821. Raises SMTPDataError if there is an unexpected reply to the DATA command; the return value from this method is the final response code received when the all data is sent.'
def data(self, msg):
self.putcmd('data') (code, repl) = self.getreply() if (self.debuglevel > 0): print >>stderr, 'data:', (code, repl) if (code != 354): raise SMTPDataError(code, repl) else: q = quotedata(msg) if (q[(-2):] != CRLF): q = (q + CRLF) q = ((q + '.') + CRLF) self.send(q) (code, msg) = self.getreply() if (self.debuglevel > 0): print >>stderr, 'data:', (code, msg) return (code, msg)
'SMTP \'verify\' command -- checks for address validity.'
def verify(self, address):
self.putcmd('vrfy', quoteaddr(address)) return self.getreply()
'SMTP \'expn\' command -- expands a mailing list.'
def expn(self, address):
self.putcmd('expn', quoteaddr(address)) return self.getreply()
'Call self.ehlo() and/or self.helo() if needed. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. This method may raise the following exceptions: SMTPHeloError The server didn\'t reply properly to the helo greeting.'
def ehlo_or_helo_if_needed(self):
if ((self.helo_resp is None) and (self.ehlo_resp is None)): if (not (200 <= self.ehlo()[0] <= 299)): (code, resp) = self.helo() if (not (200 <= code <= 299)): raise SMTPHeloError(code, resp)
'Log in on an SMTP server that requires authentication. The arguments are: - user: The user name to authenticate with. - password: The password for the authentication. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. This method will return normally if the authentication was successful. This method may raise the following exceptions: SMTPHeloError The server didn\'t reply properly to the helo greeting. SMTPAuthenticationError The server didn\'t accept the username/ password combination. SMTPException No suitable authentication method was found.'
def login(self, user, password):
def encode_cram_md5(challenge, user, password): challenge = base64.decodestring(challenge) response = ((user + ' ') + hmac.HMAC(password, challenge).hexdigest()) return encode_base64(response, eol='') def encode_plain(user, password): return encode_base64(('\x00%s\x00%s' % (user, password)), eol='') AUTH_PLAIN = 'PLAIN' AUTH_CRAM_MD5 = 'CRAM-MD5' AUTH_LOGIN = 'LOGIN' self.ehlo_or_helo_if_needed() if (not self.has_extn('auth')): raise SMTPException('SMTP AUTH extension not supported by server.') authlist = self.esmtp_features['auth'].split() preferred_auths = [AUTH_CRAM_MD5, AUTH_PLAIN, AUTH_LOGIN] authmethod = None for method in preferred_auths: if (method in authlist): authmethod = method break if (authmethod == AUTH_CRAM_MD5): (code, resp) = self.docmd('AUTH', AUTH_CRAM_MD5) if (code == 503): return (code, resp) (code, resp) = self.docmd(encode_cram_md5(resp, user, password)) elif (authmethod == AUTH_PLAIN): (code, resp) = self.docmd('AUTH', ((AUTH_PLAIN + ' ') + encode_plain(user, password))) elif (authmethod == AUTH_LOGIN): (code, resp) = self.docmd('AUTH', ('%s %s' % (AUTH_LOGIN, encode_base64(user, eol='')))) if (code != 334): raise SMTPAuthenticationError(code, resp) (code, resp) = self.docmd(encode_base64(password, eol='')) elif (authmethod is None): raise SMTPException('No suitable authentication method found.') if (code not in (235, 503)): raise SMTPAuthenticationError(code, resp) return (code, resp)
'Puts the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports TLS, this will encrypt the rest of the SMTP session. If you provide the keyfile and certfile parameters, the identity of the SMTP server and client can be checked. This, however, depends on whether the socket module really checks the certificates. This method may raise the following exceptions: SMTPHeloError The server didn\'t reply properly to the helo greeting.'
def starttls(self, keyfile=None, certfile=None):
self.ehlo_or_helo_if_needed() if (not self.has_extn('starttls')): raise SMTPException('STARTTLS extension not supported by server.') (resp, reply) = self.docmd('STARTTLS') if (resp == 220): if (not _have_ssl): raise RuntimeError('No SSL support included in this Python') self.sock = ssl.wrap_socket(self.sock, keyfile, certfile) self.file = SSLFakeFile(self.sock) self.helo_resp = None self.ehlo_resp = None self.esmtp_features = {} self.does_esmtp = 0 return (resp, reply)
'This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : A list of addresses to send this mail to. A bare string will be treated as a list with 1 address. - msg : The message to send. - mail_options : List of ESMTP options (such as 8bitmime) for the mail command. - rcpt_options : List of ESMTP options (such as DSN commands) for all the rcpt commands. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server does ESMTP, message size and each of the specified options will be passed to it. If EHLO fails, HELO will be tried and ESMTP options suppressed. This method will return normally if the mail is accepted for at least one recipient. It returns a dictionary, with one entry for each recipient that was refused. Each entry contains a tuple of the SMTP error code and the accompanying error message sent by the server. This method may raise the following exceptions: SMTPHeloError The server didn\'t reply properly to the helo greeting. SMTPRecipientsRefused The server rejected ALL recipients (no mail was sent). SMTPSenderRefused The server didn\'t accept the from_addr. SMTPDataError The server replied with an unexpected error code (other than a refusal of a recipient). Note: the connection will be open even after an exception is raised. Example: >>> import smtplib >>> s=smtplib.SMTP("localhost") >>> tolist=["[email protected]","[email protected]","[email protected]","[email protected]"] >>> msg = \'\'\'\ ... From: [email protected] ... Subject: testin\'... ... This is a test \'\'\' >>> s.sendmail("[email protected]",tolist,msg) { "[email protected]" : ( 550 ,"User unknown" ) } >>> s.quit() In the above example, the message was accepted for delivery to three of the four addresses, and one was rejected, with the error code 550. If all addresses are accepted, then the method will return an empty dictionary.'
def sendmail(self, from_addr, to_addrs, msg, mail_options=[], rcpt_options=[]):
self.ehlo_or_helo_if_needed() esmtp_opts = [] if self.does_esmtp: if self.has_extn('size'): esmtp_opts.append(('size=%d' % len(msg))) for option in mail_options: esmtp_opts.append(option) (code, resp) = self.mail(from_addr, esmtp_opts) if (code != 250): self.rset() raise SMTPSenderRefused(code, resp, from_addr) senderrs = {} if isinstance(to_addrs, basestring): to_addrs = [to_addrs] for each in to_addrs: (code, resp) = self.rcpt(each, rcpt_options) if ((code != 250) and (code != 251)): senderrs[each] = (code, resp) if (len(senderrs) == len(to_addrs)): self.rset() raise SMTPRecipientsRefused(senderrs) (code, resp) = self.data(msg) if (code != 250): self.rset() raise SMTPDataError(code, resp) return senderrs
'Close the connection to the SMTP server.'
def close(self):
if self.file: self.file.close() self.file = None if self.sock: self.sock.close() self.sock = None
'Terminate the SMTP session.'
def quit(self):
res = self.docmd('quit') self.close() return res
'Initialize a new instance.'
def __init__(self, host='', port=LMTP_PORT, local_hostname=None):
SMTP.__init__(self, host, port, local_hostname)
'Connect to the LMTP daemon, on either a Unix or a TCP socket.'
def connect(self, host='localhost', port=0):
if (host[0] != '/'): return SMTP.connect(self, host, port) try: self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.sock.connect(host) except socket.error as msg: if (self.debuglevel > 0): print >>stderr, 'connect fail:', host if self.sock: self.sock.close() self.sock = None raise socket.error, msg (code, msg) = self.getreply() if (self.debuglevel > 0): print >>stderr, 'connect:', msg return (code, msg)
'Initialize an instance. Arguments: - host: hostname to connect to - port: port to connect to (default the standard NNTP port) - user: username to authenticate with - password: password to use with username - readermode: if true, send \'mode reader\' command after connecting. readermode is sometimes necessary if you are connecting to an NNTP server on the local machine and intend to call reader-specific commands, such as `group\'. If you get unexpected NNTPPermanentErrors, you might need to set readermode.'
def __init__(self, host, port=NNTP_PORT, user=None, password=None, readermode=None, usenetrc=True):
self.host = host self.port = port self.sock = socket.create_connection((host, port)) self.file = self.sock.makefile('rb') self.debugging = 0 self.welcome = self.getresp() readermode_afterauth = 0 if readermode: try: self.welcome = self.shortcmd('mode reader') except NNTPPermanentError: pass except NNTPTemporaryError as e: if (user and (e.response[:3] == '480')): readermode_afterauth = 1 else: raise try: if (usenetrc and (not user)): import netrc credentials = netrc.netrc() auth = credentials.authenticators(host) if auth: user = auth[0] password = auth[2] except IOError: pass if user: resp = self.shortcmd(('authinfo user ' + user)) if (resp[:3] == '381'): if (not password): raise NNTPReplyError(resp) else: resp = self.shortcmd(('authinfo pass ' + password)) if (resp[:3] != '281'): raise NNTPPermanentError(resp) if readermode_afterauth: try: self.welcome = self.shortcmd('mode reader') except NNTPPermanentError: pass
'Get the welcome message from the server (this is read and squirreled away by __init__()). If the response code is 200, posting is allowed; if it 201, posting is not allowed.'
def getwelcome(self):
if self.debugging: print '*welcome*', repr(self.welcome) return self.welcome
'Set the debugging level. Argument \'level\' means: 0: no debugging output (default) 1: print commands and responses but not body text etc. 2: also print raw lines read and sent before stripping CR/LF'
def set_debuglevel(self, level):
self.debugging = level
'Internal: send one line to the server, appending CRLF.'
def putline(self, line):
line = (line + CRLF) if (self.debugging > 1): print '*put*', repr(line) self.sock.sendall(line)
'Internal: send one command to the server (through putline()).'
def putcmd(self, line):
if self.debugging: print '*cmd*', repr(line) self.putline(line)
'Internal: return one line from the server, stripping CRLF. Raise EOFError if the connection is closed.'
def getline(self):
line = self.file.readline() if (self.debugging > 1): print '*get*', repr(line) if (not line): raise EOFError if (line[(-2):] == CRLF): line = line[:(-2)] elif (line[(-1):] in CRLF): line = line[:(-1)] return line
'Internal: get a response from the server. Raise various errors if the response indicates an error.'
def getresp(self):
resp = self.getline() if self.debugging: print '*resp*', repr(resp) c = resp[:1] if (c == '4'): raise NNTPTemporaryError(resp) if (c == '5'): raise NNTPPermanentError(resp) if (c not in '123'): raise NNTPProtocolError(resp) return resp
'Internal: get a response plus following text from the server. Raise various errors if the response indicates an error.'
def getlongresp(self, file=None):
openedFile = None try: if isinstance(file, str): openedFile = file = open(file, 'w') resp = self.getresp() if (resp[:3] not in LONGRESP): raise NNTPReplyError(resp) list = [] while 1: line = self.getline() if (line == '.'): break if (line[:2] == '..'): line = line[1:] if file: file.write((line + '\n')) else: list.append(line) finally: if openedFile: openedFile.close() return (resp, list)
'Internal: send a command and get the response.'
def shortcmd(self, line):
self.putcmd(line) return self.getresp()
'Internal: send a command and get the response plus following text.'
def longcmd(self, line, file=None):
self.putcmd(line) return self.getlongresp(file)
'Process a NEWGROUPS command. Arguments: - date: string \'yymmdd\' indicating the date - time: string \'hhmmss\' indicating the time Return: - resp: server response if successful - list: list of newsgroup names'
def newgroups(self, date, time, file=None):
return self.longcmd(((('NEWGROUPS ' + date) + ' ') + time), file)
'Process a NEWNEWS command. Arguments: - group: group name or \'*\' - date: string \'yymmdd\' indicating the date - time: string \'hhmmss\' indicating the time Return: - resp: server response if successful - list: list of message ids'
def newnews(self, group, date, time, file=None):
cmd = ((((('NEWNEWS ' + group) + ' ') + date) + ' ') + time) return self.longcmd(cmd, file)
'Process a LIST command. Return: - resp: server response if successful - list: list of (group, last, first, flag) (strings)'
def list(self, file=None):
(resp, list) = self.longcmd('LIST', file) for i in range(len(list)): list[i] = tuple(list[i].split()) return (resp, list)
'Get a description for a single group. If more than one group matches (\'group\' is a pattern), return the first. If no group matches, return an empty string. This elides the response code from the server, since it can only be \'215\' or \'285\' (for xgtitle) anyway. If the response code is needed, use the \'descriptions\' method. NOTE: This neither checks for a wildcard in \'group\' nor does it check whether the group actually exists.'
def description(self, group):
(resp, lines) = self.descriptions(group) if (len(lines) == 0): return '' else: return lines[0][1]
'Get descriptions for a range of groups.'
def descriptions(self, group_pattern):
line_pat = re.compile('^(?P<group>[^ DCTB ]+)[ DCTB ]+(.*)$') (resp, raw_lines) = self.longcmd(('LIST NEWSGROUPS ' + group_pattern)) if (resp[:3] != '215'): (resp, raw_lines) = self.longcmd(('XGTITLE ' + group_pattern)) lines = [] for raw_line in raw_lines: match = line_pat.search(raw_line.strip()) if match: lines.append(match.group(1, 2)) return (resp, lines)
'Process a GROUP command. Argument: - group: the group name Returns: - resp: server response if successful - count: number of articles (string) - first: first article number (string) - last: last article number (string) - name: the group name'
def group(self, name):
resp = self.shortcmd(('GROUP ' + name)) if (resp[:3] != '211'): raise NNTPReplyError(resp) words = resp.split() count = first = last = 0 n = len(words) if (n > 1): count = words[1] if (n > 2): first = words[2] if (n > 3): last = words[3] if (n > 4): name = words[4].lower() return (resp, count, first, last, name)
'Process a HELP command. Returns: - resp: server response if successful - list: list of strings'
def help(self, file=None):
return self.longcmd('HELP', file)
'Internal: parse the response of a STAT, NEXT or LAST command.'
def statparse(self, resp):
if (resp[:2] != '22'): raise NNTPReplyError(resp) words = resp.split() nr = 0 id = '' n = len(words) if (n > 1): nr = words[1] if (n > 2): id = words[2] return (resp, nr, id)