Search is not available for this dataset
text stringlengths 75 104k |
|---|
def write_format_data(self, format_dict):
"""Write the format data dict to the frontend.
This default version of this method simply writes the plain text
representation of the object to ``io.stdout``. Subclasses should
override this method to send the entire `format_dict` to the
frontends.
Parameters
----------
format_dict : dict
The format dict for the object passed to `sys.displayhook`.
"""
# We want to print because we want to always make sure we have a
# newline, even if all the prompt separators are ''. This is the
# standard IPython behavior.
result_repr = format_dict['text/plain']
if '\n' in result_repr:
# So that multi-line strings line up with the left column of
# the screen, instead of having the output prompt mess up
# their first line.
# We use the prompt template instead of the expanded prompt
# because the expansion may add ANSI escapes that will interfere
# with our ability to determine whether or not we should add
# a newline.
prompt_template = self.shell.prompt_manager.out_template
if prompt_template and not prompt_template.endswith('\n'):
# But avoid extraneous empty lines.
result_repr = '\n' + result_repr
print >>io.stdout, result_repr |
def update_user_ns(self, result):
"""Update user_ns with various things like _, __, _1, etc."""
# Avoid recursive reference when displaying _oh/Out
if result is not self.shell.user_ns['_oh']:
if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
warn('Output cache limit (currently '+
`self.cache_size`+' entries) hit.\n'
'Flushing cache and resetting history counter...\n'
'The only history variables available will be _,__,___ and _1\n'
'with the current result.')
self.flush()
# Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
# we cause buggy behavior for things like gettext).
if '_' not in __builtin__.__dict__:
self.___ = self.__
self.__ = self._
self._ = result
self.shell.push({'_':self._,
'__':self.__,
'___':self.___}, interactive=False)
# hackish access to top-level namespace to create _1,_2... dynamically
to_main = {}
if self.do_full_cache:
new_result = '_'+`self.prompt_count`
to_main[new_result] = result
self.shell.push(to_main, interactive=False)
self.shell.user_ns['_oh'][self.prompt_count] = result |
def log_output(self, format_dict):
"""Log the output."""
if self.shell.logger.log_output:
self.shell.logger.log_write(format_dict['text/plain'], 'output')
self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
format_dict['text/plain'] |
def finish_displayhook(self):
"""Finish up all displayhook activities."""
io.stdout.write(self.shell.separate_out2)
io.stdout.flush() |
def load_ipython_extension(ip):
"""Load the extension in IPython."""
global _loaded
if not _loaded:
plugin = StoreMagic(shell=ip, config=ip.config)
ip.plugin_manager.register_plugin('storemagic', plugin)
_loaded = True |
def raise_if_freezed(self):
'''raise `InvalidOperationException` if is freezed.'''
if self.is_freezed:
name = type(self).__name__
raise InvalidOperationException('obj {name} is freezed.'.format(name=name)) |
def mysql_timestamp_converter(s):
"""Convert a MySQL TIMESTAMP to a Timestamp object."""
# MySQL>4.1 returns TIMESTAMP in the same format as DATETIME
if s[4] == '-': return DateTime_or_None(s)
s = s + "0"*(14-len(s)) # padding
parts = map(int, filter(None, (s[:4],s[4:6],s[6:8],
s[8:10],s[10:12],s[12:14])))
try:
return Timestamp(*parts)
except (SystemExit, KeyboardInterrupt):
raise
except:
return None |
def make_envelope(self, body_elements=None):
"""
body_elements: <list> of etree.Elements or <None>
"""
soap = self.get_soap_el_factory()
body_elements = body_elements or []
body = soap.Body(*body_elements)
header = self.get_soap_header()
if header is not None:
elements = [header, body]
else:
elements = [body]
return soap.Envelope(
#{
# '{%s}encodingStyle' % namespaces.SOAP_1_2: (
# 'http://www.w3.org/2001/12/soap-encoding')
#},
*elements
) |
def embed_kernel(module=None, local_ns=None, **kwargs):
"""Embed and start an IPython kernel in a given scope.
Parameters
----------
module : ModuleType, optional
The module to load into IPython globals (default: caller)
local_ns : dict, optional
The namespace to load into IPython user namespace (default: caller)
kwargs : various, optional
Further keyword args are relayed to the KernelApp constructor,
allowing configuration of the Kernel. Will only have an effect
on the first embed_kernel call for a given process.
"""
# get the app if it exists, or set it up if it doesn't
if IPKernelApp.initialized():
app = IPKernelApp.instance()
else:
app = IPKernelApp.instance(**kwargs)
app.initialize([])
# Undo unnecessary sys module mangling from init_sys_modules.
# This would not be necessary if we could prevent it
# in the first place by using a different InteractiveShell
# subclass, as in the regular embed case.
main = app.kernel.shell._orig_sys_modules_main_mod
if main is not None:
sys.modules[app.kernel.shell._orig_sys_modules_main_name] = main
# load the calling scope if not given
(caller_module, caller_locals) = extract_module_locals(1)
if module is None:
module = caller_module
if local_ns is None:
local_ns = caller_locals
app.kernel.user_module = module
app.kernel.user_ns = local_ns
app.shell.set_completer_frame()
app.start() |
def _eventloop_changed(self, name, old, new):
"""schedule call to eventloop from IOLoop"""
loop = ioloop.IOLoop.instance()
loop.add_timeout(time.time()+0.1, self.enter_eventloop) |
def dispatch_control(self, msg):
"""dispatch control requests"""
idents,msg = self.session.feed_identities(msg, copy=False)
try:
msg = self.session.unserialize(msg, content=True, copy=False)
except:
self.log.error("Invalid Control Message", exc_info=True)
return
self.log.debug("Control received: %s", msg)
header = msg['header']
msg_id = header['msg_id']
msg_type = header['msg_type']
handler = self.control_handlers.get(msg_type, None)
if handler is None:
self.log.error("UNKNOWN CONTROL MESSAGE TYPE: %r", msg_type)
else:
try:
handler(self.control_stream, idents, msg)
except Exception:
self.log.error("Exception in control handler:", exc_info=True) |
def dispatch_shell(self, stream, msg):
"""dispatch shell requests"""
# flush control requests first
if self.control_stream:
self.control_stream.flush()
idents,msg = self.session.feed_identities(msg, copy=False)
try:
msg = self.session.unserialize(msg, content=True, copy=False)
except:
self.log.error("Invalid Message", exc_info=True)
return
header = msg['header']
msg_id = header['msg_id']
msg_type = msg['header']['msg_type']
# Print some info about this message and leave a '--->' marker, so it's
# easier to trace visually the message chain when debugging. Each
# handler prints its message at the end.
self.log.debug('\n*** MESSAGE TYPE:%s***', msg_type)
self.log.debug(' Content: %s\n --->\n ', msg['content'])
if msg_id in self.aborted:
self.aborted.remove(msg_id)
# is it safe to assume a msg_id will not be resubmitted?
reply_type = msg_type.split('_')[0] + '_reply'
status = {'status' : 'aborted'}
sub = {'engine' : self.ident}
sub.update(status)
reply_msg = self.session.send(stream, reply_type, subheader=sub,
content=status, parent=msg, ident=idents)
return
handler = self.shell_handlers.get(msg_type, None)
if handler is None:
self.log.error("UNKNOWN MESSAGE TYPE: %r", msg_type)
else:
# ensure default_int_handler during handler call
sig = signal(SIGINT, default_int_handler)
try:
handler(stream, idents, msg)
except Exception:
self.log.error("Exception in message handler:", exc_info=True)
finally:
signal(SIGINT, sig) |
def enter_eventloop(self):
"""enter eventloop"""
self.log.info("entering eventloop")
# restore default_int_handler
signal(SIGINT, default_int_handler)
while self.eventloop is not None:
try:
self.eventloop(self)
except KeyboardInterrupt:
# Ctrl-C shouldn't crash the kernel
self.log.error("KeyboardInterrupt caught in kernel")
continue
else:
# eventloop exited cleanly, this means we should stop (right?)
self.eventloop = None
break
self.log.info("exiting eventloop")
# if eventloop exits, IOLoop should stop
ioloop.IOLoop.instance().stop() |
def start(self):
"""register dispatchers for streams"""
self.shell.exit_now = False
if self.control_stream:
self.control_stream.on_recv(self.dispatch_control, copy=False)
def make_dispatcher(stream):
def dispatcher(msg):
return self.dispatch_shell(stream, msg)
return dispatcher
for s in self.shell_streams:
s.on_recv(make_dispatcher(s), copy=False) |
def do_one_iteration(self):
"""step eventloop just once"""
if self.control_stream:
self.control_stream.flush()
for stream in self.shell_streams:
# handle at most one request per iteration
stream.flush(zmq.POLLIN, 1)
stream.flush(zmq.POLLOUT) |
def _publish_pyin(self, code, parent, execution_count):
"""Publish the code request on the pyin stream."""
self.session.send(self.iopub_socket, u'pyin',
{u'code':code, u'execution_count': execution_count},
parent=parent, ident=self._topic('pyin')
) |
def _publish_status(self, status, parent=None):
"""send status (busy/idle) on IOPub"""
self.session.send(self.iopub_socket,
u'status',
{u'execution_state': status},
parent=parent,
ident=self._topic('status'),
) |
def execute_request(self, stream, ident, parent):
"""handle an execute_request"""
self._publish_status(u'busy', parent)
try:
content = parent[u'content']
code = content[u'code']
silent = content[u'silent']
except:
self.log.error("Got bad msg: ")
self.log.error("%s", parent)
return
sub = self._make_subheader()
shell = self.shell # we'll need this a lot here
# Replace raw_input. Note that is not sufficient to replace
# raw_input in the user namespace.
if content.get('allow_stdin', False):
raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
else:
raw_input = lambda prompt='' : self._no_raw_input()
if py3compat.PY3:
__builtin__.input = raw_input
else:
__builtin__.raw_input = raw_input
# Set the parent message of the display hook and out streams.
shell.displayhook.set_parent(parent)
shell.display_pub.set_parent(parent)
sys.stdout.set_parent(parent)
sys.stderr.set_parent(parent)
# Re-broadcast our input for the benefit of listening clients, and
# start computing output
if not silent:
self._publish_pyin(code, parent, shell.execution_count)
reply_content = {}
try:
# FIXME: the shell calls the exception handler itself.
shell.run_cell(code, store_history=not silent, silent=silent)
except:
status = u'error'
# FIXME: this code right now isn't being used yet by default,
# because the run_cell() call above directly fires off exception
# reporting. This code, therefore, is only active in the scenario
# where runlines itself has an unhandled exception. We need to
# uniformize this, for all exception construction to come from a
# single location in the codbase.
etype, evalue, tb = sys.exc_info()
tb_list = traceback.format_exception(etype, evalue, tb)
reply_content.update(shell._showtraceback(etype, evalue, tb_list))
else:
status = u'ok'
reply_content[u'status'] = status
# Return the execution counter so clients can display prompts
reply_content['execution_count'] = shell.execution_count - 1
# FIXME - fish exception info out of shell, possibly left there by
# runlines. We'll need to clean up this logic later.
if shell._reply_content is not None:
reply_content.update(shell._reply_content)
e_info = dict(engine_uuid=self.ident, engine_id=self.int_id, method='execute')
reply_content['engine_info'] = e_info
# reset after use
shell._reply_content = None
# At this point, we can tell whether the main code execution succeeded
# or not. If it did, we proceed to evaluate user_variables/expressions
if reply_content['status'] == 'ok':
reply_content[u'user_variables'] = \
shell.user_variables(content.get(u'user_variables', []))
reply_content[u'user_expressions'] = \
shell.user_expressions(content.get(u'user_expressions', {}))
else:
# If there was an error, don't even try to compute variables or
# expressions
reply_content[u'user_variables'] = {}
reply_content[u'user_expressions'] = {}
# Payloads should be retrieved regardless of outcome, so we can both
# recover partial output (that could have been generated early in a
# block, before an error) and clear the payload system always.
reply_content[u'payload'] = shell.payload_manager.read_payload()
# Be agressive about clearing the payload because we don't want
# it to sit in memory until the next execute_request comes in.
shell.payload_manager.clear_payload()
# Flush output before sending the reply.
sys.stdout.flush()
sys.stderr.flush()
# FIXME: on rare occasions, the flush doesn't seem to make it to the
# clients... This seems to mitigate the problem, but we definitely need
# to better understand what's going on.
if self._execute_sleep:
time.sleep(self._execute_sleep)
# Send the reply.
reply_content = json_clean(reply_content)
sub['status'] = reply_content['status']
if reply_content['status'] == 'error' and \
reply_content['ename'] == 'UnmetDependency':
sub['dependencies_met'] = False
reply_msg = self.session.send(stream, u'execute_reply',
reply_content, parent, subheader=sub,
ident=ident)
self.log.debug("%s", reply_msg)
if not silent and reply_msg['content']['status'] == u'error':
self._abort_queues()
self._publish_status(u'idle', parent) |
def abort_request(self, stream, ident, parent):
"""abort a specifig msg by id"""
msg_ids = parent['content'].get('msg_ids', None)
if isinstance(msg_ids, basestring):
msg_ids = [msg_ids]
if not msg_ids:
self.abort_queues()
for mid in msg_ids:
self.aborted.add(str(mid))
content = dict(status='ok')
reply_msg = self.session.send(stream, 'abort_reply', content=content,
parent=parent, ident=ident)
self.log.debug("%s", reply_msg) |
def clear_request(self, stream, idents, parent):
"""Clear our namespace."""
self.shell.reset(False)
msg = self.session.send(stream, 'clear_reply', ident=idents, parent=parent,
content = dict(status='ok')) |
def _topic(self, topic):
"""prefixed topic for IOPub messages"""
if self.int_id >= 0:
base = "engine.%i" % self.int_id
else:
base = "kernel.%s" % self.ident
return py3compat.cast_bytes("%s.%s" % (base, topic)) |
def _at_shutdown(self):
"""Actions taken at shutdown by the kernel, called by python's atexit.
"""
# io.rprint("Kernel at_shutdown") # dbg
if self._shutdown_message is not None:
self.session.send(self.iopub_socket, self._shutdown_message, ident=self._topic('shutdown'))
self.log.debug("%s", self._shutdown_message)
[ s.flush(zmq.POLLOUT) for s in self.shell_streams ] |
def init_gui_pylab(self):
"""Enable GUI event loop integration, taking pylab into account."""
# Provide a wrapper for :meth:`InteractiveShellApp.init_gui_pylab`
# to ensure that any exception is printed straight to stderr.
# Normally _showtraceback associates the reply with an execution,
# which means frontends will never draw it, as this exception
# is not associated with any execute request.
shell = self.shell
_showtraceback = shell._showtraceback
try:
# replace pyerr-sending traceback with stderr
def print_tb(etype, evalue, stb):
print ("GUI event loop or pylab initialization failed",
file=io.stderr)
print (shell.InteractiveTB.stb2text(stb), file=io.stderr)
shell._showtraceback = print_tb
InteractiveShellApp.init_gui_pylab(self)
finally:
shell._showtraceback = _showtraceback |
def slices(self, size, n=3):
'''
Create equal sized slices of the file. The last slice may be larger than
the others.
args:
* size (int): The full size to be sliced.
* n (int): The number of slices to return.
returns:
A list of `FileSlice` objects of length (n).
'''
if n <= 0:
raise ValueError('n must be greater than 0')
if size < n:
raise ValueError('size argument cannot be less than n argument')
slice_size = size // n
last_slice_size = size - (n-1) * slice_size
t = [self(c, slice_size) for c in range(0, (n-1)*slice_size, slice_size)]
t.append(self((n-1)*slice_size, last_slice_size))
return t |
def seek(self, offset, whence=0):
'''
Same as `file.seek()` but for the slice. Returns a value between
`self.start` and `self.size` inclusive.
raises:
ValueError if the new seek position is not between 0 and
`self.size`.
'''
if self.closed:
raise ValueError('I/O operation on closed file.')
if whence == SEEK_SET:
pos = offset
elif whence == SEEK_CUR:
pos = self.pos + offset
elif whence == SEEK_END:
pos = self.size + offset
if not 0 <= pos <= self.size:
raise ValueError('new position ({}) will fall outside the file slice range (0-{})'.format(pos, self.size))
self.pos = pos
return self.pos |
def read(self, size=-1):
'''
Same as `file.read()` but for the slice. Does not read beyond
`self.end`.
'''
if self.closed:
raise ValueError('I/O operation on closed file.')
if size == -1 or size > self.size - self.pos:
size = self.size - self.pos
with self.lock:
self.f.seek(self.start + self.pos)
result = self.f.read(size)
self.seek(self.pos + size)
return result |
def write(self, b):
'''
Same as `file.write()` but for the slice.
raises:
EOFError if the new seek position is > `self.size`.
'''
if self.closed:
raise ValueError('I/O operation on closed file.')
if self.pos + len(b) > self.size:
raise EOFError('new position ({}) will fall outside the file slice range (0-{})'.format(self.pos + len(b), self.size))
with self.lock:
self.f.seek(self.start + self.pos)
result = self.f.write(b)
self.seek(self.pos + len(b))
return result |
def writelines(self, lines):
'''
Same as `file.writelines()` but for the slice.
raises:
EOFError if the new seek position is > `self.size`.
'''
lines = b''.join(lines)
self.write(lines) |
def configure(self, options, conf):
"""Configure plugin.
"""
Plugin.configure(self, options, conf)
self._mod_stack = [] |
def beforeContext(self):
"""Copy sys.modules onto my mod stack
"""
mods = sys.modules.copy()
self._mod_stack.append(mods) |
def afterContext(self):
"""Pop my mod stack and restore sys.modules to the state
it was in when mod stack was pushed.
"""
mods = self._mod_stack.pop()
to_del = [ m for m in sys.modules.keys() if m not in mods ]
if to_del:
log.debug('removing sys modules entries: %s', to_del)
for mod in to_del:
del sys.modules[mod]
sys.modules.update(mods) |
def absdir(path):
"""Return absolute, normalized path to directory, if it exists; None
otherwise.
"""
if not os.path.isabs(path):
path = os.path.normpath(os.path.abspath(os.path.join(os.getcwd(),
path)))
if path is None or not os.path.isdir(path):
return None
return path |
def absfile(path, where=None):
"""Return absolute, normalized path to file (optionally in directory
where), or None if the file can't be found either in where or the current
working directory.
"""
orig = path
if where is None:
where = os.getcwd()
if isinstance(where, list) or isinstance(where, tuple):
for maybe_path in where:
maybe_abs = absfile(path, maybe_path)
if maybe_abs is not None:
return maybe_abs
return None
if not os.path.isabs(path):
path = os.path.normpath(os.path.abspath(os.path.join(where, path)))
if path is None or not os.path.exists(path):
if where != os.getcwd():
# try the cwd instead
path = os.path.normpath(os.path.abspath(os.path.join(os.getcwd(),
orig)))
if path is None or not os.path.exists(path):
return None
if os.path.isdir(path):
# might want an __init__.py from pacakge
init = os.path.join(path,'__init__.py')
if os.path.isfile(init):
return init
elif os.path.isfile(path):
return path
return None |
def file_like(name):
"""A name is file-like if it is a path that exists, or it has a
directory part, or it ends in .py, or it isn't a legal python
identifier.
"""
return (os.path.exists(name)
or os.path.dirname(name)
or name.endswith('.py')
or not ident_re.match(os.path.splitext(name)[0])) |
def isclass(obj):
"""Is obj a class? Inspect's isclass is too liberal and returns True
for objects that can't be subclasses of anything.
"""
obj_type = type(obj)
return obj_type in class_types or issubclass(obj_type, type) |
def ispackage(path):
"""
Is this path a package directory?
>>> ispackage('nose')
True
>>> ispackage('unit_tests')
False
>>> ispackage('nose/plugins')
True
>>> ispackage('nose/loader.py')
False
"""
if os.path.isdir(path):
# at least the end of the path must be a legal python identifier
# and __init__.py[co] must exist
end = os.path.basename(path)
if ident_re.match(end):
for init in ('__init__.py', '__init__.pyc', '__init__.pyo'):
if os.path.isfile(os.path.join(path, init)):
return True
if sys.platform.startswith('java') and \
os.path.isfile(os.path.join(path, '__init__$py.class')):
return True
return False |
def getfilename(package, relativeTo=None):
"""Find the python source file for a package, relative to a
particular directory (defaults to current working directory if not
given).
"""
if relativeTo is None:
relativeTo = os.getcwd()
path = os.path.join(relativeTo, os.sep.join(package.split('.')))
suffixes = ('/__init__.py', '.py')
for suffix in suffixes:
filename = path + suffix
if os.path.exists(filename):
return filename
return None |
def getpackage(filename):
"""
Find the full dotted package name for a given python source file
name. Returns None if the file is not a python source file.
>>> getpackage('foo.py')
'foo'
>>> getpackage('biff/baf.py')
'baf'
>>> getpackage('nose/util.py')
'nose.util'
Works for directories too.
>>> getpackage('nose')
'nose'
>>> getpackage('nose/plugins')
'nose.plugins'
And __init__ files stuck onto directories
>>> getpackage('nose/plugins/__init__.py')
'nose.plugins'
Absolute paths also work.
>>> path = os.path.abspath(os.path.join('nose', 'plugins'))
>>> getpackage(path)
'nose.plugins'
"""
src_file = src(filename)
if not src_file.endswith('.py') and not ispackage(src_file):
return None
base, ext = os.path.splitext(os.path.basename(src_file))
if base == '__init__':
mod_parts = []
else:
mod_parts = [base]
path, part = os.path.split(os.path.split(src_file)[0])
while part:
if ispackage(os.path.join(path, part)):
mod_parts.append(part)
else:
break
path, part = os.path.split(path)
mod_parts.reverse()
return '.'.join(mod_parts) |
def ln(label):
"""Draw a 70-char-wide divider, with label in the middle.
>>> ln('hello there')
'---------------------------- hello there -----------------------------'
"""
label_len = len(label) + 2
chunk = (70 - label_len) // 2
out = '%s %s %s' % ('-' * chunk, label, '-' * chunk)
pad = 70 - len(out)
if pad > 0:
out = out + ('-' * pad)
return out |
def try_run(obj, names):
"""Given a list of possible method names, try to run them with the
provided object. Keep going until something works. Used to run
setup/teardown methods for module, package, and function tests.
"""
for name in names:
func = getattr(obj, name, None)
if func is not None:
if type(obj) == types.ModuleType:
# py.test compatibility
try:
args, varargs, varkw, defaults = inspect.getargspec(func)
except TypeError:
# Not a function. If it's callable, call it anyway
if hasattr(func, '__call__'):
func = func.__call__
try:
args, varargs, varkw, defaults = \
inspect.getargspec(func)
args.pop(0) # pop the self off
except TypeError:
raise TypeError("Attribute %s of %r is not a python "
"function. Only functions or callables"
" may be used as fixtures." %
(name, obj))
if len(args):
log.debug("call fixture %s.%s(%s)", obj, name, obj)
return func(obj)
log.debug("call fixture %s.%s", obj, name)
return func() |
def src(filename):
"""Find the python source file for a .pyc, .pyo or $py.class file on
jython. Returns the filename provided if it is not a python source
file.
"""
if filename is None:
return filename
if sys.platform.startswith('java') and filename.endswith('$py.class'):
return '.'.join((filename[:-9], 'py'))
base, ext = os.path.splitext(filename)
if ext in ('.pyc', '.pyo', '.py'):
return '.'.join((base, 'py'))
return filename |
def regex_last_key(regex):
"""Sort key function factory that puts items that match a
regular expression last.
>>> from nose.config import Config
>>> from nose.pyversion import sort_list
>>> c = Config()
>>> regex = c.testMatch
>>> entries = ['.', '..', 'a_test', 'src', 'lib', 'test', 'foo.py']
>>> sort_list(entries, regex_last_key(regex))
>>> entries
['.', '..', 'foo.py', 'lib', 'src', 'a_test', 'test']
"""
def k(obj):
if regex.search(obj):
return (1, obj)
return (0, obj)
return k |
def tolist(val):
"""Convert a value that may be a list or a (possibly comma-separated)
string into a list. The exception: None is returned as None, not [None].
>>> tolist(["one", "two"])
['one', 'two']
>>> tolist("hello")
['hello']
>>> tolist("separate,values, with, commas, spaces , are ,ok")
['separate', 'values', 'with', 'commas', 'spaces', 'are', 'ok']
"""
if val is None:
return None
try:
# might already be a list
val.extend([])
return val
except AttributeError:
pass
# might be a string
try:
return re.split(r'\s*,\s*', val)
except TypeError:
# who knows...
return list(val) |
def transplant_func(func, module):
"""
Make a function imported from module A appear as if it is located
in module B.
>>> from pprint import pprint
>>> pprint.__module__
'pprint'
>>> pp = transplant_func(pprint, __name__)
>>> pp.__module__
'nose.util'
The original function is not modified.
>>> pprint.__module__
'pprint'
Calling the transplanted function calls the original.
>>> pp([1, 2])
[1, 2]
>>> pprint([1,2])
[1, 2]
"""
from nose.tools import make_decorator
def newfunc(*arg, **kw):
return func(*arg, **kw)
newfunc = make_decorator(func)(newfunc)
newfunc.__module__ = module
return newfunc |
def transplant_class(cls, module):
"""
Make a class appear to reside in `module`, rather than the module in which
it is actually defined.
>>> from nose.failure import Failure
>>> Failure.__module__
'nose.failure'
>>> Nf = transplant_class(Failure, __name__)
>>> Nf.__module__
'nose.util'
>>> Nf.__name__
'Failure'
"""
class C(cls):
pass
C.__module__ = module
C.__name__ = cls.__name__
return C |
def virtual_memory():
"""System virtual memory as a namedtuple."""
total, active, inactive, wired, free = _psutil_osx.get_virtual_mem()
avail = inactive + free
used = active + inactive + wired
percent = usage_percent((total - avail), total, _round=1)
return nt_virtmem_info(total, avail, percent, used, free,
active, inactive, wired) |
def swap_memory():
"""Swap system memory as a (total, used, free, sin, sout) tuple."""
total, used, free, sin, sout = _psutil_osx.get_swap_mem()
percent = usage_percent(used, total, _round=1)
return nt_swapmeminfo(total, used, free, percent, sin, sout) |
def get_system_cpu_times():
"""Return system CPU times as a namedtuple."""
user, nice, system, idle = _psutil_osx.get_system_cpu_times()
return _cputimes_ntuple(user, nice, system, idle) |
def get_system_per_cpu_times():
"""Return system CPU times as a named tuple"""
ret = []
for cpu_t in _psutil_osx.get_system_per_cpu_times():
user, nice, system, idle = cpu_t
item = _cputimes_ntuple(user, nice, system, idle)
ret.append(item)
return ret |
def get_process_cmdline(self):
"""Return process cmdline as a list of arguments."""
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._process_name)
return _psutil_osx.get_process_cmdline(self.pid) |
def get_memory_info(self):
"""Return a tuple with the process' RSS and VMS size."""
rss, vms = _psutil_osx.get_process_memory_info(self.pid)[:2]
return nt_meminfo(rss, vms) |
def get_ext_memory_info(self):
"""Return a tuple with the process' RSS and VMS size."""
rss, vms, pfaults, pageins = _psutil_osx.get_process_memory_info(self.pid)
return self._nt_ext_mem(rss, vms,
pfaults * _PAGESIZE,
pageins * _PAGESIZE) |
def get_open_files(self):
"""Return files opened by process."""
if self.pid == 0:
return []
files = []
rawlist = _psutil_osx.get_process_open_files(self.pid)
for path, fd in rawlist:
if isfile_strict(path):
ntuple = nt_openfile(path, fd)
files.append(ntuple)
return files |
def get_connections(self, kind='inet'):
"""Return etwork connections opened by a process as a list of
namedtuples.
"""
if kind not in conn_tmap:
raise ValueError("invalid %r kind argument; choose between %s"
% (kind, ', '.join([repr(x) for x in conn_tmap])))
families, types = conn_tmap[kind]
ret = _psutil_osx.get_process_connections(self.pid, families, types)
return [nt_connection(*conn) for conn in ret] |
def user_has_group(user, group, superuser_skip=True):
"""
Check if a user is in a certaing group.
By default, the check is skipped for superusers.
"""
if user.is_superuser and superuser_skip:
return True
return user.groups.filter(name=group).exists() |
def resolve_class(class_path):
"""
Load a class by a fully qualified class_path,
eg. myapp.models.ModelName
"""
modulepath, classname = class_path.rsplit('.', 1)
module = __import__(modulepath, fromlist=[classname])
return getattr(module, classname) |
def usage_percent(used, total, _round=None):
"""Calculate percentage usage of 'used' against 'total'."""
try:
ret = (used / total) * 100
except ZeroDivisionError:
ret = 0
if _round is not None:
return round(ret, _round)
else:
return ret |
def memoize(f):
"""A simple memoize decorator for functions."""
cache= {}
def memf(*x):
if x not in cache:
cache[x] = f(*x)
return cache[x]
return memf |
def deprecated(replacement=None):
"""A decorator which can be used to mark functions as deprecated."""
def outer(fun):
msg = "psutil.%s is deprecated" % fun.__name__
if replacement is not None:
msg += "; use %s instead" % replacement
if fun.__doc__ is None:
fun.__doc__ = msg
@wraps(fun)
def inner(*args, **kwargs):
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
return fun(*args, **kwargs)
return inner
return outer |
def isfile_strict(path):
"""Same as os.path.isfile() but does not swallow EACCES / EPERM
exceptions, see:
http://mail.python.org/pipermail/python-dev/2012-June/120787.html
"""
try:
st = os.stat(path)
except OSError:
err = sys.exc_info()[1]
if err.errno in (errno.EPERM, errno.EACCES):
raise
return False
else:
return stat.S_ISREG(st.st_mode) |
def git_push(git_message=None, git_repository=None, git_branch=None,
locale_root=None):
"""
Pushes specified directory to git remote
:param git_message: commit message
:param git_repository: repository address
:param git_branch: git branch
:param locale_root: path to locale root folder containing directories
with languages
:return: tuple stdout, stderr of completed command
"""
if git_message is None:
git_message = settings.GIT_MESSAGE
if git_repository is None:
git_repository = settings.GIT_REPOSITORY
if git_branch is None:
git_branch = settings.GIT_BRANCH
if locale_root is None:
locale_root = settings.LOCALE_ROOT
try:
subprocess.check_call(['git', 'checkout', git_branch])
except subprocess.CalledProcessError:
try:
subprocess.check_call(['git', 'checkout', '-b', git_branch])
except subprocess.CalledProcessError as e:
raise PODocsError(e)
try:
subprocess.check_call(['git', 'ls-remote', git_repository])
except subprocess.CalledProcessError:
try:
subprocess.check_call(['git', 'remote', 'add', 'po_translator',
git_repository])
except subprocess.CalledProcessError as e:
raise PODocsError(e)
commands = 'git add ' + locale_root + \
' && git commit -m "' + git_message + '"' + \
' && git push po_translator ' + git_branch + ':' + git_branch
proc = Popen(commands, shell=True, stdout=PIPE, stderr=PIPE)
stdout, stderr = proc.communicate()
return stdout, stderr |
def git_checkout(git_branch=None, locale_root=None):
"""
Checkouts branch to last commit
:param git_branch: branch to checkout
:param locale_root: locale folder path
:return: tuple stdout, stderr of completed command
"""
if git_branch is None:
git_branch = settings.GIT_BRANCH
if locale_root is None:
locale_root = settings.LOCALE_ROOT
proc = Popen('git checkout ' + git_branch + ' -- ' + locale_root,
shell=True, stdout=PIPE, stderr=PIPE)
stdout, stderr = proc.communicate()
return stdout, stderr |
def _login(self):
"""
Login into Google Docs with user authentication info.
"""
try:
self.gd_client = gdata.docs.client.DocsClient()
self.gd_client.ClientLogin(self.email, self.password, self.source)
except RequestError as e:
raise PODocsError(e) |
def _get_gdocs_key(self):
"""
Parse GDocs key from Spreadsheet url.
"""
try:
args = urlparse.parse_qs(urlparse.urlparse(self.url).query)
self.key = args['key'][0]
except KeyError as e:
raise PODocsError(e) |
def _ensure_temp_path_exists(self):
"""
Make sure temp directory exists and create one if it does not.
"""
try:
if not os.path.exists(self.temp_path):
os.mkdir(self.temp_path)
except OSError as e:
raise PODocsError(e) |
def _clear_temp(self):
"""
Clear temp directory from created csv and ods files during
communicator operations.
"""
temp_files = [LOCAL_ODS, GDOCS_TRANS_CSV, GDOCS_META_CSV,
LOCAL_TRANS_CSV, LOCAL_META_CSV]
for temp_file in temp_files:
file_path = os.path.join(self.temp_path, temp_file)
if os.path.exists(file_path):
os.remove(file_path) |
def _download_csv_from_gdocs(self, trans_csv_path, meta_csv_path):
"""
Download csv from GDoc.
:return: returns resource if worksheets are present
:except: raises PODocsError with info if communication
with GDocs lead to any errors
"""
try:
entry = self.gd_client.GetResourceById(self.key)
self.gd_client.DownloadResource(
entry, trans_csv_path,
extra_params={'gid': 0, 'exportFormat': 'csv'}
)
self.gd_client.DownloadResource(
entry, meta_csv_path,
extra_params={'gid': 1, 'exportFormat': 'csv'}
)
except (RequestError, IOError) as e:
raise PODocsError(e)
return entry |
def _upload_file_to_gdoc(
self, file_path,
content_type='application/x-vnd.oasis.opendocument.spreadsheet'):
"""
Uploads file to GDocs spreadsheet.
Content type can be provided as argument, default is ods.
"""
try:
entry = self.gd_client.GetResourceById(self.key)
media = gdata.data.MediaSource(
file_path=file_path, content_type=content_type)
self.gd_client.UpdateResource(
entry, media=media, update_metadata=True)
except (RequestError, IOError) as e:
raise PODocsError(e) |
def _merge_local_and_gdoc(self, entry, local_trans_csv,
local_meta_csv, gdocs_trans_csv, gdocs_meta_csv):
"""
Download csv from GDoc.
:return: returns resource if worksheets are present
:except: raises PODocsError with info if communication with GDocs
lead to any errors
"""
try:
new_translations = po_to_csv_merge(
self.languages, self.locale_root, self.po_files_path,
local_trans_csv, local_meta_csv,
gdocs_trans_csv, gdocs_meta_csv)
if new_translations:
local_ods = os.path.join(self.temp_path, LOCAL_ODS)
csv_to_ods(local_trans_csv, local_meta_csv, local_ods)
media = gdata.data.MediaSource(
file_path=local_ods, content_type=
'application/x-vnd.oasis.opendocument.spreadsheet'
)
self.gd_client.UpdateResource(entry, media=media,
update_metadata=True)
except (IOError, OSError, RequestError) as e:
raise PODocsError(e) |
def synchronize(self):
"""
Synchronize local po files with translations on GDocs Spreadsheet.
Downloads two csv files, merges them and converts into po files
structure. If new msgids appeared in po files, this method creates
new ods with appended content and sends it to GDocs.
"""
gdocs_trans_csv = os.path.join(self.temp_path, GDOCS_TRANS_CSV)
gdocs_meta_csv = os.path.join(self.temp_path, GDOCS_META_CSV)
local_trans_csv = os.path.join(self.temp_path, LOCAL_TRANS_CSV)
local_meta_csv = os.path.join(self.temp_path, LOCAL_META_CSV)
try:
entry = self._download_csv_from_gdocs(gdocs_trans_csv,
gdocs_meta_csv)
except PODocsError as e:
if 'Sheet 1 not found' in str(e) \
or 'Conversion failed unexpectedly' in str(e):
self.upload()
else:
raise PODocsError(e)
else:
self._merge_local_and_gdoc(entry, local_trans_csv, local_meta_csv,
gdocs_trans_csv, gdocs_meta_csv)
try:
csv_to_po(local_trans_csv, local_meta_csv,
self.locale_root, self.po_files_path, self.header)
except IOError as e:
raise PODocsError(e)
self._clear_temp() |
def download(self):
"""
Download csv files from GDocs and convert them into po files structure.
"""
trans_csv_path = os.path.realpath(
os.path.join(self.temp_path, GDOCS_TRANS_CSV))
meta_csv_path = os.path.realpath(
os.path.join(self.temp_path, GDOCS_META_CSV))
self._download_csv_from_gdocs(trans_csv_path, meta_csv_path)
try:
csv_to_po(trans_csv_path, meta_csv_path,
self.locale_root, self.po_files_path, header=self.header)
except IOError as e:
raise PODocsError(e)
self._clear_temp() |
def upload(self):
"""
Upload all po files to GDocs ignoring conflicts.
This method looks for all msgids in po_files and sends them
as ods to GDocs Spreadsheet.
"""
local_ods_path = os.path.join(self.temp_path, LOCAL_ODS)
try:
po_to_ods(self.languages, self.locale_root,
self.po_files_path, local_ods_path)
except (IOError, OSError) as e:
raise PODocsError(e)
self._upload_file_to_gdoc(local_ods_path)
self._clear_temp() |
def clear(self):
"""
Clear GDoc Spreadsheet by sending empty csv file.
"""
empty_file_path = os.path.join(self.temp_path, 'empty.csv')
try:
empty_file = open(empty_file_path, 'w')
empty_file.write(',')
empty_file.close()
except IOError as e:
raise PODocsError(e)
self._upload_file_to_gdoc(empty_file_path, content_type='text/csv')
os.remove(empty_file_path) |
def new_qt_console(self, evt=None):
"""start a new qtconsole connected to our kernel"""
return connect_qtconsole(self.ipkernel.connection_file, profile=self.ipkernel.profile) |
def check_url_accessibility(url, timeout=10):
'''
Check whether the URL accessible and returns HTTP 200 OK or not
if not raises ValidationError
'''
if(url=='localhost'):
url = 'http://127.0.0.1'
try:
req = urllib2.urlopen(url, timeout=timeout)
if (req.getcode()==200):
return True
except Exception:
pass
fail("URL '%s' is not accessible from this machine" % url) |
def url_has_contents(url, contents, case_sensitive=False, timeout=10):
'''
Check whether the HTML page contains the content or not and return boolean
'''
try:
req = urllib2.urlopen(url, timeout=timeout)
except Exception, _:
False
else:
rep = req.read()
if (not case_sensitive and rep.lower().find(contents.lower()) >= 0) or (case_sensitive and rep.find(contents) >= 0):
return True
else:
return False |
def get_response_code(url, timeout=10):
'''
Visit the URL and return the HTTP response code in 'int'
'''
try:
req = urllib2.urlopen(url, timeout=timeout)
except HTTPError, e:
return e.getcode()
except Exception, _:
fail("Couldn't reach the URL '%s'" % url)
else:
return req.getcode() |
def compare_content_type(url, content_type):
'''
Compare the content type header of url param with content_type param and returns boolean
@param url -> string e.g. http://127.0.0.1/index
@param content_type -> string e.g. text/html
'''
try:
response = urllib2.urlopen(url)
except:
return False
return response.headers.type == content_type |
def compare_response_code(url, code):
'''
Compare the response code of url param with code param and returns boolean
@param url -> string e.g. http://127.0.0.1/index
@param content_type -> int e.g. 404, 500, 400 ..etc
'''
try:
response = urllib2.urlopen(url)
except HTTPError as e:
return e.code == code
except:
return False
return response.code == code |
def publish_display_data(source, data, metadata=None):
"""Publish data and metadata to all frontends.
See the ``display_data`` message in the messaging documentation for
more details about this message type.
The following MIME types are currently implemented:
* text/plain
* text/html
* text/latex
* application/json
* application/javascript
* image/png
* image/jpeg
* image/svg+xml
Parameters
----------
source : str
A string that give the function or method that created the data,
such as 'IPython.core.page'.
data : dict
A dictionary having keys that are valid MIME types (like
'text/plain' or 'image/svg+xml') and values that are the data for
that MIME type. The data itself must be a JSON'able data
structure. Minimally all data should have the 'text/plain' data,
which can be displayed by all frontends. If more than the plain
text is given, it is up to the frontend to decide which
representation to use.
metadata : dict
A dictionary for metadata related to the data. This can contain
arbitrary key, value pairs that frontends can use to interpret
the data.
"""
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.instance().display_pub.publish(
source,
data,
metadata
) |
def _validate_data(self, source, data, metadata=None):
"""Validate the display data.
Parameters
----------
source : str
The fully dotted name of the callable that created the data, like
:func:`foo.bar.my_formatter`.
data : dict
The formata data dictionary.
metadata : dict
Any metadata for the data.
"""
if not isinstance(source, basestring):
raise TypeError('source must be a str, got: %r' % source)
if not isinstance(data, dict):
raise TypeError('data must be a dict, got: %r' % data)
if metadata is not None:
if not isinstance(metadata, dict):
raise TypeError('metadata must be a dict, got: %r' % data) |
def publish(self, source, data, metadata=None):
"""Publish data and metadata to all frontends.
See the ``display_data`` message in the messaging documentation for
more details about this message type.
The following MIME types are currently implemented:
* text/plain
* text/html
* text/latex
* application/json
* application/javascript
* image/png
* image/jpeg
* image/svg+xml
Parameters
----------
source : str
A string that give the function or method that created the data,
such as 'IPython.core.page'.
data : dict
A dictionary having keys that are valid MIME types (like
'text/plain' or 'image/svg+xml') and values that are the data for
that MIME type. The data itself must be a JSON'able data
structure. Minimally all data should have the 'text/plain' data,
which can be displayed by all frontends. If more than the plain
text is given, it is up to the frontend to decide which
representation to use.
metadata : dict
A dictionary for metadata related to the data. This can contain
arbitrary key, value pairs that frontends can use to interpret
the data.
"""
# The default is to simply write the plain text data using io.stdout.
if data.has_key('text/plain'):
print(data['text/plain'], file=io.stdout) |
def clear_output(self, stdout=True, stderr=True, other=True):
"""Clear the output of the cell receiving output."""
if stdout:
print('\033[2K\r', file=io.stdout, end='')
io.stdout.flush()
if stderr:
print('\033[2K\r', file=io.stderr, end='')
io.stderr.flush() |
def grad(f, delta=DELTA):
"""
Returns numerical gradient function of given input function
Input: f, scalar function of one or two variables
delta(optional), finite difference step
Output: gradient function object
"""
def grad_f(*args, **kwargs):
if len(args) == 1:
x, = args
gradf_x = (
f(x+delta/2) - f(x-delta/2)
)/delta
return gradf_x
elif len(args) == 2:
x, y = args
if type(x) in [float, int] and type(y) in [float, int]:
gradf_x = (f(x + delta/2, y) - f(x - delta/2, y))/delta
gradf_y = (f(x, y + delta/2) - f(x, y - delta/2))/delta
return gradf_x, gradf_y
return grad_f |
def hessian(f, delta=DELTA):
"""
Returns numerical hessian function of given input function
Input: f, scalar function of one or two variables
delta(optional), finite difference step
Output: hessian function object
"""
def hessian_f(*args, **kwargs):
if len(args) == 1:
x, = args
hessianf_x = (
f(x+delta) + f(x-delta) - 2*f(x)
)/delta**2
return hessianf_x
elif len(args) == 2:
x, y = args
if type(x) in [float, int] and type(y) in [float, int]:
hess_xx = (
f(x + delta, y) + f(x - delta, y) - 2*f(x, y)
)/delta**2
hess_yy = (
f(x, y + delta) + f(x, y - delta) - 2*f(x, y)
)/delta**2
hess_xy = (
+ f(x+delta/2, y+delta/2)
+ f(x-delta/2, y-delta/2)
- f(x+delta/2, y-delta/2)
- f(x-delta/2, y+delta/2)
)/delta**2
return hess_xx, hess_xy, hess_yy
return hessian_f |
def ndgrad(f, delta=DELTA):
"""
Returns numerical gradient function of given input function
Input: f, scalar function of an numpy array object
delta(optional), finite difference step
Output: gradient function object
"""
def grad_f(*args, **kwargs):
x = args[0]
grad_val = numpy.zeros(x.shape)
it = numpy.nditer(x, op_flags=['readwrite'], flags=['multi_index'])
for xi in it:
i = it.multi_index
xi += delta/2
fp = f(*args, **kwargs)
xi -= delta
fm = f(*args, **kwargs)
xi += delta/2
grad_val[i] = (fp - fm)/delta
return grad_val
return grad_f |
def ndhess(f, delta=DELTA):
"""
Returns numerical hessian function of given input function
Input: f, scalar function of an numpy array object
delta(optional), finite difference step
Output: hessian function object
"""
def hess_f(*args, **kwargs):
x = args[0]
hess_val = numpy.zeros(x.shape + x.shape)
it = numpy.nditer(x, op_flags=['readwrite'], flags=['multi_index'])
for xi in it:
i = it.multi_index
jt = numpy.nditer(x, op_flags=['readwrite'], flags=['multi_index'])
for xj in jt:
j = jt.multi_index
xi += delta/2
xj += delta/2
fpp = f(x)
xj -= delta
fpm = f(x)
xi -= delta
fmm = f(x)
xj += delta
fmp = f(x)
xi += delta/2
xj -= delta/2
hess_val[i + j] = (fpp + fmm - fpm - fmp)/delta**2
return hess_val
return hess_f |
def clgrad(obj, exe, arg, delta=DELTA):
"""
Returns numerical gradient function of given class method
with respect to a class attribute
Input: obj, general object
exe (str), name of object method
arg (str), name of object atribute
delta(float, optional), finite difference step
Output: gradient function object
"""
f, x = get_method_and_copy_of_attribute(obj, exe, arg)
def grad_f(*args, **kwargs):
grad_val = numpy.zeros(x.shape)
it = numpy.nditer(x, op_flags=['readwrite'], flags=['multi_index'])
for xi in it:
i = it.multi_index
xi += delta/2
fp = f(*args, **kwargs)
xi -= delta
fm = f(*args, **kwargs)
xi += delta/2
grad_val[i] = (fp - fm)/delta
return grad_val
return grad_f |
def clmixhess(obj, exe, arg1, arg2, delta=DELTA):
"""
Returns numerical mixed Hessian function of given class method
with respect to two class attributes
Input: obj, general object
exe (str), name of object method
arg1(str), name of object attribute
arg2(str), name of object attribute
delta(float, optional), finite difference step
Output: Hessian function object
"""
f, x = get_method_and_copy_of_attribute(obj, exe, arg1)
_, y = get_method_and_copy_of_attribute(obj, exe, arg2)
def hess_f(*args, **kwargs):
hess_val = numpy.zeros(x.shape + y.shape)
it = numpy.nditer(x, op_flags=['readwrite'], flags=['multi_index'])
for xi in it:
i = it.multi_index
jt = numpy.nditer(y, op_flags=['readwrite'], flags=['multi_index'])
for yj in jt:
j = jt.multi_index
xi += delta/2
yj += delta/2
fpp = f(*args, **kwargs)
yj -= delta
fpm = f(*args, **kwargs)
xi -= delta
fmm = f(*args, **kwargs)
yj += delta
fmp = f(*args, **kwargs)
xi += delta/2
yj -= delta/2
hess_val[i + j] = (fpp + fmm - fpm - fmp)/delta**2
return hess_val
return hess_f |
def find_cmd(cmd):
"""Find absolute path to executable cmd in a cross platform manner.
This function tries to determine the full path to a command line program
using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the
time it will use the version that is first on the users `PATH`. If
cmd is `python` return `sys.executable`.
Warning, don't use this to find IPython command line programs as there
is a risk you will find the wrong one. Instead find those using the
following code and looking for the application itself::
from IPython.utils.path import get_ipython_module_path
from IPython.utils.process import pycmd2argv
argv = pycmd2argv(get_ipython_module_path('IPython.frontend.terminal.ipapp'))
Parameters
----------
cmd : str
The command line program to look for.
"""
if cmd == 'python':
return os.path.abspath(sys.executable)
try:
path = _find_cmd(cmd).rstrip()
except OSError:
raise FindCmdError('command could not be found: %s' % cmd)
# which returns empty if not found
if path == '':
raise FindCmdError('command could not be found: %s' % cmd)
return os.path.abspath(path) |
def pycmd2argv(cmd):
r"""Take the path of a python command and return a list (argv-style).
This only works on Python based command line programs and will find the
location of the ``python`` executable using ``sys.executable`` to make
sure the right version is used.
For a given path ``cmd``, this returns [cmd] if cmd's extension is .exe,
.com or .bat, and [, cmd] otherwise.
Parameters
----------
cmd : string
The path of the command.
Returns
-------
argv-style list.
"""
ext = os.path.splitext(cmd)[1]
if ext in ['.exe', '.com', '.bat']:
return [cmd]
else:
return [sys.executable, cmd] |
def abbrev_cwd():
""" Return abbreviated version of cwd, e.g. d:mydir """
cwd = os.getcwdu().replace('\\','/')
drivepart = ''
tail = cwd
if sys.platform == 'win32':
if len(cwd) < 4:
return cwd
drivepart,tail = os.path.splitdrive(cwd)
parts = tail.split('/')
if len(parts) > 2:
tail = '/'.join(parts[-2:])
return (drivepart + (
cwd == '/' and '/' or tail)) |
def code_unit_factory(morfs, file_locator):
"""Construct a list of CodeUnits from polymorphic inputs.
`morfs` is a module or a filename, or a list of same.
`file_locator` is a FileLocator that can help resolve filenames.
Returns a list of CodeUnit objects.
"""
# Be sure we have a list.
if not isinstance(morfs, (list, tuple)):
morfs = [morfs]
# On Windows, the shell doesn't expand wildcards. Do it here.
globbed = []
for morf in morfs:
if isinstance(morf, string_class) and ('?' in morf or '*' in morf):
globbed.extend(glob.glob(morf))
else:
globbed.append(morf)
morfs = globbed
code_units = [CodeUnit(morf, file_locator) for morf in morfs]
return code_units |
def flat_rootname(self):
"""A base for a flat filename to correspond to this code unit.
Useful for writing files about the code where you want all the files in
the same directory, but need to differentiate same-named files from
different directories.
For example, the file a/b/c.py might return 'a_b_c'
"""
if self.modname:
return self.modname.replace('.', '_')
else:
root = os.path.splitdrive(self.name)[1]
return root.replace('\\', '_').replace('/', '_').replace('.', '_') |
def source_file(self):
"""Return an open file for reading the source of the code unit."""
if os.path.exists(self.filename):
# A regular text file: open it.
return open_source(self.filename)
# Maybe it's in a zip file?
source = self.file_locator.get_zip_data(self.filename)
if source is not None:
return StringIO(source)
# Couldn't find source.
raise CoverageException(
"No source for code '%s'." % self.filename
) |
def should_be_python(self):
"""Does it seem like this file should contain Python?
This is used to decide if a file reported as part of the exection of
a program was really likely to have contained Python in the first
place.
"""
# Get the file extension.
_, ext = os.path.splitext(self.filename)
# Anything named *.py* should be Python.
if ext.startswith('.py'):
return True
# A file with no extension should be Python.
if not ext:
return True
# Everything else is probably not Python.
return False |
def _total_seconds(td):
"""timedelta.total_seconds was added in 2.7"""
try:
# Python >= 2.7
return td.total_seconds()
except AttributeError:
# Python 2.6
return 1e-6 * (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) |
def check_ready(f, self, *args, **kwargs):
"""Call spin() to sync state prior to calling the method."""
self.wait(0)
if not self._ready:
raise error.TimeoutError("result not ready")
return f(self, *args, **kwargs) |
def get(self, timeout=-1):
"""Return the result when it arrives.
If `timeout` is not ``None`` and the result does not arrive within
`timeout` seconds then ``TimeoutError`` is raised. If the
remote call raised an exception then that exception will be reraised
by get() inside a `RemoteError`.
"""
if not self.ready():
self.wait(timeout)
if self._ready:
if self._success:
return self._result
else:
raise self._exception
else:
raise error.TimeoutError("Result not ready.") |
def wait(self, timeout=-1):
"""Wait until the result is available or until `timeout` seconds pass.
This method always returns None.
"""
if self._ready:
return
self._ready = self._client.wait(self.msg_ids, timeout)
if self._ready:
try:
results = map(self._client.results.get, self.msg_ids)
self._result = results
if self._single_result:
r = results[0]
if isinstance(r, Exception):
raise r
else:
results = error.collect_exceptions(results, self._fname)
self._result = self._reconstruct_result(results)
except Exception, e:
self._exception = e
self._success = False
else:
self._success = True
finally:
self._metadata = map(self._client.metadata.get, self.msg_ids)
self._wait_for_outputs(10) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.