Search is not available for this dataset
text
stringlengths
75
104k
def divide(cls, divisions, problem_data): """divide :type problem_data: dict """ tspp = TSPProblem(**problem_data) def routes_for_subgroup(cs): for city in cs: if city == tspp.start_city: continue cities = tspp.cities.keys() cities.remove(tspp.start_city) cities.remove(city) random.shuffle(cities) route = [tspp.start_city, city] + cities assert len(set(route)) == len(route) assert len(route) == len(tspp.cities) yield json.dumps(route) if divisions: chunk_size = int(math.ceil(len(tspp.cities) / divisions)) else: chunk_size = 1 for subgroup in chunks(tspp.cities.keys(), chunk_size): routes = list(routes_for_subgroup(subgroup)) if routes: yield routes
def _defaults(self, keys=None): """create an empty record""" d = {} keys = self._keys if keys is None else keys for key in keys: d[key] = None return d
def _check_table(self): """Ensure that an incorrect table doesn't exist If a bad (old) table does exist, return False """ cursor = self._db.execute("PRAGMA table_info(%s)"%self.table) lines = cursor.fetchall() if not lines: # table does not exist return True types = {} keys = [] for line in lines: keys.append(line[1]) types[line[1]] = line[2] if self._keys != keys: # key mismatch self.log.warn('keys mismatch') return False for key in self._keys: if types[key] != self._types[key]: self.log.warn( 'type mismatch: %s: %s != %s'%(key,types[key],self._types[key]) ) return False return True
def _init_db(self): """Connect to the database and get new session number.""" # register adapters sqlite3.register_adapter(dict, _adapt_dict) sqlite3.register_converter('dict', _convert_dict) sqlite3.register_adapter(list, _adapt_bufs) sqlite3.register_converter('bufs', _convert_bufs) # connect to the db dbfile = os.path.join(self.location, self.filename) self._db = sqlite3.connect(dbfile, detect_types=sqlite3.PARSE_DECLTYPES, # isolation_level = None)#, cached_statements=64) # print dir(self._db) first_table = previous_table = self.table i=0 while not self._check_table(): i+=1 self.table = first_table+'_%i'%i self.log.warn( "Table %s exists and doesn't match db format, trying %s"% (previous_table, self.table) ) previous_table = self.table self._db.execute("""CREATE TABLE IF NOT EXISTS %s (msg_id text PRIMARY KEY, header dict text, content dict text, buffers bufs blob, submitted timestamp, client_uuid text, engine_uuid text, started timestamp, completed timestamp, resubmitted text, received timestamp, result_header dict text, result_content dict text, result_buffers bufs blob, queue text, pyin text, pyout text, pyerr text, stdout text, stderr text) """%self.table) self._db.commit()
def _list_to_dict(self, line, keys=None): """Inverse of dict_to_list""" keys = self._keys if keys is None else keys d = self._defaults(keys) for key,value in zip(keys, line): d[key] = value return d
def _render_expression(self, check): """Turn a mongodb-style search dict into an SQL query.""" expressions = [] args = [] skeys = set(check.keys()) skeys.difference_update(set(self._keys)) skeys.difference_update(set(['buffers', 'result_buffers'])) if skeys: raise KeyError("Illegal testing key(s): %s"%skeys) for name,sub_check in check.iteritems(): if isinstance(sub_check, dict): for test,value in sub_check.iteritems(): try: op = operators[test] except KeyError: raise KeyError("Unsupported operator: %r"%test) if isinstance(op, tuple): op, join = op if value is None and op in null_operators: expr = "%s %s" % (name, null_operators[op]) else: expr = "%s %s ?"%(name, op) if isinstance(value, (tuple,list)): if op in null_operators and any([v is None for v in value]): # equality tests don't work with NULL raise ValueError("Cannot use %r test with NULL values on SQLite backend"%test) expr = '( %s )'%( join.join([expr]*len(value)) ) args.extend(value) else: args.append(value) expressions.append(expr) else: # it's an equality check if sub_check is None: expressions.append("%s IS NULL" % name) else: expressions.append("%s = ?"%name) args.append(sub_check) expr = " AND ".join(expressions) return expr, args
def add_record(self, msg_id, rec): """Add a new Task Record, by msg_id.""" d = self._defaults() d.update(rec) d['msg_id'] = msg_id line = self._dict_to_list(d) tups = '(%s)'%(','.join(['?']*len(line))) self._db.execute("INSERT INTO %s VALUES %s"%(self.table, tups), line)
def get_record(self, msg_id): """Get a specific Task Record, by msg_id.""" cursor = self._db.execute("""SELECT * FROM %s WHERE msg_id==?"""%self.table, (msg_id,)) line = cursor.fetchone() if line is None: raise KeyError("No such msg: %r"%msg_id) return self._list_to_dict(line)
def update_record(self, msg_id, rec): """Update the data in an existing record.""" query = "UPDATE %s SET "%self.table sets = [] keys = sorted(rec.keys()) values = [] for key in keys: sets.append('%s = ?'%key) values.append(rec[key]) query += ', '.join(sets) query += ' WHERE msg_id == ?' values.append(msg_id) self._db.execute(query, values)
def drop_matching_records(self, check): """Remove a record from the DB.""" expr,args = self._render_expression(check) query = "DELETE FROM %s WHERE %s"%(self.table, expr) self._db.execute(query,args)
def find_records(self, check, keys=None): """Find records matching a query dict, optionally extracting subset of keys. Returns list of matching records. Parameters ---------- check: dict mongodb-style query argument keys: list of strs [optional] if specified, the subset of keys to extract. msg_id will *always* be included. """ if keys: bad_keys = [ key for key in keys if key not in self._keys ] if bad_keys: raise KeyError("Bad record key(s): %s"%bad_keys) if keys: # ensure msg_id is present and first: if 'msg_id' in keys: keys.remove('msg_id') keys.insert(0, 'msg_id') req = ', '.join(keys) else: req = '*' expr,args = self._render_expression(check) query = """SELECT %s FROM %s WHERE %s"""%(req, self.table, expr) cursor = self._db.execute(query, args) matches = cursor.fetchall() records = [] for line in matches: rec = self._list_to_dict(line, keys) records.append(rec) return records
def get_history(self): """get all msg_ids, ordered by time submitted.""" query = """SELECT msg_id FROM %s ORDER by submitted ASC"""%self.table cursor = self._db.execute(query) # will be a list of length 1 tuples return [ tup[0] for tup in cursor.fetchall()]
def warn(msg,level=2,exit_val=1): """Standard warning printer. Gives formatting consistency. Output is sent to io.stderr (sys.stderr by default). Options: -level(2): allows finer control: 0 -> Do nothing, dummy function. 1 -> Print message. 2 -> Print 'WARNING:' + message. (Default level). 3 -> Print 'ERROR:' + message. 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). -exit_val (1): exit value returned by sys.exit() for a level 4 warning. Ignored for all other levels.""" if level>0: header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] io.stderr.write('%s%s' % (header[level],msg)) if level == 4: print >> io.stderr,'Exiting.\n' sys.exit(exit_val)
def parse(self, config_file=None, specs=None, default_file=None): """Read a config_file, check the validity with a JSON Schema as specs and get default values from default_file if asked. All parameters are optionnal. If there is no config_file defined, read the venv base dir and try to get config/app.yml. If no specs, don't validate anything. If no default_file, don't merge with default values.""" self._config_exists(config_file) self._specs_exists(specs) self.loaded_config = anyconfig.load(self.config_file, ac_parser='yaml') if default_file is not None: self._merge_default(default_file) if self.specs is None: return self.loaded_config self._validate() return self.loaded_config
def table(rows): ''' Output a simple table with several columns. ''' output = '<table>' for row in rows: output += '<tr>' for column in row: output += '<td>{s}</td>'.format(s=column) output += '</tr>' output += '</table>' return output
def link(url, text='', classes='', target='', get="", **kwargs): ''' Output a link tag. ''' if not (url.startswith('http') or url.startswith('/')): # Handle additional reverse args. urlargs = {} for arg, val in kwargs.items(): if arg[:4] == "url_": urlargs[arg[4:]] = val url = reverse(url, kwargs=urlargs) if get: url += '?' + get return html.tag('a', text or url, { 'class': classes, 'target': target, 'href': url})
def jsfile(url): ''' Output a script tag to a js file. ''' if not url.startswith('http://') and not url[:1] == '/': #add media_url for relative paths url = settings.STATIC_URL + url return '<script type="text/javascript" src="{src}"></script>'.format( src=url)
def cssfile(url): ''' Output a link tag to a css stylesheet. ''' if not url.startswith('http://') and not url[:1] == '/': #add media_url for relative paths url = settings.STATIC_URL + url return '<link href="{src}" rel="stylesheet">'.format(src=url)
def img(url, alt='', classes='', style=''): ''' Image tag helper. ''' if not url.startswith('http://') and not url[:1] == '/': #add media_url for relative paths url = settings.STATIC_URL + url attr = { 'class': classes, 'alt': alt, 'style': style, 'src': url } return html.tag('img', '', attr)
def sub(value, arg): """Subtract the arg from the value.""" try: return valid_numeric(value) - valid_numeric(arg) except (ValueError, TypeError): try: return value - arg except Exception: return ''
def mul(value, arg): """Multiply the arg with the value.""" try: return valid_numeric(value) * valid_numeric(arg) except (ValueError, TypeError): try: return value * arg except Exception: return ''
def div(value, arg): """Divide the arg by the value.""" try: return valid_numeric(value) / valid_numeric(arg) except (ValueError, TypeError): try: return value / arg except Exception: return ''
def mod(value, arg): """Return the modulo value.""" try: return valid_numeric(value) % valid_numeric(arg) except (ValueError, TypeError): try: return value % arg except Exception: return ''
def model_verbose(obj, capitalize=True): """ Return the verbose name of a model. The obj argument can be either a Model instance, or a ModelForm instance. This allows to retrieve the verbose name of the model of a ModelForm easily, without adding extra context vars. """ if isinstance(obj, ModelForm): name = obj._meta.model._meta.verbose_name elif isinstance(obj, Model): name = obj._meta.verbose_name else: raise Exception('Unhandled type: ' + type(obj)) return name.capitalize() if capitalize else name
def extendManager(mixinClass): ''' Use as a class decorator to add extra methods to your model manager. Example usage: class Article(django.db.models.Model): published = models.DateTimeField() ... @extendManager class objects(object): def getPublished(self): return self.filter(published__lte = django.utils.timezone.now()).order_by('-published') ... publishedArticles = Article.objects.getPublished() ''' class MixinManager(models.Manager, mixinClass): class MixinQuerySet(models.query.QuerySet, mixinClass): pass def get_queryset(self): return self.MixinQuerySet(self.model, using = self._db) return MixinManager()
def run(): """Main method where all logic is defined""" config_option_help="'show' - displays configured options, 'set [section] [name] [value]' - sets config under a section,'set [name] [value]' - sets configuration globally" parser = OptionParser() parser.add_option("-a", "--add", action="store", type="string", dest="addfile", help="adds a notes") parser.add_option("-c", "--config", action="store", type="string", dest="config", help=config_option_help) parser.add_option("-e", "--edit", action="store", type="string", dest="editfile", help="edits a notes") parser.add_option("-o", "--open", action="store", type="string", dest="openfile", help="opens a notes") parser.add_option("-r", "--remove", action="store", type="string", dest="remove", help="removes a notes") options, args = parser.parse_args() if options.config: if options.config == "show": config_option_list='' config_sections = config.sections() for section in config_sections: config_option_list=config_option_list+section+"\n" section_items =config.items(section) for item in section_items: config_option_list=config_option_list+" "+item[0]+" "+item[1]+"\n" print config_option_list quit() def add_notes(note_name,existing_tags): call([editor,environ["HOME"] + "/.mypy/myhelp/notes/"+note_name+".note"]) definedtags = raw_input("Define Tags (separated by spaces): ").split(" ") definedtags.append(note_name) print definedtags print existing_tags definedtags=list(set(definedtags)-set(existing_tags)) print definedtags if len(definedtags)>0: modify_tags_xml(note_name,definedtags,files,rootfiles,tags,roottags,tree,TAGS_XML_DIR) def get_tags_from_file(note_name): fil = get_file_from_files(note_name) filetags = fil.iter('tag') filetaglist=[] for tag in filetags: filetaglist.append(tag.text) return filetaglist if options.addfile: existing_tags=[] if isFile(options.addfile,files): existing_tags=get_tags_from_file(options.addfile) raw_input("Note exists with tags - "+" ".join(existing_tags)+"\nDo you want to edit the notes ? [Press enter to continue]\n") add_notes(options.addfile,existing_tags) quit() if options.editfile: if isFile(options.editfile,files): add_notes(note_name,[]) else: raw_input("Note doesn't exist.\nDo you want add note ? [Press enter to continue]") add_notes(note_name) if options.remove: pass if len(args) != 1: print "Please use a search term\n example : myhelp <some tag word> " quit() _key_File = "Note" _key_Results = " Results " table={_key_Results:[]} for tag in tags: if tag.attrib["value"] == args[0]: fileelements = tag.iter("file") for fileelement in fileelements: f = open( environ["HOME"] + "/.mypy/myhelp/notes/" + fileelement.text+".note", "r") table[_key_Results].append(f.read()+"\r\n\tfile: ~/.mypy/myhelp/notes/"+fileelement.text+".note") f.close() print tabulate(table,headers=[],tablefmt="rst")
def split_user_input(line, pattern=None): """Split user input into initial whitespace, escape character, function part and the rest. """ # We need to ensure that the rest of this routine deals only with unicode encoding = get_stream_enc(sys.stdin, 'utf-8') line = py3compat.cast_unicode(line, encoding) if pattern is None: pattern = line_split match = pattern.match(line) if not match: # print "match failed for line '%s'" % line try: ifun, the_rest = line.split(None,1) except ValueError: # print "split failed for line '%s'" % line ifun, the_rest = line, u'' pre = re.match('^(\s*)(.*)',line).groups()[0] esc = "" else: pre, esc, ifun, the_rest = match.groups() #print 'line:<%s>' % line # dbg #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun.strip(),the_rest) # dbg return pre, esc or '', ifun.strip(), the_rest.lstrip()
def current(context, urlName, className = 'active', **kwargs): ''' Return a class name (string) if the current URL matches the route name specified in ``className``. If any URL keyword arguments are provided, they must be matched as well. :param urlName: The route name that the current URL should match. Example: 'accounts:login'. :param className: The string that is returned if the current URL matches the specified one. :param kwargs: Any extra URL keyword arguments that must also be present in the current URL for it to match. :returns: ``className`` if the current URL matches, or an empty string otherwise. ''' matches = pathMatches(context['request'].path, urlName, **kwargs) return className if matches else ''
def pathMatches(path, urlName, **kwargs): ''' :param path: str :param urlName: str :returns: bool. ''' resolved = urlresolvers.resolve(path) # Different URL name => the current URL cannot match. resolvedName = '{r.namespace}:{r.url_name}'.format(r = resolved) if resolved.namespace else resolved.url_name if urlName != resolvedName: return False # If any of the current keyword args is missing or different, the URL cannot match. for key, value in kwargs.items(): currentArg = resolved.kwargs.get(key) if currentArg is None or str(value) != str(currentArg): return False return True
def options(self, parser, env): """ Register command-line options. """ parser.add_option("--processes", action="store", default=env.get('NOSE_PROCESSES', 0), dest="multiprocess_workers", metavar="NUM", help="Spread test run among this many processes. " "Set a number equal to the number of processors " "or cores in your machine for best results. " "[NOSE_PROCESSES]") parser.add_option("--process-timeout", action="store", default=env.get('NOSE_PROCESS_TIMEOUT', 10), dest="multiprocess_timeout", metavar="SECONDS", help="Set timeout for return of results from each " "test runner process. [NOSE_PROCESS_TIMEOUT]") parser.add_option("--process-restartworker", action="store_true", default=env.get('NOSE_PROCESS_RESTARTWORKER', False), dest="multiprocess_restartworker", help="If set, will restart each worker process once" " their tests are done, this helps control memory " "leaks from killing the system. " "[NOSE_PROCESS_RESTARTWORKER]")
def configure(self, options, config): """ Configure plugin. """ try: self.status.pop('active') except KeyError: pass if not hasattr(options, 'multiprocess_workers'): self.enabled = False return # don't start inside of a worker process if config.worker: return self.config = config try: workers = int(options.multiprocess_workers) except (TypeError, ValueError): workers = 0 if workers: _import_mp() if Process is None: self.enabled = False return self.enabled = True self.config.multiprocess_workers = workers t = float(options.multiprocess_timeout) self.config.multiprocess_timeout = t r = int(options.multiprocess_restartworker) self.config.multiprocess_restartworker = r self.status['active'] = True
def run(self, result): """Run tests in suite inside of suite fixtures. """ # proxy the result for myself log.debug("suite %s (%s) run called, tests: %s", id(self), self, self._tests) if self.resultProxy: result, orig = self.resultProxy(result, self), result else: result, orig = result, result try: #log.debug('setUp for %s', id(self)); self.setUp() except KeyboardInterrupt: raise except: self.error_context = 'setup' result.addError(self, self._exc_info()) return try: for test in self._tests: if (isinstance(test,nose.case.Test) and self.arg is not None): test.test.arg = self.arg else: test.arg = self.arg test.testQueue = self.testQueue test.tasks = self.tasks if result.shouldStop: log.debug("stopping") break # each nose.case.Test will create its own result proxy # so the cases need the original result, to avoid proxy # chains #log.debug('running test %s in suite %s', test, self); try: test(orig) except KeyboardInterrupt, e: timeout = isinstance(e, TimedOutException) if timeout: msg = 'Timeout when running test %s in suite %s' else: msg = 'KeyboardInterrupt when running test %s in suite %s' log.debug(msg, test, self) err = (TimedOutException,TimedOutException(str(test)), sys.exc_info()[2]) test.config.plugins.addError(test,err) orig.addError(test,err) if not timeout: raise finally: self.has_run = True try: #log.debug('tearDown for %s', id(self)); self.tearDown() except KeyboardInterrupt: raise except: self.error_context = 'teardown' result.addError(self, self._exc_info())
def add_builtin(self, key, value): """Add a builtin and save the original.""" bdict = __builtin__.__dict__ orig = bdict.get(key, BuiltinUndefined) if value is HideBuiltin: if orig is not BuiltinUndefined: #same as 'key in bdict' self._orig_builtins[key] = orig del bdict[key] else: self._orig_builtins[key] = orig bdict[key] = value
def remove_builtin(self, key, orig): """Remove an added builtin and re-set the original.""" if orig is BuiltinUndefined: del __builtin__.__dict__[key] else: __builtin__.__dict__[key] = orig
def activate(self): """Store ipython references in the __builtin__ namespace.""" add_builtin = self.add_builtin for name, func in self.auto_builtins.iteritems(): add_builtin(name, func)
def deactivate(self): """Remove any builtins which might have been added by add_builtins, or restore overwritten ones to their previous values.""" remove_builtin = self.remove_builtin for key, val in self._orig_builtins.iteritems(): remove_builtin(key, val) self._orig_builtins.clear() self._builtins_added = False
def _find_url_name(self, index_url, url_name, req): """ Finds the true URL name of a package, when the given name isn't quite correct. This is usually used to implement case-insensitivity. """ if not index_url.url.endswith('/'): # Vaguely part of the PyPI API... weird but true. # FIXME: bad to modify this? index_url.url += '/' page = self._get_page(index_url, req) if page is None: logger.critical('Cannot fetch index base URL %s', index_url) return norm_name = normalize_name(req.url_name) for link in page.links: base = posixpath.basename(link.path.rstrip('/')) if norm_name == normalize_name(base): logger.debug( 'Real name of requirement %s is %s', url_name, base, ) return base return None
def _link_package_versions(self, link, search_name): """ Return an iterable of triples (pkg_resources_version_key, link, python_version) that can be extracted from the given link. Meant to be overridden by subclasses, not called by clients. """ platform = get_platform() version = None if link.egg_fragment: egg_info = link.egg_fragment else: egg_info, ext = link.splitext() if not ext: if link not in self.logged_links: logger.debug('Skipping link %s; not a file', link) self.logged_links.add(link) return if egg_info.endswith('.tar'): # Special double-extension case: egg_info = egg_info[:-4] ext = '.tar' + ext if ext not in self._known_extensions(): if link not in self.logged_links: logger.debug( 'Skipping link %s; unknown archive format: %s', link, ext, ) self.logged_links.add(link) return if "macosx10" in link.path and ext == '.zip': if link not in self.logged_links: logger.debug('Skipping link %s; macosx10 one', link) self.logged_links.add(link) return if ext == wheel_ext: try: wheel = Wheel(link.filename) except InvalidWheelFilename: logger.debug( 'Skipping %s because the wheel filename is invalid', link ) return if (pkg_resources.safe_name(wheel.name).lower() != pkg_resources.safe_name(search_name).lower()): logger.debug( 'Skipping link %s; wrong project name (not %s)', link, search_name, ) return if not wheel.supported(): logger.debug( 'Skipping %s because it is not compatible with this ' 'Python', link, ) return # This is a dirty hack to prevent installing Binary Wheels from # PyPI unless it is a Windows or Mac Binary Wheel. This is # paired with a change to PyPI disabling uploads for the # same. Once we have a mechanism for enabling support for # binary wheels on linux that deals with the inherent problems # of binary distribution this can be removed. comes_from = getattr(link, "comes_from", None) if ( ( not platform.startswith('win') and not platform.startswith('macosx') and not platform == 'cli' ) and comes_from is not None and urllib_parse.urlparse( comes_from.url ).netloc.endswith(PyPI.netloc)): if not wheel.supported(tags=supported_tags_noarch): logger.debug( "Skipping %s because it is a pypi-hosted binary " "Wheel on an unsupported platform", link, ) return version = wheel.version if not version: version = self._egg_info_matches(egg_info, search_name, link) if version is None: logger.debug( 'Skipping link %s; wrong project name (not %s)', link, search_name, ) return if (link.internal is not None and not link.internal and not normalize_name(search_name).lower() in self.allow_external and not self.allow_all_external): # We have a link that we are sure is external, so we should skip # it unless we are allowing externals logger.debug("Skipping %s because it is externally hosted.", link) self.need_warn_external = True return if (link.verifiable is not None and not link.verifiable and not (normalize_name(search_name).lower() in self.allow_unverified)): # We have a link that we are sure we cannot verify its integrity, # so we should skip it unless we are allowing unsafe installs # for this requirement. logger.debug( "Skipping %s because it is an insecure and unverifiable file.", link, ) self.need_warn_unverified = True return match = self._py_version_re.search(version) if match: version = version[:match.start()] py_version = match.group(1) if py_version != sys.version[:3]: logger.debug( 'Skipping %s because Python version is incorrect', link ) return logger.debug('Found link %s, version: %s', link, version) return InstallationCandidate(search_name, version, link)
def explicit_rel_links(self, rels=('homepage', 'download')): """Yields all links with the given relations""" rels = set(rels) for anchor in self.parsed.findall(".//a"): if anchor.get("rel") and anchor.get("href"): found_rels = set(anchor.get("rel").split()) # Determine the intersection between what rels were found and # what rels were being looked for if found_rels & rels: href = anchor.get("href") url = self.clean_link( urllib_parse.urljoin(self.base_url, href) ) yield Link(url, self, trusted=False)
def send_multi_alt_email( subject, # single line with no line-breaks text_content, to_emails, html_content=None, from_email=DEFAULT_FROM_EMAIL, fail_silently=True ): """ Send a message to one more email address(s). With text content as primary and html content as alternative. """ messenger = EmailMultiAlternatives(subject, text_content, from_email, to_emails) if html_content: messenger.attach_alternative(html_content, "text/html") try: messenger.send() except Exception as e: if not fail_silently: raise
def send_html_email( subject, # single line with no line-breaks html_content, to_emails, from_email=DEFAULT_FROM_EMAIL, fail_silently=True ): """ Send a message to one more email address(s). With html content as primary. """ messenger = EmailMessage(subject, html_content, from_email, to_emails) messenger.content_subtype = "html" # Main content is now text/html try: messenger.send() except Exception as e: if not fail_silently: raise
def trim_form(parser, token): """ Returns a form that only contains a subset of the original fields (opcode: incude/exclude fields) Exampel: <fieldset> <legend>Business Info</legend> <ul> {% trim_form orig_form fields biz_name,biz_city,biz_email,biz_phone as new_form %} {{ new_form.as_ul }} </ul> </fieldset> OR: <fieldset> <legend>Business Info</legend> <ul> {% trim_form orig_form exclude biz_country,biz_url as new_form %} {{ new_form.as_ul }} </ul> </fieldset> """ try: trim_form, orig_form, opcode, fields, as_, new_form = token.split_contents() except ValueError: raise template.TemplateSyntaxError('Invalid arguments for %r' % token.split_contents()[0]) return FieldSetNode(opcode, fields.split(','), orig_form, new_form)
def unshell_list(s): """Turn a command-line argument into a list.""" if not s: return None if sys.platform == 'win32': # When running coverage as coverage.exe, some of the behavior # of the shell is emulated: wildcards are expanded into a list of # filenames. So you have to single-quote patterns on the command # line, but (not) helpfully, the single quotes are included in the # argument, so we have to strip them off here. s = s.strip("'") return s.split(',')
def main(argv=None): """The main entry point to Coverage. This is installed as the script entry point. """ if argv is None: argv = sys.argv[1:] try: start = time.clock() status = CoverageScript().command_line(argv) end = time.clock() if 0: print("time: %.3fs" % (end - start)) except ExceptionDuringRun: # An exception was caught while running the product code. The # sys.exc_info() return tuple is packed into an ExceptionDuringRun # exception. _, err, _ = sys.exc_info() traceback.print_exception(*err.args) status = ERR except CoverageException: # A controlled error inside coverage.py: print the message to the user. _, err, _ = sys.exc_info() print(err) status = ERR except SystemExit: # The user called `sys.exit()`. Exit with their argument, if any. _, err, _ = sys.exc_info() if err.args: status = err.args[0] else: status = None return status
def parse_args(self, args=None, options=None): """Call optparse.parse_args, but return a triple: (ok, options, args) """ try: options, args = \ super(CoverageOptionParser, self).parse_args(args, options) except self.OptionParserError: return False, None, None return True, options, args
def add_action(self, dash, dashdash, action_code): """Add a specialized option that is the action to execute.""" option = self.add_option(dash, dashdash, action='callback', callback=self._append_action ) option.action_code = action_code
def _append_action(self, option, opt_unused, value_unused, parser): """Callback for an option that adds to the `actions` list.""" parser.values.actions.append(option.action_code)
def command_line(self, argv): """The bulk of the command line interface to Coverage. `argv` is the argument list to process. Returns 0 if all is well, 1 if something went wrong. """ # Collect the command-line options. if not argv: self.help_fn(topic='minimum_help') return OK # The command syntax we parse depends on the first argument. Classic # syntax always starts with an option. self.classic = argv[0].startswith('-') if self.classic: parser = ClassicOptionParser() else: parser = CMDS.get(argv[0]) if not parser: self.help_fn("Unknown command: '%s'" % argv[0]) return ERR argv = argv[1:] parser.help_fn = self.help_fn ok, options, args = parser.parse_args(argv) if not ok: return ERR # Handle help and version. if self.do_help(options, args, parser): return OK # Check for conflicts and problems in the options. if not self.args_ok(options, args): return ERR # Listify the list options. source = unshell_list(options.source) omit = unshell_list(options.omit) include = unshell_list(options.include) debug = unshell_list(options.debug) # Do something. self.coverage = self.covpkg.coverage( data_suffix = options.parallel_mode, cover_pylib = options.pylib, timid = options.timid, branch = options.branch, config_file = options.rcfile, source = source, omit = omit, include = include, debug = debug, ) if 'debug' in options.actions: return self.do_debug(args) if 'erase' in options.actions or options.erase_first: self.coverage.erase() else: self.coverage.load() if 'execute' in options.actions: self.do_execute(options, args) if 'combine' in options.actions: self.coverage.combine() self.coverage.save() # Remaining actions are reporting, with some common options. report_args = dict( morfs = args, ignore_errors = options.ignore_errors, omit = omit, include = include, ) if 'report' in options.actions: total = self.coverage.report( show_missing=options.show_missing, **report_args) if 'annotate' in options.actions: self.coverage.annotate( directory=options.directory, **report_args) if 'html' in options.actions: total = self.coverage.html_report( directory=options.directory, title=options.title, **report_args) if 'xml' in options.actions: outfile = options.outfile total = self.coverage.xml_report(outfile=outfile, **report_args) if options.fail_under is not None: if total >= options.fail_under: return OK else: return FAIL_UNDER else: return OK
def help(self, error=None, topic=None, parser=None): """Display an error message, or the named topic.""" assert error or topic or parser if error: print(error) print("Use 'coverage help' for help.") elif parser: print(parser.format_help().strip()) else: help_msg = HELP_TOPICS.get(topic, '').strip() if help_msg: print(help_msg % self.covpkg.__dict__) else: print("Don't know topic %r" % topic)
def do_help(self, options, args, parser): """Deal with help requests. Return True if it handled the request, False if not. """ # Handle help. if options.help: if self.classic: self.help_fn(topic='help') else: self.help_fn(parser=parser) return True if "help" in options.actions: if args: for a in args: parser = CMDS.get(a) if parser: self.help_fn(parser=parser) else: self.help_fn(topic=a) else: self.help_fn(topic='help') return True # Handle version. if options.version: self.help_fn(topic='version') return True return False
def args_ok(self, options, args): """Check for conflicts and problems in the options. Returns True if everything is ok, or False if not. """ for i in ['erase', 'execute']: for j in ['annotate', 'html', 'report', 'combine']: if (i in options.actions) and (j in options.actions): self.help_fn("You can't specify the '%s' and '%s' " "options at the same time." % (i, j)) return False if not options.actions: self.help_fn( "You must specify at least one of -e, -x, -c, -r, -a, or -b." ) return False args_allowed = ( 'execute' in options.actions or 'annotate' in options.actions or 'html' in options.actions or 'debug' in options.actions or 'report' in options.actions or 'xml' in options.actions ) if not args_allowed and args: self.help_fn("Unexpected arguments: %s" % " ".join(args)) return False if 'execute' in options.actions and not args: self.help_fn("Nothing to do.") return False return True
def do_execute(self, options, args): """Implementation of 'coverage run'.""" # Set the first path element properly. old_path0 = sys.path[0] # Run the script. self.coverage.start() code_ran = True try: try: if options.module: sys.path[0] = '' self.run_python_module(args[0], args) else: filename = args[0] sys.path[0] = os.path.abspath(os.path.dirname(filename)) self.run_python_file(filename, args) except NoSource: code_ran = False raise finally: self.coverage.stop() if code_ran: self.coverage.save() # Restore the old path sys.path[0] = old_path0
def do_debug(self, args): """Implementation of 'coverage debug'.""" if not args: self.help_fn("What information would you like: data, sys?") return ERR for info in args: if info == 'sys': print("-- sys ----------------------------------------") for line in info_formatter(self.coverage.sysinfo()): print(" %s" % line) elif info == 'data': print("-- data ---------------------------------------") self.coverage.load() print("path: %s" % self.coverage.data.filename) print("has_arcs: %r" % self.coverage.data.has_arcs()) summary = self.coverage.data.summary(fullpath=True) if summary: filenames = sorted(summary.keys()) print("\n%d files:" % len(filenames)) for f in filenames: print("%s: %d lines" % (f, summary[f])) else: print("No data collected") else: self.help_fn("Don't know what you mean by %r" % info) return ERR return OK
def serialize_object(obj, threshold=64e-6): """Serialize an object into a list of sendable buffers. Parameters ---------- obj : object The object to be serialized threshold : float The threshold for not double-pickling the content. Returns ------- ('pmd', [bufs]) : where pmd is the pickled metadata wrapper, bufs is a list of data buffers """ databuffers = [] if isinstance(obj, (list, tuple)): clist = canSequence(obj) slist = map(serialize, clist) for s in slist: if s.typeDescriptor in ('buffer', 'ndarray') or s.getDataSize() > threshold: databuffers.append(s.getData()) s.data = None return pickle.dumps(slist,-1), databuffers elif isinstance(obj, dict): sobj = {} for k in sorted(obj.iterkeys()): s = serialize(can(obj[k])) if s.typeDescriptor in ('buffer', 'ndarray') or s.getDataSize() > threshold: databuffers.append(s.getData()) s.data = None sobj[k] = s return pickle.dumps(sobj,-1),databuffers else: s = serialize(can(obj)) if s.typeDescriptor in ('buffer', 'ndarray') or s.getDataSize() > threshold: databuffers.append(s.getData()) s.data = None return pickle.dumps(s,-1),databuffers
def unserialize_object(bufs): """reconstruct an object serialized by serialize_object from data buffers.""" bufs = list(bufs) sobj = pickle.loads(bufs.pop(0)) if isinstance(sobj, (list, tuple)): for s in sobj: if s.data is None: s.data = bufs.pop(0) return uncanSequence(map(unserialize, sobj)), bufs elif isinstance(sobj, dict): newobj = {} for k in sorted(sobj.iterkeys()): s = sobj[k] if s.data is None: s.data = bufs.pop(0) newobj[k] = uncan(unserialize(s)) return newobj, bufs else: if sobj.data is None: sobj.data = bufs.pop(0) return uncan(unserialize(sobj)), bufs
def pack_apply_message(f, args, kwargs, threshold=64e-6): """pack up a function, args, and kwargs to be sent over the wire as a series of buffers. Any object whose data is larger than `threshold` will not have their data copied (currently only numpy arrays support zero-copy)""" msg = [pickle.dumps(can(f),-1)] databuffers = [] # for large objects sargs, bufs = serialize_object(args,threshold) msg.append(sargs) databuffers.extend(bufs) skwargs, bufs = serialize_object(kwargs,threshold) msg.append(skwargs) databuffers.extend(bufs) msg.extend(databuffers) return msg
def unpack_apply_message(bufs, g=None, copy=True): """unpack f,args,kwargs from buffers packed by pack_apply_message() Returns: original f,args,kwargs""" bufs = list(bufs) # allow us to pop assert len(bufs) >= 3, "not enough buffers!" if not copy: for i in range(3): bufs[i] = bufs[i].bytes cf = pickle.loads(bufs.pop(0)) sargs = list(pickle.loads(bufs.pop(0))) skwargs = dict(pickle.loads(bufs.pop(0))) # print sargs, skwargs f = uncan(cf, g) for sa in sargs: if sa.data is None: m = bufs.pop(0) if sa.getTypeDescriptor() in ('buffer', 'ndarray'): # always use a buffer, until memoryviews get sorted out sa.data = buffer(m) # disable memoryview support # if copy: # sa.data = buffer(m) # else: # sa.data = m.buffer else: if copy: sa.data = m else: sa.data = m.bytes args = uncanSequence(map(unserialize, sargs), g) kwargs = {} for k in sorted(skwargs.iterkeys()): sa = skwargs[k] if sa.data is None: m = bufs.pop(0) if sa.getTypeDescriptor() in ('buffer', 'ndarray'): # always use a buffer, until memoryviews get sorted out sa.data = buffer(m) # disable memoryview support # if copy: # sa.data = buffer(m) # else: # sa.data = m.buffer else: if copy: sa.data = m else: sa.data = m.bytes kwargs[k] = uncan(unserialize(sa), g) return f,args,kwargs
def set(self): """Set the hook.""" if sys.displayhook is not self.hook: self.old_hook = sys.displayhook sys.displayhook = self.hook
def log_errors(f, self, *args, **kwargs): """decorator to log unhandled exceptions raised in a method. For use wrapping on_recv callbacks, so that exceptions do not cause the stream to be closed. """ try: return f(self, *args, **kwargs) except Exception: self.log.error("Uncaught exception in %r" % f, exc_info=True)
def is_url(url): """boolean check for whether a string is a zmq url""" if '://' not in url: return False proto, addr = url.split('://', 1) if proto.lower() not in ['tcp','pgm','epgm','ipc','inproc']: return False return True
def validate_url(url): """validate a url for zeromq""" if not isinstance(url, basestring): raise TypeError("url must be a string, not %r"%type(url)) url = url.lower() proto_addr = url.split('://') assert len(proto_addr) == 2, 'Invalid url: %r'%url proto, addr = proto_addr assert proto in ['tcp','pgm','epgm','ipc','inproc'], "Invalid protocol: %r"%proto # domain pattern adapted from http://www.regexlib.com/REDetails.aspx?regexp_id=391 # author: Remi Sabourin pat = re.compile(r'^([\w\d]([\w\d\-]{0,61}[\w\d])?\.)*[\w\d]([\w\d\-]{0,61}[\w\d])?$') if proto == 'tcp': lis = addr.split(':') assert len(lis) == 2, 'Invalid url: %r'%url addr,s_port = lis try: port = int(s_port) except ValueError: raise AssertionError("Invalid port %r in url: %r"%(port, url)) assert addr == '*' or pat.match(addr) is not None, 'Invalid url: %r'%url else: # only validate tcp urls currently pass return True
def validate_url_container(container): """validate a potentially nested collection of urls.""" if isinstance(container, basestring): url = container return validate_url(url) elif isinstance(container, dict): container = container.itervalues() for element in container: validate_url_container(element)
def split_url(url): """split a zmq url (tcp://ip:port) into ('tcp','ip','port').""" proto_addr = url.split('://') assert len(proto_addr) == 2, 'Invalid url: %r'%url proto, addr = proto_addr lis = addr.split(':') assert len(lis) == 2, 'Invalid url: %r'%url addr,s_port = lis return proto,addr,s_port
def disambiguate_ip_address(ip, location=None): """turn multi-ip interfaces '0.0.0.0' and '*' into connectable ones, based on the location (default interpretation of location is localhost).""" if ip in ('0.0.0.0', '*'): try: external_ips = socket.gethostbyname_ex(socket.gethostname())[2] except (socket.gaierror, IndexError): # couldn't identify this machine, assume localhost external_ips = [] if location is None or location in external_ips or not external_ips: # If location is unspecified or cannot be determined, assume local ip='127.0.0.1' elif location: return location return ip
def disambiguate_url(url, location=None): """turn multi-ip interfaces '0.0.0.0' and '*' into connectable ones, based on the location (default interpretation is localhost). This is for zeromq urls, such as tcp://*:10101.""" try: proto,ip,port = split_url(url) except AssertionError: # probably not tcp url; could be ipc, etc. return url ip = disambiguate_ip_address(ip,location) return "%s://%s:%s"%(proto,ip,port)
def _pull(keys): """helper method for implementing `client.pull` via `client.apply`""" user_ns = globals() if isinstance(keys, (list,tuple, set)): for key in keys: if not user_ns.has_key(key): raise NameError("name '%s' is not defined"%key) return map(user_ns.get, keys) else: if not user_ns.has_key(keys): raise NameError("name '%s' is not defined"%keys) return user_ns.get(keys)
def select_random_ports(n): """Selects and return n random ports that are available.""" ports = [] for i in xrange(n): sock = socket.socket() sock.bind(('', 0)) while sock.getsockname()[1] in _random_ports: sock.close() sock = socket.socket() sock.bind(('', 0)) ports.append(sock) for i, sock in enumerate(ports): port = sock.getsockname()[1] sock.close() ports[i] = port _random_ports.add(port) return ports
def signal_children(children): """Relay interupt/term signals to children, for more solid process cleanup.""" def terminate_children(sig, frame): log = Application.instance().log log.critical("Got signal %i, terminating children..."%sig) for child in children: child.terminate() sys.exit(sig != SIGINT) # sys.exit(sig) for sig in (SIGINT, SIGABRT, SIGTERM): signal(sig, terminate_children)
def remote(view, block=None, **flags): """Turn a function into a remote function. This method can be used for map: In [1]: @remote(view,block=True) ...: def func(a): ...: pass """ def remote_function(f): return RemoteFunction(view, f, block=block, **flags) return remote_function
def parallel(view, dist='b', block=None, ordered=True, **flags): """Turn a function into a parallel remote function. This method can be used for map: In [1]: @parallel(view, block=True) ...: def func(a): ...: pass """ def parallel_function(f): return ParallelFunction(view, f, dist=dist, block=block, ordered=ordered, **flags) return parallel_function
def map(self, *sequences): """call a function on each element of a sequence remotely. This should behave very much like the builtin map, but return an AsyncMapResult if self.block is False. """ # set _map as a flag for use inside self.__call__ self._map = True try: ret = self.__call__(*sequences) finally: del self._map return ret
def get_readline_tail(self, n=10): """Get the last n items in readline history.""" end = self.shell.readline.get_current_history_length() + 1 start = max(end-n, 1) ghi = self.shell.readline.get_history_item return [ghi(x) for x in range(start, end)]
def set_autoindent(self,value=None): """Set the autoindent flag, checking for readline support. If called with no arguments, it acts as a toggle.""" if value != 0 and not self.has_readline: if os.name == 'posix': warn("The auto-indent feature requires the readline library") self.autoindent = 0 return if value is None: self.autoindent = not self.autoindent else: self.autoindent = value
def init_logstart(self): """Initialize logging in case it was requested at the command line. """ if self.logappend: self.magic('logstart %s append' % self.logappend) elif self.logfile: self.magic('logstart %s' % self.logfile) elif self.logstart: self.magic('logstart')
def init_virtualenv(self): """Add a virtualenv to sys.path so the user can import modules from it. This isn't perfect: it doesn't use the Python interpreter with which the virtualenv was built, and it ignores the --no-site-packages option. A warning will appear suggesting the user installs IPython in the virtualenv, but for many cases, it probably works well enough. Adapted from code snippets online. http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv """ if 'VIRTUAL_ENV' not in os.environ: # Not in a virtualenv return if sys.executable.startswith(os.environ['VIRTUAL_ENV']): # Running properly in the virtualenv, don't need to do anything return warn("Attempting to work in a virtualenv. If you encounter problems, please " "install IPython inside the virtualenv.\n") if sys.platform == "win32": virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') else: virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', 'python%d.%d' % sys.version_info[:2], 'site-packages') import site sys.path.insert(0, virtual_env) site.addsitedir(virtual_env)
def save_sys_module_state(self): """Save the state of hooks in the sys module. This has to be called after self.user_module is created. """ self._orig_sys_module_state = {} self._orig_sys_module_state['stdin'] = sys.stdin self._orig_sys_module_state['stdout'] = sys.stdout self._orig_sys_module_state['stderr'] = sys.stderr self._orig_sys_module_state['excepthook'] = sys.excepthook self._orig_sys_modules_main_name = self.user_module.__name__ self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
def restore_sys_module_state(self): """Restore the state of the sys module.""" try: for k, v in self._orig_sys_module_state.iteritems(): setattr(sys, k, v) except AttributeError: pass # Reset what what done in self.init_sys_modules if self._orig_sys_modules_main_mod is not None: sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): """set_hook(name,hook) -> sets an internal IPython hook. IPython exposes some of its internal API as user-modifiable hooks. By adding your function to one of these hooks, you can modify IPython's behavior to call at runtime your own routines.""" # At some point in the future, this should validate the hook before it # accepts it. Probably at least check that the hook takes the number # of args it's supposed to. f = types.MethodType(hook,self) # check if the hook is for strdispatcher first if str_key is not None: sdp = self.strdispatchers.get(name, StrDispatch()) sdp.add_s(str_key, f, priority ) self.strdispatchers[name] = sdp return if re_key is not None: sdp = self.strdispatchers.get(name, StrDispatch()) sdp.add_re(re.compile(re_key), f, priority ) self.strdispatchers[name] = sdp return dp = getattr(self.hooks, name, None) if name not in IPython.core.hooks.__all__: print "Warning! Hook '%s' is not one of %s" % \ (name, IPython.core.hooks.__all__ ) if not dp: dp = IPython.core.hooks.CommandChainDispatcher() try: dp.add(f,priority) except AttributeError: # it was not commandchain, plain old func - replace dp = f setattr(self.hooks,name, dp)
def register_post_execute(self, func): """Register a function for calling after code execution. """ if not callable(func): raise ValueError('argument %s must be callable' % func) self._post_execute[func] = True
def new_main_mod(self,ns=None): """Return a new 'main' module object for user code execution. """ main_mod = self._user_main_module init_fakemod_dict(main_mod,ns) return main_mod
def cache_main_mod(self,ns,fname): """Cache a main module's namespace. When scripts are executed via %run, we must keep a reference to the namespace of their __main__ module (a FakeModule instance) around so that Python doesn't clear it, rendering objects defined therein useless. This method keeps said reference in a private dict, keyed by the absolute path of the module object (which corresponds to the script path). This way, for multiple executions of the same script we only keep one copy of the namespace (the last one), thus preventing memory leaks from old references while allowing the objects from the last execution to be accessible. Note: we can not allow the actual FakeModule instances to be deleted, because of how Python tears down modules (it hard-sets all their references to None without regard for reference counts). This method must therefore make a *copy* of the given namespace, to allow the original module's __dict__ to be cleared and reused. Parameters ---------- ns : a namespace (a dict, typically) fname : str Filename associated with the namespace. Examples -------- In [10]: import IPython In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) In [12]: IPython.__file__ in _ip._main_ns_cache Out[12]: True """ self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
def debugger(self,force=False): """Call the pydb/pdb debugger. Keywords: - force(False): by default, this routine checks the instance call_pdb flag and does not actually invoke the debugger if the flag is false. The 'force' option forces the debugger to activate even if the flag is false. """ if not (force or self.call_pdb): return if not hasattr(sys,'last_traceback'): error('No traceback has been produced, nothing to debug.') return # use pydb if available if debugger.has_pydb: from pydb import pm else: # fallback to our internal debugger pm = lambda : self.InteractiveTB.debugger(force=True) with self.readline_no_record: pm()
def prepare_user_module(self, user_module=None, user_ns=None): """Prepare the module and namespace in which user code will be run. When IPython is started normally, both parameters are None: a new module is created automatically, and its __dict__ used as the namespace. If only user_module is provided, its __dict__ is used as the namespace. If only user_ns is provided, a dummy module is created, and user_ns becomes the global namespace. If both are provided (as they may be when embedding), user_ns is the local namespace, and user_module provides the global namespace. Parameters ---------- user_module : module, optional The current user module in which IPython is being run. If None, a clean module will be created. user_ns : dict, optional A namespace in which to run interactive commands. Returns ------- A tuple of user_module and user_ns, each properly initialised. """ if user_module is None and user_ns is not None: user_ns.setdefault("__name__", "__main__") class DummyMod(object): "A dummy module used for IPython's interactive namespace." pass user_module = DummyMod() user_module.__dict__ = user_ns if user_module is None: user_module = types.ModuleType("__main__", doc="Automatically created module for IPython interactive environment") # We must ensure that __builtin__ (without the final 's') is always # available and pointing to the __builtin__ *module*. For more details: # http://mail.python.org/pipermail/python-dev/2001-April/014068.html user_module.__dict__.setdefault('__builtin__', builtin_mod) user_module.__dict__.setdefault('__builtins__', builtin_mod) if user_ns is None: user_ns = user_module.__dict__ return user_module, user_ns
def init_user_ns(self): """Initialize all user-visible namespaces to their minimum defaults. Certain history lists are also initialized here, as they effectively act as user namespaces. Notes ----- All data structures here are only filled in, they are NOT reset by this method. If they were not empty before, data will simply be added to therm. """ # This function works in two parts: first we put a few things in # user_ns, and we sync that contents into user_ns_hidden so that these # initial variables aren't shown by %who. After the sync, we add the # rest of what we *do* want the user to see with %who even on a new # session (probably nothing, so theye really only see their own stuff) # The user dict must *always* have a __builtin__ reference to the # Python standard __builtin__ namespace, which must be imported. # This is so that certain operations in prompt evaluation can be # reliably executed with builtins. Note that we can NOT use # __builtins__ (note the 's'), because that can either be a dict or a # module, and can even mutate at runtime, depending on the context # (Python makes no guarantees on it). In contrast, __builtin__ is # always a module object, though it must be explicitly imported. # For more details: # http://mail.python.org/pipermail/python-dev/2001-April/014068.html ns = dict() # Put 'help' in the user namespace try: from site import _Helper ns['help'] = _Helper() except ImportError: warn('help() not available - check site.py') # make global variables for user access to the histories ns['_ih'] = self.history_manager.input_hist_parsed ns['_oh'] = self.history_manager.output_hist ns['_dh'] = self.history_manager.dir_hist ns['_sh'] = shadowns # user aliases to input and output histories. These shouldn't show up # in %who, as they can have very large reprs. ns['In'] = self.history_manager.input_hist_parsed ns['Out'] = self.history_manager.output_hist # Store myself as the public api!!! ns['get_ipython'] = self.get_ipython ns['exit'] = self.exiter ns['quit'] = self.exiter # Sync what we've added so far to user_ns_hidden so these aren't seen # by %who self.user_ns_hidden.update(ns) # Anything put into ns now would show up in %who. Think twice before # putting anything here, as we really want %who to show the user their # stuff, not our variables. # Finally, update the real user's namespace self.user_ns.update(ns)
def all_ns_refs(self): """Get a list of references to all the namespace dictionaries in which IPython might store a user-created object. Note that this does not include the displayhook, which also caches objects from the output.""" return [self.user_ns, self.user_global_ns, self._user_main_module.__dict__] + self._main_ns_cache.values()
def reset(self, new_session=True): """Clear all internal namespaces, and attempt to release references to user objects. If new_session is True, a new history session will be opened. """ # Clear histories self.history_manager.reset(new_session) # Reset counter used to index all histories if new_session: self.execution_count = 1 # Flush cached output items if self.displayhook.do_full_cache: self.displayhook.flush() # The main execution namespaces must be cleared very carefully, # skipping the deletion of the builtin-related keys, because doing so # would cause errors in many object's __del__ methods. if self.user_ns is not self.user_global_ns: self.user_ns.clear() ns = self.user_global_ns drop_keys = set(ns.keys()) drop_keys.discard('__builtin__') drop_keys.discard('__builtins__') drop_keys.discard('__name__') for k in drop_keys: del ns[k] self.user_ns_hidden.clear() # Restore the user namespaces to minimal usability self.init_user_ns() # Restore the default and user aliases self.alias_manager.clear_aliases() self.alias_manager.init_aliases() # Flush the private list of module references kept for script # execution protection self.clear_main_mod_cache() # Clear out the namespace from the last %run self.new_main_mod()
def del_var(self, varname, by_name=False): """Delete a variable from the various namespaces, so that, as far as possible, we're not keeping any hidden references to it. Parameters ---------- varname : str The name of the variable to delete. by_name : bool If True, delete variables with the given name in each namespace. If False (default), find the variable in the user namespace, and delete references to it. """ if varname in ('__builtin__', '__builtins__'): raise ValueError("Refusing to delete %s" % varname) ns_refs = self.all_ns_refs if by_name: # Delete by name for ns in ns_refs: try: del ns[varname] except KeyError: pass else: # Delete by object try: obj = self.user_ns[varname] except KeyError: raise NameError("name '%s' is not defined" % varname) # Also check in output history ns_refs.append(self.history_manager.output_hist) for ns in ns_refs: to_delete = [n for n, o in ns.iteritems() if o is obj] for name in to_delete: del ns[name] # displayhook keeps extra references, but not in a dictionary for name in ('_', '__', '___'): if getattr(self.displayhook, name) is obj: setattr(self.displayhook, name, None)
def reset_selective(self, regex=None): """Clear selective variables from internal namespaces based on a specified regular expression. Parameters ---------- regex : string or compiled pattern, optional A regular expression pattern that will be used in searching variable names in the users namespaces. """ if regex is not None: try: m = re.compile(regex) except TypeError: raise TypeError('regex must be a string or compiled pattern') # Search for keys in each namespace that match the given regex # If a match is found, delete the key/value pair. for ns in self.all_ns_refs: for var in ns: if m.search(var): del ns[var]
def push(self, variables, interactive=True): """Inject a group of variables into the IPython user namespace. Parameters ---------- variables : dict, str or list/tuple of str The variables to inject into the user's namespace. If a dict, a simple update is done. If a str, the string is assumed to have variable names separated by spaces. A list/tuple of str can also be used to give the variable names. If just the variable names are give (list/tuple/str) then the variable values looked up in the callers frame. interactive : bool If True (default), the variables will be listed with the ``who`` magic. """ vdict = None # We need a dict of name/value pairs to do namespace updates. if isinstance(variables, dict): vdict = variables elif isinstance(variables, (basestring, list, tuple)): if isinstance(variables, basestring): vlist = variables.split() else: vlist = variables vdict = {} cf = sys._getframe(1) for name in vlist: try: vdict[name] = eval(name, cf.f_globals, cf.f_locals) except: print ('Could not get variable %s from %s' % (name,cf.f_code.co_name)) else: raise ValueError('variables must be a dict/str/list/tuple') # Propagate variables to user namespace self.user_ns.update(vdict) # And configure interactive visibility user_ns_hidden = self.user_ns_hidden if interactive: user_ns_hidden.difference_update(vdict) else: user_ns_hidden.update(vdict)
def drop_by_id(self, variables): """Remove a dict of variables from the user namespace, if they are the same as the values in the dictionary. This is intended for use by extensions: variables that they've added can be taken back out if they are unloaded, without removing any that the user has overwritten. Parameters ---------- variables : dict A dictionary mapping object names (as strings) to the objects. """ for name, obj in variables.iteritems(): if name in self.user_ns and self.user_ns[name] is obj: del self.user_ns[name] self.user_ns_hidden.discard(name)
def _ofind(self, oname, namespaces=None): """Find an object in the available namespaces. self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic Has special code to detect magic functions. """ oname = oname.strip() #print '1- oname: <%r>' % oname # dbg if not oname.startswith(ESC_MAGIC) and \ not oname.startswith(ESC_MAGIC2) and \ not py3compat.isidentifier(oname, dotted=True): return dict(found=False) alias_ns = None if namespaces is None: # Namespaces to search in: # Put them in a list. The order is important so that we # find things in the same order that Python finds them. namespaces = [ ('Interactive', self.user_ns), ('Interactive (global)', self.user_global_ns), ('Python builtin', builtin_mod.__dict__), ('Alias', self.alias_manager.alias_table), ] alias_ns = self.alias_manager.alias_table # initialize results to 'null' found = False; obj = None; ospace = None; ds = None; ismagic = False; isalias = False; parent = None # We need to special-case 'print', which as of python2.6 registers as a # function but should only be treated as one if print_function was # loaded with a future import. In this case, just bail. if (oname == 'print' and not py3compat.PY3 and not \ (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): return {'found':found, 'obj':obj, 'namespace':ospace, 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} # Look for the given name by splitting it in parts. If the head is # found, then we look for all the remaining parts as members, and only # declare success if we can find them all. oname_parts = oname.split('.') oname_head, oname_rest = oname_parts[0],oname_parts[1:] for nsname,ns in namespaces: try: obj = ns[oname_head] except KeyError: continue else: #print 'oname_rest:', oname_rest # dbg for part in oname_rest: try: parent = obj obj = getattr(obj,part) except: # Blanket except b/c some badly implemented objects # allow __getattr__ to raise exceptions other than # AttributeError, which then crashes IPython. break else: # If we finish the for loop (no break), we got all members found = True ospace = nsname if ns == alias_ns: isalias = True break # namespace loop # Try to see if it's magic if not found: obj = None if oname.startswith(ESC_MAGIC2): oname = oname.lstrip(ESC_MAGIC2) obj = self.find_cell_magic(oname) elif oname.startswith(ESC_MAGIC): oname = oname.lstrip(ESC_MAGIC) obj = self.find_line_magic(oname) else: # search without prefix, so run? will find %run? obj = self.find_line_magic(oname) if obj is None: obj = self.find_cell_magic(oname) if obj is not None: found = True ospace = 'IPython internal' ismagic = True # Last try: special-case some literals like '', [], {}, etc: if not found and oname_head in ["''",'""','[]','{}','()']: obj = eval(oname_head) found = True ospace = 'Interactive' return {'found':found, 'obj':obj, 'namespace':ospace, 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
def _ofind_property(self, oname, info): """Second part of object finding, to look for property details.""" if info.found: # Get the docstring of the class property if it exists. path = oname.split('.') root = '.'.join(path[:-1]) if info.parent is not None: try: target = getattr(info.parent, '__class__') # The object belongs to a class instance. try: target = getattr(target, path[-1]) # The class defines the object. if isinstance(target, property): oname = root + '.__class__.' + path[-1] info = Struct(self._ofind(oname)) except AttributeError: pass except AttributeError: pass # We return either the new info or the unmodified input if the object # hadn't been found return info
def _object_find(self, oname, namespaces=None): """Find an object and return a struct with info about it.""" inf = Struct(self._ofind(oname, namespaces)) return Struct(self._ofind_property(oname, inf))
def _inspect(self, meth, oname, namespaces=None, **kw): """Generic interface to the inspector system. This function is meant to be called by pdef, pdoc & friends.""" info = self._object_find(oname, namespaces) if info.found: pmethod = getattr(self.inspector, meth) formatter = format_screen if info.ismagic else None if meth == 'pdoc': pmethod(info.obj, oname, formatter) elif meth == 'pinfo': pmethod(info.obj, oname, formatter, info, **kw) else: pmethod(info.obj, oname) else: print 'Object `%s` not found.' % oname return 'not found'
def init_history(self): """Sets up the command history, and starts regular autosaves.""" self.history_manager = HistoryManager(shell=self, config=self.config) self.configurables.append(self.history_manager)
def set_custom_exc(self, exc_tuple, handler): """set_custom_exc(exc_tuple,handler) Set a custom exception handler, which will be called if any of the exceptions in exc_tuple occur in the mainloop (specifically, in the run_code() method). Parameters ---------- exc_tuple : tuple of exception classes A *tuple* of exception classes, for which to call the defined handler. It is very important that you use a tuple, and NOT A LIST here, because of the way Python's except statement works. If you only want to trap a single exception, use a singleton tuple:: exc_tuple == (MyCustomException,) handler : callable handler must have the following signature:: def my_handler(self, etype, value, tb, tb_offset=None): ... return structured_traceback Your handler must return a structured traceback (a list of strings), or None. This will be made into an instance method (via types.MethodType) of IPython itself, and it will be called if any of the exceptions listed in the exc_tuple are caught. If the handler is None, an internal basic one is used, which just prints basic info. To protect IPython from crashes, if your handler ever raises an exception or returns an invalid result, it will be immediately disabled. WARNING: by putting in your own exception handler into IPython's main execution loop, you run a very good chance of nasty crashes. This facility should only be used if you really know what you are doing.""" assert type(exc_tuple)==type(()) , \ "The custom exceptions must be given AS A TUPLE." def dummy_handler(self,etype,value,tb,tb_offset=None): print '*** Simple custom exception handler ***' print 'Exception type :',etype print 'Exception value:',value print 'Traceback :',tb #print 'Source code :','\n'.join(self.buffer) def validate_stb(stb): """validate structured traceback return type return type of CustomTB *should* be a list of strings, but allow single strings or None, which are harmless. This function will *always* return a list of strings, and will raise a TypeError if stb is inappropriate. """ msg = "CustomTB must return list of strings, not %r" % stb if stb is None: return [] elif isinstance(stb, basestring): return [stb] elif not isinstance(stb, list): raise TypeError(msg) # it's a list for line in stb: # check every element if not isinstance(line, basestring): raise TypeError(msg) return stb if handler is None: wrapped = dummy_handler else: def wrapped(self,etype,value,tb,tb_offset=None): """wrap CustomTB handler, to protect IPython from user code This makes it harder (but not impossible) for custom exception handlers to crash IPython. """ try: stb = handler(self,etype,value,tb,tb_offset=tb_offset) return validate_stb(stb) except: # clear custom handler immediately self.set_custom_exc((), None) print >> io.stderr, "Custom TB Handler failed, unregistering" # show the exception in handler first stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) print >> io.stdout, self.InteractiveTB.stb2text(stb) print >> io.stdout, "The original exception:" stb = self.InteractiveTB.structured_traceback( (etype,value,tb), tb_offset=tb_offset ) return stb self.CustomTB = types.MethodType(wrapped,self) self.custom_exceptions = exc_tuple
def excepthook(self, etype, value, tb): """One more defense for GUI apps that call sys.excepthook. GUI frameworks like wxPython trap exceptions and call sys.excepthook themselves. I guess this is a feature that enables them to keep running after exceptions that would otherwise kill their mainloop. This is a bother for IPython which excepts to catch all of the program exceptions with a try: except: statement. Normally, IPython sets sys.excepthook to a CrashHandler instance, so if any app directly invokes sys.excepthook, it will look to the user like IPython crashed. In order to work around this, we can disable the CrashHandler and replace it with this excepthook instead, which prints a regular traceback using our InteractiveTB. In this fashion, apps which call sys.excepthook will generate a regular-looking exception from IPython, and the CrashHandler will only be triggered by real IPython crashes. This hook should be used sparingly, only in places which are not likely to be true IPython errors. """ self.showtraceback((etype,value,tb),tb_offset=0)
def _get_exc_info(self, exc_tuple=None): """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. Ensures sys.last_type,value,traceback hold the exc_info we found, from whichever source. raises ValueError if none of these contain any information """ if exc_tuple is None: etype, value, tb = sys.exc_info() else: etype, value, tb = exc_tuple if etype is None: if hasattr(sys, 'last_type'): etype, value, tb = sys.last_type, sys.last_value, \ sys.last_traceback if etype is None: raise ValueError("No exception to find") # Now store the exception info in sys.last_type etc. # WARNING: these variables are somewhat deprecated and not # necessarily safe to use in a threaded environment, but tools # like pdb depend on their existence, so let's set them. If we # find problems in the field, we'll need to revisit their use. sys.last_type = etype sys.last_value = value sys.last_traceback = tb return etype, value, tb
def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, exception_only=False): """Display the exception that just occurred. If nothing is known about the exception, this is the method which should be used throughout the code for presenting user tracebacks, rather than directly invoking the InteractiveTB object. A specific showsyntaxerror() also exists, but this method can take care of calling it if needed, so unless you are explicitly catching a SyntaxError exception, don't try to analyze the stack manually and simply call this method.""" try: try: etype, value, tb = self._get_exc_info(exc_tuple) except ValueError: self.write_err('No traceback available to show.\n') return if etype is SyntaxError: # Though this won't be called by syntax errors in the input # line, there may be SyntaxError cases with imported code. self.showsyntaxerror(filename) elif etype is UsageError: self.write_err("UsageError: %s" % value) else: if exception_only: stb = ['An exception has occurred, use %tb to see ' 'the full traceback.\n'] stb.extend(self.InteractiveTB.get_exception_only(etype, value)) else: try: # Exception classes can customise their traceback - we # use this in IPython.parallel for exceptions occurring # in the engines. This should return a list of strings. stb = value._render_traceback_() except Exception: stb = self.InteractiveTB.structured_traceback(etype, value, tb, tb_offset=tb_offset) self._showtraceback(etype, value, stb) if self.call_pdb: # drop into debugger self.debugger(force=True) return # Actually show the traceback self._showtraceback(etype, value, stb) except KeyboardInterrupt: self.write_err("\nKeyboardInterrupt\n")
def _showtraceback(self, etype, evalue, stb): """Actually show a traceback. Subclasses may override this method to put the traceback on a different place, like a side channel. """ print >> io.stdout, self.InteractiveTB.stb2text(stb)