Search is not available for this dataset
text
stringlengths
75
104k
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_file self.clean_stats_file = False else: self.pfile = None self.clean_stats_file = True self.fileno = None self.sort = options.profile_sort self.restrict = tolist(options.profile_restrict)
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. # Before 2.5, stats objects have no stream attribute; in 2.5 and later # a reference sys.stdout is stored before we can tweak it. compat_25 = hasattr(prof_stats, 'stream') if compat_25: tmp = prof_stats.stream prof_stats.stream = stream else: tmp = sys.stdout sys.stdout = stream try: if self.restrict: log.debug('setting profiler restriction to %s', self.restrict) prof_stats.print_stats(*self.restrict) else: prof_stats.print_stats() finally: if compat_25: prof_stats.stream = tmp else: sys.stdout = tmp
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.prof, "close")? If so, the function call should be # moved out of the try: suite. pass if self.clean_stats_file: if self.fileno: try: os.close(self.fileno) except OSError: pass try: os.unlink(self.pfile) except OSError: pass return None
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...")
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. Notes ----- This methods sets the ``PyOS_InputHook`` for wxPython, which allows the wxPython to integrate with terminal based applications like IPython. If ``app`` is not given we probe for an existing one, and return it if found. If no existing app is found, we create an :class:`wx.App` as follows:: import wx app = wx.App(redirect=False, clearSigInt=False) """ import wx wx_version = V(wx.__version__).version if wx_version < [2, 8]: raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__) from IPython.lib.inputhookwx import inputhook_wx self.set_inputhook(inputhook_wx) self._current_gui = GUI_WX import wx if app is None: app = wx.GetApp() if app is None: app = wx.App(redirect=False, clearSigInt=False) app._in_event_loop = True self._apps[GUI_WX] = app return app
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()
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 found. Notes ----- This methods sets the PyOS_InputHook for PyQt4, which allows the PyQt4 to integrate with terminal based applications like IPython. If ``app`` is not given we probe for an existing one, and return it if found. If no existing app is found, we create an :class:`QApplication` as follows:: from PyQt4 import QtCore app = QtGui.QApplication(sys.argv) """ from IPython.lib.inputhookqt4 import create_inputhook_qt4 app, inputhook_qt4 = create_inputhook_qt4(self, app) self.set_inputhook(inputhook_qt4) self._current_gui = GUI_QT4 app._in_event_loop = True self._apps[GUI_QT4] = app return app
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()
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 supporting magics. Notes ----- This methods sets the PyOS_InputHook for PyGTK, which allows the PyGTK to integrate with terminal based applications like IPython. """ import gtk try: gtk.set_interactive(True) self._current_gui = GUI_GTK except AttributeError: # For older versions of gtk, use our own ctypes version from IPython.lib.inputhookgtk import inputhook_gtk self.set_inputhook(inputhook_gtk) self._current_gui = GUI_GTK
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 found. Notes ----- If you have already created a :class:`Tkinter.Tk` object, the only thing done by this method is to register with the :class:`InputHookManager`, since creating that object automatically sets ``PyOS_InputHook``. """ self._current_gui = GUI_TK if app is None: import Tkinter app = Tkinter.Tk() app.withdraw() self._apps[GUI_TK] = app return app
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 supporting magics. Notes ----- This methods sets the ``PyOS_InputHook`` for pyglet, which allows pyglet to integrate with terminal based applications like IPython. """ import pyglet from IPython.lib.inputhookpyglet import inputhook_pyglet self.set_inputhook(inputhook_pyglet) self._current_gui = GUI_PYGLET return app
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 supporting magics. Notes ----- This methods sets the PyOS_InputHook for Gtk3, which allows the Gtk3 to integrate with terminal based applications like IPython. """ from IPython.lib.inputhookgtk3 import inputhook_gtk3 self.set_inputhook(inputhook_gtk3) self._current_gui = GUI_GTK
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 the global namespace: partitioner=p
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)
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_str) if not rmatch: continue start = int(rmatch.group("start")) end = rmatch.group("end") end = int(end) if end else start+1 # If no end specified, get (a, a+1) if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3] end += 1 startsess = rmatch.group("startsess") or "0" endsess = rmatch.group("endsess") or startsess startsess = int(startsess.replace("~","-")) endsess = int(endsess.replace("~","-")) assert endsess >= startsess if endsess == startsess: yield (startsess, start, end) continue # Multiple sessions in one range: yield (startsess, start, None) for sess in range(startsess+1, endsess): yield (sess, 1, None) yield (endsess, 1, end)
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("""CREATE TABLE IF NOT EXISTS sessions (session integer primary key autoincrement, start timestamp, end timestamp, num_cmds integer, remark text)""") self.db.execute("""CREATE TABLE IF NOT EXISTS history (session integer, line integer, source text, source_raw text, PRIMARY KEY (session, line))""") # Output history is optional, but ensure the table's there so it can be # enabled later. self.db.execute("""CREATE TABLE IF NOT EXISTS output_history (session integer, line integer, output text, PRIMARY KEY (session, line))""") self.db.commit()
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 (to replace "?") raw, output : bool See :meth:`get_range` Returns ------- Tuples as :meth:`get_range` """ toget = 'source_raw' if raw else 'source' sqlfrom = "history" if output: sqlfrom = "history LEFT JOIN output_history USING (session, line)" toget = "history.%s, output_history.output" % toget cur = self.db.execute("SELECT session, line, %s FROM %s " %\ (toget, sqlfrom) + sql, params) if output: # Regroup into 3-tuples, and parse JSON return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur) return cur
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 ------- (session_id [int], start [datetime], end [datetime], num_cmds [int], remark [unicode]) Sessions that are running or did not exit cleanly will have `end=None` and `num_cmds=None`. """ if session <= 0: session += self.session_number query = "SELECT * from sessions where session == ?" return self.db.execute(query, (session,)).fetchone()
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 If False (default), n+1 lines are fetched, and the latest one is discarded. This is intended to be used where the function is called by a user command, which it should not return. Returns ------- Tuples as :meth:`get_range` """ self.writeout_cache() if not include_latest: n += 1 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?", (n,), raw=raw, output=output) if not include_latest: return reversed(list(cur)[1:]) return reversed(list(cur))
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 match when searching search_raw : bool If True, search the raw input, otherwise, the parsed input raw, output : bool See :meth:`get_range` Returns ------- Tuples as :meth:`get_range` """ tosearch = "source_raw" if search_raw else "source" if output: tosearch = "history." + tosearch self.writeout_cache() return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,), raw=raw, output=output)
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 (excluded from output itself). If None, retrieve to the end of the session. raw : bool If True, return untranslated input output : bool If True, attempt to include output. This will be 'real' Python objects for the current session, or text reprs from previous sessions if db_log_output was enabled at the time. Where no output is found, None is used. Returns ------- An iterator over the desired lines. Each line is a 3-tuple, either (session, line, input) if output is False, or (session, line, (input, output)) if output is True. """ if stop: lineclause = "line >= ? AND line < ?" params = (session, start, stop) else: lineclause = "line>=?" params = (session, start) return self._run_sql("WHERE session==? AND %s""" % lineclause, params, raw=raw, output=output)
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:`magic_history` for full details. raw, output : bool As :meth:`get_range` Returns ------- Tuples as :meth:`get_range` """ for sess, s, e in extract_hist_ranges(rangestr): for line in self.get_range(sess, s, e, raw=raw, output=output): yield line
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(profile_dir, 'history.sqlite')
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.session_number = cur.lastrowid
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(), len(self.input_hist_parsed)-1, self.session_number)) self.session_number = 0
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))
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: if self.session_number: self.end_session() self.input_hist_parsed[:] = [""] self.input_hist_raw[:] = [""] self.new_session()
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) if start < 0: start += n if not stop or (stop > n): stop = n elif stop < 0: stop += n for i in range(start, stop): if output: line = (input_hist[i], self.output_hist_reprs.get(i)) else: line = input_hist[i] yield (0, i, line)
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 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 of the session. raw : bool If True, return untranslated input output : bool If True, attempt to include output. This will be 'real' Python objects for the current session, or text reprs from previous sessions if db_log_output was enabled at the time. Where no output is found, None is used. Returns ------- An iterator over the desired lines. Each line is a 3-tuple, either (session, line, input) if output is False, or (session, line, (input, output)) if output is True. """ if session <= 0: session += self.session_number if session==self.session_number: # Current session return self._get_range_session(start, stop, raw, output) return super(HistoryManager, self).get_range(session, start, stop, raw, output)
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_raw : str, optional If given, this is the raw input without any IPython transformations applied to it. If not given, ``source`` is used. """ if source_raw is None: source_raw = source source = source.rstrip('\n') source_raw = source_raw.rstrip('\n') # do not store exit/quit commands if self._exit_re.match(source_raw.strip()): return self.input_hist_parsed.append(source) self.input_hist_raw.append(source_raw) with self.db_input_cache_lock: self.db_input_cache.append((line_num, source, source_raw)) # Trigger to flush cache and write to DB. if len(self.db_input_cache) >= self.db_cache_size: self.save_flag.set() # update the auto _i variables self._iii = self._ii self._ii = self._i self._i = self._i00 self._i00 = source_raw # hackish access to user namespace to create _i1,_i2... dynamically new_i = '_i%s' % line_num to_main = {'_i': self._i, '_ii': self._ii, '_iii': self._iii, new_i : self._i00 } self.shell.push(to_main, interactive=False)
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 from which to save outputs """ if (not self.db_log_output) or (line_num not in self.output_hist_reprs): return output = self.output_hist_reprs[line_num] with self.db_output_cache_lock: self.db_output_cache.append((line_num, output)) if self.db_cache_size <= 1: self.save_flag.set()
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.new_session(conn) print("ERROR! Session/line number was not unique in", "database. History logging moved to new session", self.session_number) try: # Try writing to the new session. If this fails, don't # recurse self._writeout_input_cache(conn) except sqlite3.IntegrityError: pass finally: self.db_input_cache = [] with self.db_output_cache_lock: try: self._writeout_output_cache(conn) except sqlite3.IntegrityError: print("!! Session/line number for output was not unique", "in database. Output will not be stored.") finally: self.db_output_cache = []
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.history_manager.save_flag.set() self.join()
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()
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: # as a second fallback we try to parse /proc/cpuinfo num = 0 f = open('/proc/cpuinfo', 'r') try: lines = f.readlines() finally: f.close() for line in lines: if line.lower().startswith('processor'): num += 1 # unknown format (e.g. amrel/sparc architectures), see: # http://code.google.com/p/psutil/issues/detail?id=200 # try to parse /proc/stat as a last resort if num == 0: f = open('/proc/stat', 'r') try: lines = f.readlines() finally: f.close() search = re.compile('cpu\d') for line in lines: line = line.split(' ')[0] if search.match(line): num += 1 if num == 0: raise RuntimeError("can't determine number of CPUs") return num
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) / _CLOCK_TICKS for x in values]) return nt_sys_cputimes(*values[:7])
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(): if line.startswith('cpu'): values = line.split()[1:8] values = tuple([float(x) / _CLOCK_TICKS for x in values]) entry = nt_sys_cputimes(*values[:7]) cpus.append(entry) return cpus finally: f.close()
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 = [] partitions = _psutil_linux.get_disk_partitions() for partition in partitions: device, mountpoint, fstype, opts = partition if device == 'none': device = '' if not all: if device == '' or fstype not in phydevs: continue ntuple = nt_partition(device, mountpoint, fstype, opts) retlist.append(ntuple) return retlist
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 boot, run level and others. We might want # to use them in the future. if not user_process: continue if hostname == ':0.0': hostname = 'localhost' nt = nt_user(user, tty or None, hostname, tstamp) retlist.append(nt) return retlist
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
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 = line.find(':') assert colon > 0, line name = line[:colon].strip() fields = line[colon+1:].strip().split() bytes_recv = int(fields[0]) packets_recv = int(fields[1]) errin = int(fields[2]) dropin = int(fields[2]) bytes_sent = int(fields[8]) packets_sent = int(fields[9]) errout = int(fields[10]) dropout = int(fields[11]) retdict[name] = (bytes_sent, bytes_recv, packets_sent, packets_recv, errin, errout, dropin, dropout) return retdict
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 bytes. SECTOR_SIZE = 512 # determine partitions we want to look for partitions = [] f = open("/proc/partitions", "r") try: lines = f.readlines()[2:] finally: f.close() for line in lines: _, _, _, name = line.split() if name[-1].isdigit(): partitions.append(name) # retdict = {} f = open("/proc/diskstats", "r") try: lines = f.readlines() finally: f.close() for line in lines: _, _, name, reads, _, rbytes, rtime, writes, _, wbytes, wtime = \ line.split()[:11] if name in partitions: rbytes = int(rbytes) * SECTOR_SIZE wbytes = int(wbytes) * SECTOR_SIZE reads = int(reads) writes = int(writes) # TODO: times are expressed in milliseconds while OSX/BSD has # these expressed in nanoseconds; figure this out. rtime = int(rtime) wtime = int(wtime) retdict[name] = (reads, writes, rbytes, wbytes, rtime, wtime) return retdict
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: # ENOENT (no such file or directory) gets raised on open(). # ESRCH (no such process) can get raised on read() if # process is gone in meantime. err = sys.exc_info()[1] if err.errno in (errno.ENOENT, errno.ESRCH): raise NoSuchProcess(self.pid, self._process_name) if err.errno in (errno.EPERM, errno.EACCES): raise AccessDenied(self.pid, self._process_name) raise return wrapper
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) first_line = f.readline() current_block = [first_line] def get_blocks(): data = {} for line in f: fields = line.split(None, 5) if len(fields) >= 5: yield (current_block.pop(), data) current_block.append(line) else: data[fields[0]] = int(fields[1]) * 1024 yield (current_block.pop(), data) if first_line: # smaps file can be empty for header, data in get_blocks(): hfields = header.split(None, 5) try: addr, perms, offset, dev, inode, path = hfields except ValueError: addr, perms, offset, dev, inode, path = hfields + [''] if not path: path = '[anon]' else: path = path.strip() yield (addr, perms, path, data['Rss:'], data['Size:'], data.get('Pss:', 0), data['Shared_Clean:'], data['Shared_Clean:'], data['Private_Clean:'], data['Private_Dirty:'], data['Referenced:'], data['Anonymous:'], data['Swap:']) f.close() except EnvironmentError: # XXX - Can't use wrap_exceptions decorator as we're # returning a generator; this probably needs some # refactoring in order to avoid this code duplication. if f is not None: f.close() err = sys.exc_info()[1] if err.errno in (errno.ENOENT, errno.ESRCH): raise NoSuchProcess(self.pid, self._process_name) if err.errno in (errno.EPERM, errno.EACCES): raise AccessDenied(self.pid, self._process_name) raise except: if f is not None: f.close() raise
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 IPv4 inet6 IPv6 tcp TCP tcp4 TCP over IPv4 tcp6 TCP over IPv6 udp UDP udp4 UDP over IPv4 udp6 UDP over IPv6 all the sum of all the possible families and protocols """ # Note: in case of UNIX sockets we're only able to determine the # local bound path while the remote endpoint is not retrievable: # http://goo.gl/R3GHM inodes = {} # os.listdir() is gonna raise a lot of access denied # exceptions in case of unprivileged user; that's fine: # lsof does the same so it's unlikely that we can to better. for fd in os.listdir("/proc/%s/fd" % self.pid): try: inode = os.readlink("/proc/%s/fd/%s" % (self.pid, fd)) except OSError: continue if inode.startswith('socket:['): # the process is using a socket inode = inode[8:][:-1] inodes[inode] = fd if not inodes: # no connections for this process return [] def process(file, family, type_): retlist = [] try: f = open(file, 'r') except IOError: # IPv6 not supported on this platform err = sys.exc_info()[1] if err.errno == errno.ENOENT and file.endswith('6'): return [] else: raise try: f.readline() # skip the first line for line in f: # IPv4 / IPv6 if family in (socket.AF_INET, socket.AF_INET6): _, laddr, raddr, status, _, _, _, _, _, inode = \ line.split()[:10] if inode in inodes: laddr = self._decode_address(laddr, family) raddr = self._decode_address(raddr, family) if type_ == socket.SOCK_STREAM: status = _TCP_STATES_TABLE[status] else: status = "" fd = int(inodes[inode]) conn = nt_connection(fd, family, type_, laddr, raddr, status) retlist.append(conn) elif family == socket.AF_UNIX: tokens = line.split() _, _, _, _, type_, _, inode = tokens[0:7] if inode in inodes: if len(tokens) == 8: path = tokens[-1] else: path = "" fd = int(inodes[inode]) type_ = int(type_) conn = nt_connection(fd, family, type_, path, None, "") retlist.append(conn) else: raise ValueError(family) return retlist finally: f.close() tcp4 = ("tcp" , socket.AF_INET , socket.SOCK_STREAM) tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM) udp4 = ("udp" , socket.AF_INET , socket.SOCK_DGRAM) udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM) unix = ("unix", socket.AF_UNIX, None) tmap = { "all" : (tcp4, tcp6, udp4, udp6, unix), "tcp" : (tcp4, tcp6), "tcp4" : (tcp4,), "tcp6" : (tcp6,), "udp" : (udp4, udp6), "udp4" : (udp4,), "udp6" : (udp6,), "unix" : (unix,), "inet" : (tcp4, tcp6, udp4, udp6), "inet4": (tcp4, udp4), "inet6": (tcp6, udp6), } if kind not in tmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in tmap]))) ret = [] for f, family, type_ in tmap[kind]: ret += process("/proc/net/%s" % f, family, type_) # raise NSP if the process disappeared on us os.stat('/proc/%s' % self.pid) return ret
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 little or big endian four-byte hexadecimal number; that is, the least significant byte is listed first, so we need to reverse the order of the bytes to convert it to an IP address. The port is represented as a two-byte hexadecimal number. Reference: http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html """ ip, port = addr.split(':') port = int(port, 16) if PY3: ip = ip.encode('ascii') # this usually refers to a local socket in listen mode with # no end-points connected if not port: return () if family == socket.AF_INET: # see: http://code.google.com/p/psutil/issues/detail?id=201 if sys.byteorder == 'little': ip = socket.inet_ntop(family, base64.b16decode(ip)[::-1]) else: ip = socket.inet_ntop(family, base64.b16decode(ip)) else: # IPv6 # old version - let's keep it, just in case... #ip = ip.decode('hex') #return socket.inet_ntop(socket.AF_INET6, # ''.join(ip[i:i+4][::-1] for i in xrange(0, 16, 4))) ip = base64.b16decode(ip) # see: http://code.google.com/p/psutil/issues/detail?id=201 if sys.byteorder == 'little': ip = socket.inet_ntop(socket.AF_INET6, struct.pack('>4I', *struct.unpack('<4I', ip))) else: ip = socket.inet_ntop(socket.AF_INET6, struct.pack('<4I', *struct.unpack('<4I', ip))) return (ip, port)
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: return "%d-%d" % (start, end)
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` is [1,2,3,4,5,10,11,12,13,14] and `lines` is [1,2,5,10,11,13,14] then the result will be "1-2, 5-11, 13-14". """ pairs = [] i = 0 j = 0 start = None statements = sorted(statements) lines = sorted(lines) while i < len(statements) and j < len(lines): if statements[i] == lines[j]: if start == None: start = lines[j] end = lines[j] j += 1 elif start: pairs.append((start, end)) start = None i += 1 if start: pairs.append((start, end)) ret = ', '.join(map(nice_pair, pairs)) return ret
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])
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(self)) return getattr(self, attr) return _wrapped
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 ""
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
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(to_bytes(str(v))) elif isinstance(v, (tuple, list)): for e in v: self.update(e) elif isinstance(v, dict): keys = v.keys() for k in sorted(keys): self.update(k) self.update(v[k]) else: for k in dir(v): if k.startswith('__'): continue a = getattr(v, k) if inspect.isroutine(a): continue self.update(k) self.update(a)
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: self.log.debug("Adding cluster profile '%s'" % profile) self.profiles[profile] = { 'profile': profile, 'profile_dir': pd, 'status': 'stopped' }
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_launchers(data['profile_dir']) n = n if n is not None else default_n def clean_data(): data.pop('controller_launcher',None) data.pop('engine_set_launcher',None) data.pop('n',None) data['status'] = 'stopped' def engines_stopped(r): self.log.debug('Engines stopped') if cl.running: cl.stop() clean_data() esl.on_stop(engines_stopped) def controller_stopped(r): self.log.debug('Controller stopped') if esl.running: esl.stop() clean_data() cl.on_stop(controller_stopped) dc = ioloop.DelayedCallback(lambda: cl.start(), 0, self.loop) dc.start() dc = ioloop.DelayedCallback(lambda: esl.start(n), 1000*self.delay, self.loop) dc.start() self.log.debug('Cluster started') data['controller_launcher'] = cl data['engine_set_launcher'] = esl data['n'] = n data['status'] = 'running' return self.profile_info(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['controller_launcher'] esl = data['engine_set_launcher'] if cl.running: cl.stop() if esl.running: esl.stop() # Return a temp info dict, the real one is updated in the on_stop # logic above. result = { 'profile': data['profile'], 'profile_dir': data['profile_dir'], 'status': 'stopped' } return result
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] if iface[1]: self.regport = int(iface[1])
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', '.com', '.bat', '.py'] path = None for ext in extensions: try: path = SearchPath(PATH, cmd + ext)[0] except: pass if path is None: raise OSError("command %r not found" % cmd) else: return path
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') print(line, file=sys.stderr) # Wait to finish for returncode return p.wait()
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 return the subprocess status code, as this utility is meant to be used extensively in IPython, where any return value would trigger :func:`sys.displayhook` calls. """ # The controller provides interactivity with both # stdin and stdout #import _process_win32_controller #_process_win32_controller.system(cmd) with AvoidUNCPath() as path: if path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) return process_handler(cmd, _system_body)
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 path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT) if out is None: out = b'' return py3compat.bytes_to_str(out)
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() # put the partitioner into the global namespace: partitioner=p
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)
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)
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)
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_locator) if self.config.include: patterns = prep_patterns(self.config.include) filtered = [] for cu in self.code_units: for pattern in patterns: if fnmatch.fnmatch(cu.filename, pattern): filtered.append(cu) break self.code_units = filtered if self.config.omit: patterns = prep_patterns(self.config.omit) filtered = [] for cu in self.code_units: for pattern in patterns: if fnmatch.fnmatch(cu.filename, pattern): break else: filtered.append(cu) self.code_units = filtered self.code_units.sort()
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 `analysis` is the `Analysis` for the morf. """ self.find_code_units(morfs) if not self.code_units: raise CoverageException("No data to report.") self.directory = directory if self.directory and not os.path.exists(self.directory): os.makedirs(self.directory) for cu in self.code_units: try: report_fn(cu, self.coverage._analyze(cu)) except NoSource: if not self.config.ignore_errors: raise except NotPython: # Only report errors for .py files, and only if we didn't # explicitly suppress those errors. if cu.should_be_python() and not self.config.ignore_errors: raise
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 else: name = func.__name__ newfunc.__dict__ = func.__dict__ newfunc.__doc__ = func.__doc__ newfunc.__module__ = func.__module__ if not hasattr(newfunc, 'compat_co_firstlineno'): newfunc.compat_co_firstlineno = func.func_code.co_firstlineno try: newfunc.__name__ = name except TypeError: # can't set func name in 2.3 newfunc.compat_func_name = name return newfunc return decorate
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 to test many assertions about exceptions in a single test, you may want to use `assert_raises` instead. """ valid = ' or '.join([e.__name__ for e in exceptions]) def decorate(func): name = func.__name__ def newfunc(*arg, **kw): try: func(*arg, **kw) except exceptions: pass except: raise else: message = "%s() did not raise %s" % (name, valid) raise AssertionError(message) newfunc = make_decorator(func)(newfunc) return newfunc return decorate
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().set_trace(sys._getframe().f_back)
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.time() if end - start > limit: raise TimeExpired("Time limit (%s) exceeded" % limit) newfunc = make_decorator(func)(newfunc) return newfunc return decorate
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 subclasses. """ def decorate(func, setup=setup, teardown=teardown): if setup: if hasattr(func, 'setup'): _old_s = func.setup def _s(): setup() _old_s() func.setup = _s else: func.setup = setup if teardown: if hasattr(func, 'teardown'): _old_t = func.teardown def _t(): _old_t() teardown() func.teardown = _t else: func.teardown = teardown return func return decorate
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.log.info("Enabling GUI event loop integration, " "toolkit=%s, pylab=%s" % (gui, self.pylab)) shell.enable_pylab(gui, import_all=self.pylab_import_all) else: self.log.info("Enabling GUI event loop integration, " "toolkit=%s" % self.gui) shell.enable_gui(self.gui) except Exception: self.log.warn("GUI event loop or pylab initialization failed") self.shell.showtraceback()
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...") extensions = self.default_extensions + self.extensions for ext in extensions: try: self.log.info("Loading IPython extension: %s" % ext) self.shell.extension_manager.load_extension(ext) except: self.log.warn("Error in loading extension: %s" % ext + "\nCheck your config files in %s" % self.profile_dir.location ) self.shell.showtraceback() except: self.log.warn("Unknown error in loading extensions:") self.shell.showtraceback()
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 sys.stdout.flush() sys.stderr.flush() # Hide variables defined here from %who etc. self.shell.user_ns_hidden.update(self.shell.user_ns)
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: self.log.info("Running code in user namespace: %s" % line) self.shell.run_cell(line, store_history=False) except: self.log.warn("Error in executing line in user " "namespace: %s" % line) self.shell.showtraceback() except: self.log.warn("Unknown error in handling IPythonApp.exec_lines:") self.shell.showtraceback()
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: return self.log.debug("Running startup files from %s...", startup_dir) try: for fname in sorted(startup_files): self._exec_file(fname) except: self.log.warn("Unknown error in handling startup files:") self.shell.showtraceback()
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: self.log.warn("Unknown error in handling IPythonApp.exec_files:") self.shell.showtraceback()
def _run_cmd_line_code(self): """Run code or file specified at the command-line""" if self.code_to_run: line = self.code_to_run try: self.log.info("Running code given at command line (c=): %s" % line) self.shell.run_cell(line, store_history=False) except: self.log.warn("Error in executing line in user namespace: %s" % line) self.shell.showtraceback() # Like Python itself, ignore the second if the first of these is present elif self.file_to_run: fname = self.file_to_run try: self._exec_file(fname) except: self.log.warn("Error in executing file in user namespace: %s" % fname) self.shell.showtraceback()
def _run_module(self): """Run module specified at the command-line.""" if self.module_to_run: # Make sure that the module gets a proper sys.argv as if it were # run using `python -m`. save_argv = sys.argv sys.argv = [sys.executable] + self.extra_args try: self.shell.safe_run_module(self.module_to_run, self.shell.user_ns) finally: sys.argv = save_argv
def generic(func): """Create a simple generic function""" _sentinel = object() def _by_class(*args, **kw): cls = args[0].__class__ for t in type(cls.__name__, (cls,object), {}).__mro__: f = _gbt(t, _sentinel) if f is not _sentinel: return f(*args, **kw) else: return func(*args, **kw) _by_type = {object: func} try: _by_type[InstanceType] = _by_class except NameError: # Python 3 pass _gbt = _by_type.get def when_type(*types): """Decorator to add a method that will be called for the given types""" for t in types: if not isinstance(t, classtypes): raise TypeError( "%r is not a type or class" % (t,) ) def decorate(f): for t in types: if _by_type.setdefault(t,f) is not f: raise TypeError( "%r already has method for type %r" % (func, t) ) return f return decorate _by_object = {} _gbo = _by_object.get def when_object(*obs): """Decorator to add a method to be called for the given object(s)""" def decorate(f): for o in obs: if _by_object.setdefault(id(o), (o,f))[1] is not f: raise TypeError( "%r already has method for object %r" % (func, o) ) return f return decorate def dispatch(*args, **kw): f = _gbo(id(args[0]), _sentinel) if f is _sentinel: for t in type(args[0]).__mro__: f = _gbt(t, _sentinel) if f is not _sentinel: return f(*args, **kw) else: return func(*args, **kw) else: return f[1](*args, **kw) dispatch.__name__ = func.__name__ dispatch.__dict__ = func.__dict__.copy() dispatch.__doc__ = func.__doc__ dispatch.__module__ = func.__module__ dispatch.when_type = when_type dispatch.when_object = when_object dispatch.default = func dispatch.has_object = lambda o: id(o) in _by_object dispatch.has_type = lambda t: t in _by_type return dispatch
def data_filename(fname, pkgdir=""): """Return the path to a data file of ours. The file is searched for on `STATIC_PATH`, and the first place it's found, is returned. Each directory in `STATIC_PATH` is searched as-is, and also, if `pkgdir` is provided, at that subdirectory. """ for static_dir in STATIC_PATH: static_filename = os.path.join(static_dir, fname) if os.path.exists(static_filename): return static_filename if pkgdir: static_filename = os.path.join(static_dir, pkgdir, fname) if os.path.exists(static_filename): return static_filename raise CoverageException("Couldn't find static file %r" % fname)
def data(fname): """Return the contents of a data file of ours.""" data_file = open(data_filename(fname)) try: return data_file.read() finally: data_file.close()
def escape(t): """HTML-escape the text in `t`.""" return (t # Convert HTML special chars into HTML entities. .replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") .replace("'", "&#39;").replace('"', "&quot;") # Convert runs of spaces: "......" -> "&nbsp;.&nbsp;.&nbsp;." .replace(" ", "&nbsp; ") # To deal with odd-length runs, convert the final pair of spaces # so that "....." -> "&nbsp;.&nbsp;&nbsp;." .replace(" ", "&nbsp; ") )
def report(self, morfs): """Generate an HTML report for `morfs`. `morfs` is a list of modules or filenames. """ assert self.config.html_dir, "must give a directory for html reporting" # Read the status data. self.status.read(self.config.html_dir) # Check that this run used the same settings as the last run. m = Hasher() m.update(self.config) these_settings = m.digest() if self.status.settings_hash() != these_settings: self.status.reset() self.status.set_settings_hash(these_settings) # The user may have extra CSS they want copied. if self.config.extra_css: self.extra_css = os.path.basename(self.config.extra_css) # Process all the files. self.report_files(self.html_file, morfs, self.config.html_dir) if not self.files: raise CoverageException("No data to report.") # Write the index file. self.index_file() self.make_local_static_report_files() return self.totals.pc_covered
def make_local_static_report_files(self): """Make local instances of static files for HTML report.""" # The files we provide must always be copied. for static, pkgdir in self.STATIC_FILES: shutil.copyfile( data_filename(static, pkgdir), os.path.join(self.directory, static) ) # The user may have extra CSS they want copied. if self.extra_css: shutil.copyfile( self.config.extra_css, os.path.join(self.directory, self.extra_css) )
def write_html(self, fname, html): """Write `html` to `fname`, properly encoded.""" fout = open(fname, "wb") try: fout.write(html.encode('ascii', 'xmlcharrefreplace')) finally: fout.close()
def file_hash(self, source, cu): """Compute a hash that changes if the file needs to be re-reported.""" m = Hasher() m.update(source) self.coverage.data.add_to_hash(cu.filename, m) return m.digest()
def html_file(self, cu, analysis): """Generate an HTML file for one source file.""" source_file = cu.source_file() try: source = source_file.read() finally: source_file.close() # Find out if the file on disk is already correct. flat_rootname = cu.flat_rootname() this_hash = self.file_hash(source, cu) that_hash = self.status.file_hash(flat_rootname) if this_hash == that_hash: # Nothing has changed to require the file to be reported again. self.files.append(self.status.index_info(flat_rootname)) return self.status.set_file_hash(flat_rootname, this_hash) # If need be, determine the encoding of the source file. We use it # later to properly write the HTML. if sys.version_info < (3, 0): encoding = source_encoding(source) # Some UTF8 files have the dreaded UTF8 BOM. If so, junk it. if encoding.startswith("utf-8") and source[:3] == "\xef\xbb\xbf": source = source[3:] encoding = "utf-8" # Get the numbers for this file. nums = analysis.numbers if self.arcs: missing_branch_arcs = analysis.missing_branch_arcs() # These classes determine which lines are highlighted by default. c_run = "run hide_run" c_exc = "exc" c_mis = "mis" c_par = "par " + c_run lines = [] for lineno, line in enumerate(source_token_lines(source)): lineno += 1 # 1-based line numbers. # Figure out how to mark this line. line_class = [] annotate_html = "" annotate_title = "" if lineno in analysis.statements: line_class.append("stm") if lineno in analysis.excluded: line_class.append(c_exc) elif lineno in analysis.missing: line_class.append(c_mis) elif self.arcs and lineno in missing_branch_arcs: line_class.append(c_par) annlines = [] for b in missing_branch_arcs[lineno]: if b < 0: annlines.append("exit") else: annlines.append(str(b)) annotate_html = "&nbsp;&nbsp; ".join(annlines) if len(annlines) > 1: annotate_title = "no jumps to these line numbers" elif len(annlines) == 1: annotate_title = "no jump to this line number" elif lineno in analysis.statements: line_class.append(c_run) # Build the HTML for the line html = [] for tok_type, tok_text in line: if tok_type == "ws": html.append(escape(tok_text)) else: tok_html = escape(tok_text) or '&nbsp;' html.append( "<span class='%s'>%s</span>" % (tok_type, tok_html) ) lines.append({ 'html': ''.join(html), 'number': lineno, 'class': ' '.join(line_class) or "pln", 'annotate': annotate_html, 'annotate_title': annotate_title, }) # Write the HTML page for this file. html = spaceless(self.source_tmpl.render({ 'c_exc': c_exc, 'c_mis': c_mis, 'c_par': c_par, 'c_run': c_run, 'arcs': self.arcs, 'extra_css': self.extra_css, 'cu': cu, 'nums': nums, 'lines': lines, })) if sys.version_info < (3, 0): html = html.decode(encoding) html_filename = flat_rootname + ".html" html_path = os.path.join(self.directory, html_filename) self.write_html(html_path, html) # Save this file's information for the index file. index_info = { 'nums': nums, 'html_filename': html_filename, 'name': cu.name, } self.files.append(index_info) self.status.set_index_info(flat_rootname, index_info)
def index_file(self): """Write the index.html file for this report.""" index_tmpl = Templite( data("index.html"), self.template_globals ) self.totals = sum([f['nums'] for f in self.files]) html = index_tmpl.render({ 'arcs': self.arcs, 'extra_css': self.extra_css, 'files': self.files, 'totals': self.totals, }) if sys.version_info < (3, 0): html = html.decode("utf-8") self.write_html( os.path.join(self.directory, "index.html"), html ) # Write the latest hashes for next time. self.status.write(self.directory)
def read(self, directory): """Read the last status in `directory`.""" usable = False try: status_file = os.path.join(directory, self.STATUS_FILE) fstatus = open(status_file, "rb") try: status = pickle.load(fstatus) finally: fstatus.close() except (IOError, ValueError): usable = False else: usable = True if status['format'] != self.STATUS_FORMAT: usable = False elif status['version'] != coverage.__version__: usable = False if usable: self.files = status['files'] self.settings = status['settings'] else: self.reset()
def write(self, directory): """Write the current status to `directory`.""" status_file = os.path.join(directory, self.STATUS_FILE) status = { 'format': self.STATUS_FORMAT, 'version': coverage.__version__, 'settings': self.settings, 'files': self.files, } fout = open(status_file, "wb") try: pickle.dump(status, fout) finally: fout.close()
def uniq_stable(elems): """uniq_stable(elems) -> list Return from an iterable, a list of all the unique elements in the input, but maintaining the order in which they first appear. A naive solution to this problem which just makes a dictionary with the elements as keys fails to respect the stability condition, since dictionaries are unsorted by nature. Note: All elements in the input must be valid dictionary keys for this routine to work, as it internally uses a dictionary for efficiency reasons.""" unique = [] unique_dict = {} for nn in elems: if nn not in unique_dict: unique.append(nn) unique_dict[nn] = None return unique
def sort_compare(lst1, lst2, inplace=1): """Sort and compare two lists. By default it does it in place, thus modifying the lists. Use inplace = 0 to avoid that (at the cost of temporary copy creation).""" if not inplace: lst1 = lst1[:] lst2 = lst2[:] lst1.sort(); lst2.sort() return lst1 == lst2
def list2dict(lst): """Takes a list of (key,value) pairs and turns it into a dict.""" dic = {} for k,v in lst: dic[k] = v return dic
def list2dict2(lst, default=''): """Takes a list and turns it into a dict. Much slower than list2dict, but more versatile. This version can take lists with sublists of arbitrary length (including sclars).""" dic = {} for elem in lst: if type(elem) in (types.ListType,types.TupleType): size = len(elem) if size == 0: pass elif size == 1: dic[elem] = default else: k,v = elem[0], elem[1:] if len(v) == 1: v = v[0] dic[k] = v else: dic[elem] = default return dic
def get_slice(seq, start=0, stop=None, step=1): """Get a slice of a sequence with variable step. Specify start,stop,step.""" if stop == None: stop = len(seq) item = lambda i: seq[i] return map(item,xrange(start,stop,step))
def chop(seq, size): """Chop a sequence into chunks of the given size.""" chunk = lambda i: seq[i:i+size] return map(chunk,xrange(0,len(seq),size))
def read_config(): """Read configuration from setup.cfg.""" # XXX modifies global state, which is kind of evil config = ConfigParser.ConfigParser() config.read(['setup.cfg']) if not config.has_section('check-manifest'): return if (config.has_option('check-manifest', 'ignore-default-rules') and config.getboolean('check-manifest', 'ignore-default-rules')): del IGNORE[:] if config.has_option('check-manifest', 'ignore'): patterns = [p.strip() for p in config.get('check-manifest', 'ignore').splitlines()] IGNORE.extend(p for p in patterns if p)
def read_manifest(): """Read existing configuration from MANIFEST.in. We use that to ignore anything the MANIFEST.in ignores. """ # XXX modifies global state, which is kind of evil if not os.path.isfile('MANIFEST.in'): return with open('MANIFEST.in') as manifest: contents = manifest.read() ignore, ignore_regexps = _get_ignore_from_manifest(contents) IGNORE.extend(ignore) IGNORE_REGEXPS.extend(ignore_regexps)