INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Split a line of text with a cursor at the given position.
def split_line(self, line, cursor_pos=None): """Split a line of text with a cursor at the given position. """ l = line if cursor_pos is None else line[:cursor_pos] return self._delim_re.split(l)[-1]
Compute matches when text is a simple name.
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace or self.global_namespace that match. """ #print 'Completer->global_matches, txt=%r' % text # dbg matches = [] match_append = matches.append n = len(text) for lst in [keyword.kwlist, __builtin__.__dict__.keys(), self.namespace.keys(), self.global_namespace.keys()]: for word in lst: if word[:n] == text and word != "__builtins__": match_append(word) return matches
Compute matches when text contains a dot.
def attr_matches(self, text): """Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated. """ #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg # Another option, seems to work great. Catches things like ''.<tab> m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) if m: expr, attr = m.group(1, 3) elif self.greedy: m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) if not m2: return [] expr, attr = m2.group(1,2) else: return [] try: obj = eval(expr, self.namespace) except: try: obj = eval(expr, self.global_namespace) except: return [] if self.limit_to__all__ and hasattr(obj, '__all__'): words = get__all__entries(obj) else: words = dir2(obj) try: words = generics.complete_object(obj, words) except TryNext: pass except Exception: # Silence errors from completion function #raise # dbg pass # Build match list to return n = len(attr) res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] return res
update the splitter and readline delims when greedy is changed
def _greedy_changed(self, name, old, new): """update the splitter and readline delims when greedy is changed""" if new: self.splitter.delims = GREEDY_DELIMS else: self.splitter.delims = DELIMS if self.readline: self.readline.set_completer_delims(self.splitter.delims)
Match filenames expanding ~USER type strings.
def file_matches(self, text): """Match filenames, expanding ~USER type strings. Most of the seemingly convoluted logic in this completer is an attempt to handle filenames with spaces in them. And yet it's not quite perfect, because Python's readline doesn't expose all of the GNU readline details needed for this to be done correctly. For a filename with a space in it, the printed completions will be only the parts after what's already been typed (instead of the full completions, as is normally done). I don't think with the current (as of Python 2.3) Python readline it's possible to do better.""" #io.rprint('Completer->file_matches: <%r>' % text) # dbg # chars that require escaping with backslash - i.e. chars # that readline treats incorrectly as delimiters, but we # don't want to treat as delimiters in filename matching # when escaped with backslash if text.startswith('!'): text = text[1:] text_prefix = '!' else: text_prefix = '' text_until_cursor = self.text_until_cursor # track strings with open quotes open_quotes = has_open_quotes(text_until_cursor) if '(' in text_until_cursor or '[' in text_until_cursor: lsplit = text else: try: # arg_split ~ shlex.split, but with unicode bugs fixed by us lsplit = arg_split(text_until_cursor)[-1] except ValueError: # typically an unmatched ", or backslash without escaped char. if open_quotes: lsplit = text_until_cursor.split(open_quotes)[-1] else: return [] except IndexError: # tab pressed on empty line lsplit = "" if not open_quotes and lsplit != protect_filename(lsplit): # if protectables are found, do matching on the whole escaped name has_protectables = True text0,text = text,lsplit else: has_protectables = False text = os.path.expanduser(text) if text == "": return [text_prefix + protect_filename(f) for f in self.glob("*")] # Compute the matches from the filesystem m0 = self.clean_glob(text.replace('\\','')) if has_protectables: # If we had protectables, we need to revert our changes to the # beginning of filename so that we don't double-write the part # of the filename we have so far len_lsplit = len(lsplit) matches = [text_prefix + text0 + protect_filename(f[len_lsplit:]) for f in m0] else: if open_quotes: # if we have a string with an open quote, we don't need to # protect the names at all (and we _shouldn't_, as it # would cause bugs when the filesystem call is made). matches = m0 else: matches = [text_prefix + protect_filename(f) for f in m0] #io.rprint('mm', matches) # dbg # Mark directories in input list by appending '/' to their names. matches = [x+'/' if os.path.isdir(x) else x for x in matches] return matches
Match magics
def magic_matches(self, text): """Match magics""" #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg # Get all shell magics now rather than statically, so magics loaded at # runtime show up too. lsm = self.shell.magics_manager.lsmagic() line_magics = lsm['line'] cell_magics = lsm['cell'] pre = self.magic_escape pre2 = pre+pre # Completion logic: # - user gives %%: only do cell magics # - user gives %: do both line and cell magics # - no prefix: do both # In other words, line magics are skipped if the user gives %% explicitly bare_text = text.lstrip(pre) comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)] if not text.startswith(pre2): comp += [ pre+m for m in line_magics if m.startswith(bare_text)] return comp
Match internal system aliases
def alias_matches(self, text): """Match internal system aliases""" #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg # if we are not in the first 'item', alias matching # doesn't make sense - unless we are starting with 'sudo' command. main_text = self.text_until_cursor.lstrip() if ' ' in main_text and not main_text.startswith('sudo'): return [] text = os.path.expanduser(text) aliases = self.alias_table.keys() if text == '': return aliases else: return [a for a in aliases if a.startswith(text)]
Match attributes or global python names
def python_matches(self,text): """Match attributes or global python names""" #io.rprint('Completer->python_matches, txt=%r' % text) # dbg if "." in text: try: matches = self.attr_matches(text) if text.endswith('.') and self.omit__names: if self.omit__names == 1: # true if txt is _not_ a __ name, false otherwise: no__name = (lambda txt: re.match(r'.*\.__.*?__',txt) is None) else: # true if txt is _not_ a _ name, false otherwise: no__name = (lambda txt: re.match(r'.*\._.*?',txt) is None) matches = filter(no__name, matches) except NameError: # catches <undefined attributes>.<tab> matches = [] else: matches = self.global_matches(text) return matches
Return the list of default arguments of obj if it is callable or empty list otherwise.
def _default_arguments(self, obj): """Return the list of default arguments of obj if it is callable, or empty list otherwise.""" if not (inspect.isfunction(obj) or inspect.ismethod(obj)): # for classes, check for __init__,__new__ if inspect.isclass(obj): obj = (getattr(obj,'__init__',None) or getattr(obj,'__new__',None)) # for all others, check if they are __call__able elif hasattr(obj, '__call__'): obj = obj.__call__ # XXX: is there a way to handle the builtins ? try: args,_,_1,defaults = inspect.getargspec(obj) if defaults: return args[-len(defaults):] except TypeError: pass return []
Match named parameters ( kwargs ) of the last open function
def python_func_kw_matches(self,text): """Match named parameters (kwargs) of the last open function""" if "." in text: # a parameter cannot be dotted return [] try: regexp = self.__funcParamsRegex except AttributeError: regexp = self.__funcParamsRegex = re.compile(r''' '.*?(?<!\\)' | # single quoted strings or ".*?(?<!\\)" | # double quoted strings or \w+ | # identifier \S # other characters ''', re.VERBOSE | re.DOTALL) # 1. find the nearest identifier that comes before an unclosed # parenthesis before the cursor # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" tokens = regexp.findall(self.text_until_cursor) tokens.reverse() iterTokens = iter(tokens); openPar = 0 for token in iterTokens: if token == ')': openPar -= 1 elif token == '(': openPar += 1 if openPar > 0: # found the last unclosed parenthesis break else: return [] # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) ids = [] isId = re.compile(r'\w+$').match while True: try: ids.append(iterTokens.next()) if not isId(ids[-1]): ids.pop(); break if not iterTokens.next() == '.': break except StopIteration: break # lookup the candidate callable matches either using global_matches # or attr_matches for dotted names if len(ids) == 1: callableMatches = self.global_matches(ids[0]) else: callableMatches = self.attr_matches('.'.join(ids[::-1])) argMatches = [] for callableMatch in callableMatches: try: namedArgs = self._default_arguments(eval(callableMatch, self.namespace)) except: continue for namedArg in namedArgs: if namedArg.startswith(text): argMatches.append("%s=" %namedArg) return argMatches
Find completions for the given text and line context.
def complete(self, text=None, line_buffer=None, cursor_pos=None): """Find completions for the given text and line context. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. Note that both the text and the line_buffer are optional, but at least one of them must be given. Parameters ---------- text : string, optional Text to perform the completion on. If not given, the line buffer is split using the instance's CompletionSplitter object. line_buffer : string, optional If not given, the completer attempts to obtain the current line buffer via readline. This keyword allows clients which are requesting for text completions in non-readline contexts to inform the completer of the entire text. cursor_pos : int, optional Index of the cursor in the full line buffer. Should be provided by remote frontends where kernel has no access to frontend state. Returns ------- text : str Text that was actually used in the completion. matches : list A list of completion matches. """ #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg # if the cursor position isn't given, the only sane assumption we can # make is that it's at the end of the line (the common case) if cursor_pos is None: cursor_pos = len(line_buffer) if text is None else len(text) # if text is either None or an empty string, rely on the line buffer if not text: text = self.splitter.split_line(line_buffer, cursor_pos) # If no line buffer is given, assume the input text is all there was if line_buffer is None: line_buffer = text self.line_buffer = line_buffer self.text_until_cursor = self.line_buffer[:cursor_pos] #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg # Start with a clean slate of completions self.matches[:] = [] custom_res = self.dispatch_custom_completer(text) if custom_res is not None: # did custom completers produce something? self.matches = custom_res else: # Extend the list of completions with the results of each # matcher, so we return results to the user from all # namespaces. if self.merge_completions: self.matches = [] for matcher in self.matchers: try: self.matches.extend(matcher(text)) except: # Show the ugly traceback if the matcher causes an # exception, but do NOT crash the kernel! sys.excepthook(*sys.exc_info()) else: for matcher in self.matchers: self.matches = matcher(text) if self.matches: break # FIXME: we should extend our api to return a dict with completions for # different types of objects. The rlcomplete() method could then # simply collapse the dict into a list for readline, but we'd have # richer completion semantics in other evironments. self.matches = sorted(set(self.matches)) #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg return text, self.matches
Return the state - th possible completion for text.
def rlcomplete(self, text, state): """Return the state-th possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. Parameters ---------- text : string Text to perform the completion on. state : int Counter used by readline. """ if state==0: self.line_buffer = line_buffer = self.readline.get_line_buffer() cursor_pos = self.readline.get_endidx() #io.rprint("\nRLCOMPLETE: %r %r %r" % # (text, line_buffer, cursor_pos) ) # dbg # if there is only a tab on a line with only whitespace, instead of # the mostly useless 'do you want to see all million completions' # message, just do the right thing and give the user his tab! # Incidentally, this enables pasting of tabbed text from an editor # (as long as autoindent is off). # It should be noted that at least pyreadline still shows file # completions - is there a way around it? # don't apply this on 'dumb' terminals, such as emacs buffers, so # we don't interfere with their own tab-completion mechanism. if not (self.dumb_terminal or line_buffer.strip()): self.readline.insert_text('\t') sys.stdout.flush() return None # Note: debugging exceptions that may occur in completion is very # tricky, because readline unconditionally silences them. So if # during development you suspect a bug in the completion code, turn # this flag on temporarily by uncommenting the second form (don't # flip the value in the first line, as the '# dbg' marker can be # automatically detected and is used elsewhere). DEBUG = False #DEBUG = True # dbg if DEBUG: try: self.complete(text, line_buffer, cursor_pos) except: import traceback; traceback.print_exc() else: # The normal production version is here # This method computes the self.matches array self.complete(text, line_buffer, cursor_pos) try: return self.matches[state] except IndexError: return None
Check if a specific record matches tests.
def _match_one(self, rec, tests): """Check if a specific record matches tests.""" for key,test in tests.iteritems(): if not test(rec.get(key, None)): return False return True
Find all the matches for a check dict.
def _match(self, check): """Find all the matches for a check dict.""" matches = [] tests = {} for k,v in check.iteritems(): if isinstance(v, dict): tests[k] = CompositeFilter(v) else: tests[k] = lambda o: o==v for rec in self._records.itervalues(): if self._match_one(rec, tests): matches.append(copy(rec)) return matches
extract subdict of keys
def _extract_subdict(self, rec, keys): """extract subdict of keys""" d = {} d['msg_id'] = rec['msg_id'] for key in keys: d[key] = rec[key] return copy(d)
Add a new Task Record by msg_id.
def add_record(self, msg_id, rec): """Add a new Task Record, by msg_id.""" if self._records.has_key(msg_id): raise KeyError("Already have msg_id %r"%(msg_id)) self._records[msg_id] = rec
Get a specific Task Record by msg_id.
def get_record(self, msg_id): """Get a specific Task Record, by msg_id.""" if not msg_id in self._records: raise KeyError("No such msg_id %r"%(msg_id)) return copy(self._records[msg_id])
Remove a record from the DB.
def drop_matching_records(self, check): """Remove a record from the DB.""" matches = self._match(check) for m in matches: del self._records[m['msg_id']]
Find records matching a query dict optionally extracting subset of keys.
def find_records(self, check, keys=None): """Find records matching a query dict, optionally extracting subset of keys. Returns dict keyed by msg_id of matching records. Parameters ---------- check: dict mongodb-style query argument keys: list of strs [optional] if specified, the subset of keys to extract. msg_id will *always* be included. """ matches = self._match(check) if keys: return [ self._extract_subdict(rec, keys) for rec in matches ] else: return matches
get all msg_ids ordered by time submitted.
def get_history(self): """get all msg_ids, ordered by time submitted.""" msg_ids = self._records.keys() return sorted(msg_ids, key=lambda m: self._records[m]['submitted'])
Should we silence the display hook because of ; ?
def quiet(self): """Should we silence the display hook because of ';'?""" # do not print output if input ends in ';' try: cell = self.shell.history_manager.input_hist_parsed[self.prompt_count] if cell.rstrip().endswith(';'): return True except IndexError: # some uses of ipshellembed may fail here pass return False
Write the output prompt.
def write_output_prompt(self): """Write the output prompt. The default implementation simply writes the prompt to ``io.stdout``. """ # Use write, not print which adds an extra space. io.stdout.write(self.shell.separate_out) outprompt = self.shell.prompt_manager.render('out') if self.do_full_cache: io.stdout.write(outprompt)
Write the format data dict to the frontend.
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
Update user_ns with various things like _ __ _1 etc.
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
Log the output.
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']
Finish up all displayhook activities.
def finish_displayhook(self): """Finish up all displayhook activities.""" io.stdout.write(self.shell.separate_out2) io.stdout.flush()
Load the extension in IPython.
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
raise InvalidOperationException if is freezed.
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))
Convert a MySQL TIMESTAMP to a Timestamp object.
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
body_elements: <list > of etree. Elements or <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 )
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.
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()
schedule call to eventloop from IOLoop
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)
dispatch control requests
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)
dispatch shell requests
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)
enter eventloop
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()
register dispatchers for streams
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)
step eventloop just once
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)
Publish the code request on the pyin stream.
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') )
send status ( busy/ idle ) on IOPub
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'), )
handle an execute_request
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)
abort a specifig msg by id
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)
Clear our namespace.
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'))
prefixed topic for IOPub messages
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))
Actions taken at shutdown by the kernel called by python s atexit.
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 ]
Enable GUI event loop integration taking pylab into account.
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
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 ).
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
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.
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
Same as file. read () but for the slice. Does not read beyond self. end.
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
Same as file. write () but for the slice. raises: EOFError if the new seek position is > self. size.
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
Same as file. writelines () but for the slice. raises: EOFError if the new seek position is > self. size.
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)
Configure plugin.
def configure(self, options, conf): """Configure plugin. """ Plugin.configure(self, options, conf) self._mod_stack = []
Copy sys. modules onto my mod stack
def beforeContext(self): """Copy sys.modules onto my mod stack """ mods = sys.modules.copy() self._mod_stack.append(mods)
Pop my mod stack and restore sys. modules to the state it was in when mod stack was pushed.
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)
Return absolute normalized path to directory if it exists ; None otherwise.
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
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.
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
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.
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]))
Is obj a class? Inspect s isclass is too liberal and returns True for objects that can t be subclasses of anything.
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)
Is this path a package directory?
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
Find the python source file for a package relative to a particular directory ( defaults to current working directory if not given ).
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
Find the full dotted package name for a given python source file name. Returns None if the file is not a python source file.
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)
Draw a 70 - char - wide divider with label in the middle.
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
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.
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()
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.
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
Sort key function factory that puts items that match a regular expression last.
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
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 ].
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)
Make a function imported from module A appear as if it is located in module B.
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
Make a class appear to reside in module rather than the module in which it is actually defined.
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
System virtual memory as a namedtuple.
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)
Swap system memory as a ( total used free sin sout ) tuple.
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)
Return system CPU times as a namedtuple.
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)
Return system CPU times as a named tuple
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
Return process cmdline as a list of arguments.
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)
Return a tuple with the process RSS and VMS size.
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)
Return a tuple with the process RSS and VMS size.
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)
Return files opened by process.
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
Return etwork connections opened by a process as a list of namedtuples.
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]
Check if a user is in a certaing group. By default the check is skipped for superusers.
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()
Load a class by a fully qualified class_path eg. myapp. models. ModelName
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)
Calculate percentage usage of used against total.
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
A simple memoize decorator for functions.
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
A decorator which can be used to mark functions as deprecated.
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
Same as os. path. isfile () but does not swallow EACCES/ EPERM exceptions see: http:// mail. python. org/ pipermail/ python - dev/ 2012 - June/ 120787. html
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)
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
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
Checkouts branch to last commit: param git_branch: branch to checkout: param locale_root: locale folder path: return: tuple stdout stderr of completed command
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
Login into Google Docs with user authentication info.
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)
Parse GDocs key from Spreadsheet url.
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)
Make sure temp directory exists and create one if it does not.
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)
Clear temp directory from created csv and ods files during communicator operations.
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)
Download csv from GDoc.: return: returns resource if worksheets are present: except: raises PODocsError with info if communication with GDocs lead to any errors
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
Uploads file to GDocs spreadsheet. Content type can be provided as argument default is ods.
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)
Download csv from GDoc.: return: returns resource if worksheets are present: except: raises PODocsError with info if communication with GDocs lead to any errors
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)
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.
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()
Download csv files from GDocs and convert them into po files structure.
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()
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.
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()
Clear GDoc Spreadsheet by sending empty csv file.
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)
start a new qtconsole connected to our kernel
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)
Check whether the URL accessible and returns HTTP 200 OK or not if not raises ValidationError
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)
Check whether the HTML page contains the content or not and return boolean
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
Visit the URL and return the HTTP response code in int
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()
Compare the content type header of url param with content_type param and returns boolean
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