INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return a valid python filename in the current directory.
def get_py_filename(name, force_win32=None): """Return a valid python filename in the current directory. If the given name is not a file, it adds '.py' and searches again. Raises IOError with an informative message if the file isn't found. On Windows, apply Windows semantics to the filename. In partic...
Find a file by looking through a sequence of paths.
def filefind(filename, path_dirs=None): """Find a file by looking through a sequence of paths. This iterates through a sequence of paths looking for a file and returns the full, absolute path of the first occurence of the file. If no set of path dirs is given, the filename is tested as is, after runni...
Return the home directory as a unicode string.
def get_home_dir(require_writable=False): """Return the 'home' directory, as a unicode string. * First, check for frozen env in case of py2exe * Otherwise, defer to os.path.expanduser('~') See stdlib docs for how this is determined. $HOME is first priority on *ALL* platforms. Paramete...
Return the XDG_CONFIG_HOME if it is defined and exists else None.
def get_xdg_dir(): """Return the XDG_CONFIG_HOME, if it is defined and exists, else None. This is only for non-OS X posix (Linux,Unix,etc.) systems. """ env = os.environ if os.name == 'posix' and sys.platform != 'darwin': # Linux, Unix, AIX, etc. # use ~/.config if empty OR not se...
Get the IPython directory for this platform and user.
def get_ipython_dir(): """Get the IPython directory for this platform and user. This uses the logic in `get_home_dir` to find the home directory and then adds .ipython to the end of the path. """ env = os.environ pjoin = os.path.join ipdir_def = '.ipython' xdg_def = 'ipython' ho...
Get the base directory where IPython itself is installed.
def get_ipython_package_dir(): """Get the base directory where IPython itself is installed.""" ipdir = os.path.dirname(IPython.__file__) return py3compat.cast_unicode(ipdir, fs_encoding)
Find the path to an IPython module in this version of IPython.
def get_ipython_module_path(module_str): """Find the path to an IPython module in this version of IPython. This will always find the version of the module that is in this importable IPython package. This will always return the path to the ``.py`` version of the module. """ if module_str == 'IPy...
Find the path to the folder associated with a given profile. I. e. find $IPYTHONDIR/ profile_whatever.
def locate_profile(profile='default'): """Find the path to the folder associated with a given profile. I.e. find $IPYTHONDIR/profile_whatever. """ from IPython.core.profiledir import ProfileDir, ProfileDirError try: pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile) ...
Expand $VARS and ~names in a string like a shell
def expand_path(s): """Expand $VARS and ~names in a string, like a shell :Examples: In [2]: os.environ['FOO']='test' In [3]: expand_path('variable FOO is $FOO') Out[3]: 'variable FOO is test' """ # This is a pretty subtle hack. When expand user is given a UNC path # on Window...
Determine whether a target is out of date.
def target_outdated(target,deps): """Determine whether a target is out of date. target_outdated(target,deps) -> 1/0 deps: list of filenames which MUST exist. target: single filename which may or may not exist. If target doesn't exist or is older than any file listed in deps, return true, othe...
Make an MD5 hash of a file ignoring any differences in line ending characters.
def filehash(path): """Make an MD5 hash of a file, ignoring any differences in line ending characters.""" with open(path, "rU") as f: return md5(py3compat.str_to_bytes(f.read())).hexdigest()
Check for old config files and present a warning if they exist.
def check_for_old_config(ipython_dir=None): """Check for old config files, and present a warning if they exist. A link to the docs of the new config is included in the message. This should mitigate confusion with the transition to the new config system in 0.11. """ if ipython_dir is None: ...
Return the absolute path of a security file given by filename and profile This allows users and developers to find security files without knowledge of the IPython directory structure. The search path will be [. profile. security_dir ] Parameters ---------- filename: str The file to be found. If it is passed as an absol...
def get_security_file(filename, profile='default'): """Return the absolute path of a security file given by filename and profile This allows users and developers to find security files without knowledge of the IPython directory structure. The search path will be ['.', profile.security_dir] ...
Updates the suggestions dictionary for an object upon visiting its page
def update_suggestions_dictionary(request, object): """ Updates the suggestions' dictionary for an object upon visiting its page """ if request.user.is_authenticated(): user = request.user content_type = ContentType.objects.get_for_model(type(object)) try: # Check if ...
Gets a list with a certain size of suggestions for an object
def get_suggestions_with_size(object, size): """ Gets a list with a certain size of suggestions for an object """ content_type = ContentType.objects.get_for_model(type(object)) try: return ObjectViewDictionary.objects.filter( current_object_id=object.id, current_content_type=...
Gets a list of all suggestions for an object
def get_suggestions(object): """ Gets a list of all suggestions for an object """ content_type = ContentType.objects.get_for_model(type(object)) return ObjectViewDictionary.objects.filter( current_object_id=object.id, current_content_type=content_type).extra(order_by=['-visits'])
Return this path as a relative path based from the current working directory.
def relpath(self): """ Return this path as a relative path, based from the current working directory. """ cwd = self.__class__(os.getcwdu()) return cwd.relpathto(self)
Return a list of path objects that match the pattern.
def glob(self, pattern): """ Return a list of path objects that match the pattern. pattern - a path relative to this directory, with wildcards. For example, path('/users').glob('*/bin/*') returns a list of all the files users have in their bin directories. """ cls = sel...
r Open this file read all lines return them in a list.
def lines(self, encoding=None, errors='strict', retain=True): r""" Open this file, read all lines, return them in a list. Optional arguments: encoding - The Unicode encoding (or character set) of the file. The default is None, meaning the content of the file...
Calculate the md5 hash for this file.
def read_md5(self): """ Calculate the md5 hash for this file. This reads through the entire file. """ f = self.open('rb') try: m = md5() while True: d = f.read(8192) if not d: break m.upd...
Register commandline options.
def options(self, parser, env): """Register commandline options. """ if not self.available(): return Plugin.options(self, parser, env) parser.add_option('--profile-sort', action='store', dest='profile_sort', default=env.get('NOSE_PROFILE_SORT...
Create profile stats file and load profiler.
def begin(self): """Create profile stats file and load profiler. """ if not self.available(): return self._create_pfile() self.prof = hotshot.Profile(self.pfile)
Configure plugin.
def configure(self, options, conf): """Configure plugin. """ if not self.available(): self.enabled = False return Plugin.configure(self, options, conf) self.conf = conf if options.profile_stats_file: self.pfile = options.profile_stats_f...
Output profiler report.
def report(self, stream): """Output profiler report. """ log.debug('printing profiler report') self.prof.close() prof_stats = stats.load(self.pfile) prof_stats.sort_stats(self.sort) # 2.5 has completely different stream handling from 2.4 and earlier. # Be...
Clean up stats file if configured to do so.
def finalize(self, result): """Clean up stats file, if configured to do so. """ if not self.available(): return try: self.prof.close() except AttributeError: # TODO: is this trying to catch just the case where not # hasattr(self.pro...
Handle CLI command
def handle(self, *args, **options): """Handle CLI command""" try: while True: Channel(HEARTBEAT_CHANNEL).send({'time':time.time()}) time.sleep(HEARTBEAT_FREQUENCY) except KeyboardInterrupt: print("Received keyboard interrupt, exiting...")
Enable event loop integration with wxPython.
def enable_wx(self, app=None): """Enable event loop integration with wxPython. Parameters ---------- app : WX Application, optional. Running application to use. If not given, we probe WX for an existing application object, and create a new one if none is found. ...
Disable event loop integration with wxPython.
def disable_wx(self): """Disable event loop integration with wxPython. This merely sets PyOS_InputHook to NULL. """ if self._apps.has_key(GUI_WX): self._apps[GUI_WX]._in_event_loop = False self.clear_inputhook()
Enable event loop integration with PyQt4. Parameters ---------- app: Qt Application optional. Running application to use. If not given we probe Qt for an existing application object and create a new one if none is found.
def enable_qt4(self, app=None): """Enable event loop integration with PyQt4. Parameters ---------- app : Qt Application, optional. Running application to use. If not given, we probe Qt for an existing application object, and create a new one if none is f...
Disable event loop integration with PyQt4.
def disable_qt4(self): """Disable event loop integration with PyQt4. This merely sets PyOS_InputHook to NULL. """ if self._apps.has_key(GUI_QT4): self._apps[GUI_QT4]._in_event_loop = False self.clear_inputhook()
Enable event loop integration with PyGTK.
def enable_gtk(self, app=None): """Enable event loop integration with PyGTK. Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supportin...
Enable event loop integration with Tk.
def enable_tk(self, app=None): """Enable event loop integration with Tk. Parameters ---------- app : toplevel :class:`Tkinter.Tk` widget, optional. Running toplevel widget to use. If not given, we probe Tk for an existing one, and create a new one if none is fou...
Enable event loop integration with pyglet.
def enable_pyglet(self, app=None): """Enable event loop integration with pyglet. Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of suppo...
Enable event loop integration with Gtk3 ( gir bindings ).
def enable_gtk3(self, app=None): """Enable event loop integration with Gtk3 (gir bindings). Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of ...
create a partitioner in the engine namespace
def setup_partitioner(index, num_procs, gnum_cells, parts): """create a partitioner in the engine namespace""" global partitioner p = MPIRectPartitioner2D(my_id=index, num_procs=num_procs) p.redim(global_num_cells=gnum_cells, num_parts=parts) p.prepare_communication() # put the partitioner into ...
save the wave log
def wave_saver(u, x, y, t): """save the wave log""" global u_hist global t_hist t_hist.append(t) u_hist.append(1.0*u)
Turn a string of history ranges into 3 - tuples of ( session start stop ).
def extract_hist_ranges(ranges_str): """Turn a string of history ranges into 3-tuples of (session, start, stop). Examples -------- list(extract_input_ranges("~8/5-~7/4 2")) [(-8, 5, None), (-7, 1, 4), (0, 2, 3)] """ for range_str in ranges_str.split(): rmatch = range_re.match(range_...
Connect to the database and create tables if necessary.
def init_db(self): """Connect to the database, and create tables if necessary.""" # use detect_types so that timestamps return datetime objects self.db = sqlite3.connect(self.hist_file, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) self.db.execute("""CR...
Prepares and runs an SQL query for the history database.
def _run_sql(self, sql, params, raw=True, output=False): """Prepares and runs an SQL query for the history database. Parameters ---------- sql : str Any filtering expressions to go after SELECT ... FROM ... params : tuple Parameters passed to the SQL query (t...
get info about a session
def get_session_info(self, session=0): """get info about a session Parameters ---------- session : int Session number to retrieve. The current session is 0, and negative numbers count back from current session, so -1 is previous session. Returns ...
Get the last n lines from the history database.
def get_tail(self, n=10, raw=True, output=False, include_latest=False): """Get the last n lines from the history database. Parameters ---------- n : int The number of lines to get raw, output : bool See :meth:`get_range` include_latest : bool ...
Search the database using unix glob - style matching ( wildcards * and ? ).
def search(self, pattern="*", raw=True, search_raw=True, output=False): """Search the database using unix glob-style matching (wildcards * and ?). Parameters ---------- pattern : str The wildcarded pattern to matc...
Retrieve input by session.
def get_range(self, session, start=1, stop=None, raw=True,output=False): """Retrieve input by session. Parameters ---------- session : int Session number to retrieve. start : int First line to retrieve. stop : int End of line range (ex...
Get lines of history from a string of ranges as used by magic commands %hist %save %macro etc.
def get_range_by_str(self, rangestr, raw=True, output=False): """Get lines of history from a string of ranges, as used by magic commands %hist, %save, %macro, etc. Parameters ---------- rangestr : str A string specifying ranges, e.g. "5 ~2/1-4". See :func:`ma...
Get default history file name based on the Shell s profile. The profile parameter is ignored but must exist for compatibility with the parent class.
def _get_hist_file_name(self, profile=None): """Get default history file name based on the Shell's profile. The profile parameter is ignored, but must exist for compatibility with the parent class.""" profile_dir = self.shell.profile_dir.location return os.path.join(prof...
Get a new session number.
def new_session(self, conn=None): """Get a new session number.""" if conn is None: conn = self.db with conn: cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL, NULL, "") """, (datetime.datetime.now(),)) self....
Close the database session filling in the end time and line count.
def end_session(self): """Close the database session, filling in the end time and line count.""" self.writeout_cache() with self.db: self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE session==?""", (datetime.datetime.now(), ...
Give the current session a name in the history database.
def name_session(self, name): """Give the current session a name in the history database.""" with self.db: self.db.execute("UPDATE sessions SET remark=? WHERE session==?", (name, self.session_number))
Clear the session history releasing all object references and optionally open a new session.
def reset(self, new_session=True): """Clear the session history, releasing all object references, and optionally open a new session.""" self.output_hist.clear() # The directory history can't be completely empty self.dir_hist[:] = [os.getcwdu()] if new_session: ...
Get input and output history from the current session. Called by get_range and takes similar parameters.
def _get_range_session(self, start=1, stop=None, raw=True, output=False): """Get input and output history from the current session. Called by get_range, and takes similar parameters.""" input_hist = self.input_hist_raw if raw else self.input_hist_parsed n = len(input_hist) ...
Retrieve input by session. Parameters ---------- session: int Session number to retrieve. The current session is 0 and negative numbers count back from current session so - 1 is previous session. start: int First line to retrieve. stop: int End of line range ( excluded from output itself ). If None retrieve to the end ...
def get_range(self, session=0, start=1, stop=None, raw=True,output=False): """Retrieve input by session. Parameters ---------- session : int Session number to retrieve. The current session is 0, and negative numbers count back from current session, so -1 ...
Store source and raw input in history and create input cache variables _i *.
def store_inputs(self, line_num, source, source_raw=None): """Store source and raw input in history and create input cache variables _i*. Parameters ---------- line_num : int The prompt number of this input. source : str Python input. source...
If database output logging is enabled this saves all the outputs from the indicated prompt number to the database. It s called by run_cell after code has been executed.
def store_output(self, line_num): """If database output logging is enabled, this saves all the outputs from the indicated prompt number to the database. It's called by run_cell after code has been executed. Parameters ---------- line_num : int The line number f...
Write any entries in the cache to the database.
def writeout_cache(self, conn=None): """Write any entries in the cache to the database.""" if conn is None: conn = self.db with self.db_input_cache_lock: try: self._writeout_input_cache(conn) except sqlite3.IntegrityError: self...
This can be called from the main thread to safely stop this thread.
def stop(self): """This can be called from the main thread to safely stop this thread. Note that it does not attempt to write out remaining history before exiting. That should be done by calling the HistoryManager's end_session method.""" self.stop_now = True self.histor...
Return system boot time ( epoch in seconds )
def _get_boot_time(): """Return system boot time (epoch in seconds)""" f = open('/proc/stat', 'r') try: for line in f: if line.startswith('btime'): return float(line.strip().split()[1]) raise RuntimeError("line not found") finally: f.close()
Return the number of CPUs on the system
def _get_num_cpus(): """Return the number of CPUs on the system""" # we try to determine num CPUs by using different approaches. # SC_NPROCESSORS_ONLN seems to be the safer and it is also # used by multiprocessing module try: return os.sysconf("SC_NPROCESSORS_ONLN") except ValueError: ...
Return a named tuple representing the following CPU times: user nice system idle iowait irq softirq.
def get_system_cpu_times(): """Return a named tuple representing the following CPU times: user, nice, system, idle, iowait, irq, softirq. """ f = open('/proc/stat', 'r') try: values = f.readline().split() finally: f.close() values = values[1:8] values = tuple([float(x) /...
Return a list of namedtuple representing the CPU times for every CPU available on the system.
def get_system_per_cpu_times(): """Return a list of namedtuple representing the CPU times for every CPU available on the system. """ cpus = [] f = open('/proc/stat', 'r') # get rid of the first line who refers to system wide CPU stats try: f.readline() for line in f.readlines...
Return mounted disk partitions as a list of nameduples
def disk_partitions(all=False): """Return mounted disk partitions as a list of nameduples""" phydevs = [] f = open("/proc/filesystems", "r") try: for line in f: if not line.startswith("nodev"): phydevs.append(line.strip()) finally: f.close() retlist =...
Return currently connected users as a list of namedtuples.
def get_system_users(): """Return currently connected users as a list of namedtuples.""" retlist = [] rawlist = _psutil_linux.get_system_users() for item in rawlist: user, tty, hostname, tstamp, user_process = item # XXX the underlying C function includes entries about # system b...
Returns a list of PIDs currently running on the system.
def get_pid_list(): """Returns a list of PIDs currently running on the system.""" pids = [int(x) for x in os.listdir('/proc') if x.isdigit()] return pids
Return network I/ O statistics for every network interface installed on the system as a dict of raw tuples.
def network_io_counters(): """Return network I/O statistics for every network interface installed on the system as a dict of raw tuples. """ f = open("/proc/net/dev", "r") try: lines = f.readlines() finally: f.close() retdict = {} for line in lines[2:]: colon = l...
Return disk I/ O statistics for every disk installed on the system as a dict of raw tuples.
def disk_io_counters(): """Return disk I/O statistics for every disk installed on the system as a dict of raw tuples. """ # man iostat states that sectors are equivalent with blocks and # have a size of 512 bytes since 2.4 kernels. This value is # needed to calculate the amount of disk I/O in by...
Call callable into a try/ except clause and translate ENOENT EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
def wrap_exceptions(callable): """Call callable into a try/except clause and translate ENOENT, EACCES and EPERM in NoSuchProcess or AccessDenied exceptions. """ def wrapper(self, *args, **kwargs): try: return callable(self, *args, **kwargs) except EnvironmentError: ...
Return process s mapped memory regions as a list of nameduples. Fields are explained in man proc ; here is an updated ( Apr 2012 ) version: http:// goo. gl/ fmebo
def get_memory_maps(self): """Return process's mapped memory regions as a list of nameduples. Fields are explained in 'man proc'; here is an updated (Apr 2012) version: http://goo.gl/fmebo """ f = None try: f = open("/proc/%s/smaps" % self.pid) fir...
Return connections opened by process as a list of namedtuples. The kind parameter filters for connections that fit the following criteria:
def get_connections(self, kind='inet'): """Return connections opened by process as a list of namedtuples. The kind parameter filters for connections that fit the following criteria: Kind Value Number of connections using inet IPv4 and IPv6 inet4 ...
Accept an ip: port address as displayed in/ proc/ net/ * and convert it into a human readable form like:
def _decode_address(addr, family): """Accept an "ip:port" address as displayed in /proc/net/* and convert it into a human readable form, like: "0500000A:0016" -> ("10.0.0.5", 22) "0000000000000000FFFF00000100007F:9E49" -> ("::ffff:127.0.0.1", 40521) The IP address portion is a ...
Make a nice string representation of a pair of numbers.
def nice_pair(pair): """Make a nice string representation of a pair of numbers. If the numbers are equal, just return the number, otherwise return the pair with a dash between them, indicating the range. """ start, end = pair if start == end: return "%d" % start else: retur...
Nicely format a list of line numbers.
def format_lines(statements, lines): """Nicely format a list of line numbers. Format a list of line numbers for printing by coalescing groups of lines as long as the lines represent consecutive statements. This will coalesce even if there are gaps between statements. For example, if `statements` ...
Return a string summarizing the call stack.
def short_stack(): """Return a string summarizing the call stack.""" stack = inspect.stack()[:0:-1] return "\n".join(["%30s : %s @%d" % (t[3],t[1],t[2]) for t in stack])
A decorator to cache the result of an expensive operation.
def expensive(fn): """A decorator to cache the result of an expensive operation. Only applies to methods with no arguments. """ attr = "_cache_" + fn.__name__ def _wrapped(self): """Inner fn that checks the cache.""" if not hasattr(self, attr): setattr(self, attr, fn(se...
Combine a list of regexes into one that matches any of them.
def join_regex(regexes): """Combine a list of regexes into one that matches any of them.""" if len(regexes) > 1: return "|".join(["(%s)" % r for r in regexes]) elif regexes: return regexes[0] else: return ""
Remove a file and don t get annoyed if it doesn t exist.
def file_be_gone(path): """Remove a file, and don't get annoyed if it doesn't exist.""" try: os.remove(path) except OSError: _, e, _ = sys.exc_info() if e.errno != errno.ENOENT: raise
Add v to the hash recursively if needed.
def update(self, v): """Add `v` to the hash, recursively if needed.""" self.md5.update(to_bytes(str(type(v)))) if isinstance(v, string_class): self.md5.update(to_bytes(v)) elif v is None: pass elif isinstance(v, (int, float)): self.md5.update(t...
List all profiles in the ipython_dir and cwd.
def update_profiles(self): """List all profiles in the ipython_dir and cwd. """ for path in [get_ipython_dir(), os.getcwdu()]: for profile in list_profiles_in(path): pd = self.get_profile_dir(profile, path) if profile not in self.profiles: ...
Start a cluster for a given profile.
def start_cluster(self, profile, n=None): """Start a cluster for a given profile.""" self.check_profile(profile) data = self.profiles[profile] if data['status'] == 'running': raise web.HTTPError(409, u'cluster already running') cl, esl, default_n = self.build_launcher...
Stop a cluster for a given profile.
def stop_cluster(self, profile): """Stop a cluster for a given profile.""" self.check_profile(profile) data = self.profiles[profile] if data['status'] == 'stopped': raise web.HTTPError(409, u'cluster not running') data = self.profiles[profile] cl = data['contr...
Ensure self. url contains full transport:// interface: port
def _propagate_url(self): """Ensure self.url contains full transport://interface:port""" if self.url: iface = self.url.split('://',1) if len(iface) == 2: self.transport,iface = iface iface = iface.split(':') self.ip = iface[0] i...
Find the full path to a. bat or. exe using the win32api module.
def _find_cmd(cmd): """Find the full path to a .bat or .exe using the win32api module.""" try: from win32api import SearchPath except ImportError: raise ImportError('you need to have pywin32 installed for this to work') else: PATH = os.environ['PATH'] extensions = ['.exe'...
Callback for _system.
def _system_body(p): """Callback for _system.""" enc = DEFAULT_ENCODING for line in read_no_interrupt(p.stdout).splitlines(): line = line.decode(enc, 'replace') print(line, file=sys.stdout) for line in read_no_interrupt(p.stderr).splitlines(): line = line.decode(enc, 'replace') ...
Win32 version of os. system () that works with network shares.
def system(cmd): """Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- None : we explicitly do NOT ret...
Return standard output of executing cmd in a shell.
def getoutput(cmd): """Return standard output of executing cmd in a shell. Accepts the same arguments as os.system(). Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- stdout : str """ with AvoidUNCPath() as path: if p...
create a partitioner in the engine namespace
def setup_partitioner(comm, addrs, index, num_procs, gnum_cells, parts): """create a partitioner in the engine namespace""" global partitioner p = ZMQRectPartitioner2D(comm, addrs, my_id=index, num_procs=num_procs) p.redim(global_num_cells=gnum_cells, num_parts=parts) p.prepare_communication() #...
Returns a list of ( code translation ) tuples for codes
def get_translations(codes): """ Returns a list of (code, translation) tuples for codes """ codes = codes or self.codes return self._get_priority_translations(priority, codes)
Returns a sorted list of ( code translation ) tuples for codes
def get_translations_sorted(codes): """ Returns a sorted list of (code, translation) tuples for codes """ codes = codes or self.codes return self._get_priority_translations(priority, codes)
Returns a list of ( code translation ) tuples for priority codes
def get_priority_translations(priority, codes): """ Returns a list of (code, translation) tuples for priority, codes """ priority = priority or self.priority codes = codes or self.codes return self._get_priority_translations(priority, codes)
Find the code units we ll report on.
def find_code_units(self, morfs): """Find the code units we'll report on. `morfs` is a list of modules or filenames. """ morfs = morfs or self.coverage.data.measured_files() file_locator = self.coverage.file_locator self.code_units = code_unit_factory(morfs, file_locato...
Run a reporting function on a number of morfs.
def report_files(self, report_fn, morfs, directory=None): """Run a reporting function on a number of morfs. `report_fn` is called for each relative morf in `morfs`. It is called as:: report_fn(code_unit, analysis) where `code_unit` is the `CodeUnit` for the morf, and `ana...
Wraps a test decorator so as to properly replicate metadata of the decorated function including nose s additional stuff ( namely setup and teardown ).
def make_decorator(func): """ Wraps a test decorator so as to properly replicate metadata of the decorated function, including nose's additional stuff (namely, setup and teardown). """ def decorate(newfunc): if hasattr(func, 'compat_func_name'): name = func.compat_func_name ...
Test must raise one of expected exceptions to pass.
def raises(*exceptions): """Test must raise one of expected exceptions to pass. Example use:: @raises(TypeError, ValueError) def test_raises_type_error(): raise TypeError("This test passes") @raises(Exception) def test_that_fails_by_passing(): pass If you want...
Call pdb. set_trace in the calling frame first restoring sys. stdout to the real output stream. Note that sys. stdout is NOT reset to whatever it was before the call once pdb is done!
def set_trace(): """Call pdb.set_trace in the calling frame, first restoring sys.stdout to the real output stream. Note that sys.stdout is NOT reset to whatever it was before the call once pdb is done! """ import pdb import sys stdout = sys.stdout sys.stdout = sys.__stdout__ pdb.Pdb(...
Test must finish within specified time limit to pass.
def timed(limit): """Test must finish within specified time limit to pass. Example use:: @timed(.1) def test_that_fails(): time.sleep(.2) """ def decorate(func): def newfunc(*arg, **kw): start = time.time() func(*arg, **kw) end = time.t...
Decorator to add setup and/ or teardown methods to a test function::
def with_setup(setup=None, teardown=None): """Decorator to add setup and/or teardown methods to a test function:: @with_setup(setup, teardown) def test_something(): " ... " Note that `with_setup` is useful *only* for test functions, not for test methods or inside of TestCase subclass...
Enable GUI event loop integration taking pylab into account.
def init_gui_pylab(self): """Enable GUI event loop integration, taking pylab into account.""" if self.gui or self.pylab: shell = self.shell try: if self.pylab: gui, backend = pylabtools.find_gui_and_backend(self.pylab) self....
Load all IPython extensions in IPythonApp. extensions.
def init_extensions(self): """Load all IPython extensions in IPythonApp.extensions. This uses the :meth:`ExtensionManager.load_extensions` to load all the extensions listed in ``self.extensions``. """ try: self.log.debug("Loading IPython extensions...") e...
run the pre - flight code specified via exec_lines
def init_code(self): """run the pre-flight code, specified via exec_lines""" self._run_startup_files() self._run_exec_lines() self._run_exec_files() self._run_cmd_line_code() self._run_module() # flush output, so itwon't be attached to the first cell ...
Run lines of code in IPythonApp. exec_lines in the user s namespace.
def _run_exec_lines(self): """Run lines of code in IPythonApp.exec_lines in the user's namespace.""" if not self.exec_lines: return try: self.log.debug("Running code from IPythonApp.exec_lines...") for line in self.exec_lines: try: ...
Run files from profile startup directory
def _run_startup_files(self): """Run files from profile startup directory""" startup_dir = self.profile_dir.startup_dir startup_files = glob.glob(os.path.join(startup_dir, '*.py')) startup_files += glob.glob(os.path.join(startup_dir, '*.ipy')) if not startup_files: re...
Run files from IPythonApp. exec_files
def _run_exec_files(self): """Run files from IPythonApp.exec_files""" if not self.exec_files: return self.log.debug("Running files in IPythonApp.exec_files...") try: for fname in self.exec_files: self._exec_file(fname) except: ...