INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Reimplemented to handle keyboard input and to auto - hide when the text edit loses focus.
def eventFilter(self, obj, event): """ Reimplemented to handle keyboard input and to auto-hide when the text edit loses focus. """ if obj == self._text_edit: etype = event.type() if etype == QtCore.QEvent.KeyPress: key = event.key() ...
Cancel the completion
def cancel_completion(self): """Cancel the completion should be called when the completer have to be dismissed This reset internal variable, clearing the temporary buffer of the console where the completion are shown. """ self._consecutive_tab = 0 self._slice_st...
Change the selection index and make sure it stays in the right range
def _select_index(self, row, col): """Change the selection index, and make sure it stays in the right range A little more complicated than just dooing modulo the number of row columns to be sure to cycle through all element. horizontaly, the element are maped like this : to r <...
move cursor up
def select_up(self): """move cursor up""" r, c = self._index self._select_index(r-1, c)
move cursor down
def select_down(self): """move cursor down""" r, c = self._index self._select_index(r+1, c)
move cursor left
def select_left(self): """move cursor left""" r, c = self._index self._select_index(r, c-1)
move cursor right
def select_right(self): """move cursor right""" r, c = self._index self._select_index(r, c+1)
Shows the completion widget with items at the position specified by cursor.
def show_items(self, cursor, items): """ Shows the completion widget with 'items' at the position specified by 'cursor'. """ if not items : return self._start_position = cursor.position() self._consecutive_tab = 1 items_m, ci = text.compute_item_ma...
update the list of completion and hilight the currently selected completion
def _update_list(self, hilight=True): """ update the list of completion and hilight the currently selected completion """ self._sliding_interval.current = self._index[0] head = None foot = None if self._sliding_interval.start > 0 : head = '...' if self._slid...
Perform the completion with the currently selected item.
def _complete_current(self): """ Perform the completion with the currently selected item. """ i = self._index item = self._items[i[0]][i[1]] item = item.strip() if item : self._current_text_cursor().insertText(item) self.cancel_completion()
Return a dictionary of words and word counts in a string.
def wordfreq(text, is_filename=False): """Return a dictionary of words and word counts in a string.""" if is_filename: with open(text) as f: text = f.read() freqs = {} for word in text.split(): lword = word.lower() freqs[lword] = freqs.get(lword, 0) + 1 return fre...
Print the n most common words and counts in the freqs dict.
def print_wordfreq(freqs, n=10): """Print the n most common words and counts in the freqs dict.""" words, counts = freqs.keys(), freqs.values() items = zip(counts, words) items.sort(reverse=True) for (count, word) in items[:n]: print(word, count)
Return the string representation of the job description XML.
def tostring(self): """Return the string representation of the job description XML.""" root = self.as_element() indent(root) txt = ET.tostring(root, encoding="utf-8") # Now remove the tokens used to order the attributes. txt = re.sub(r'_[A-Z]_','',txt) txt = '<?xm...
Write the XML job description to a file.
def write(self, filename): """Write the XML job description to a file.""" txt = self.tostring() with open(filename, 'w') as f: f.write(txt)
Validate the given pin against the schema.
def validate_pin(pin): """ Validate the given pin against the schema. :param dict pin: The pin to validate: :raises pypebbleapi.schemas.DocumentError: If the pin is not valid. """ v = _Validator(schemas.pin) if v.validate(pin): return else: raise schemas.DocumentError(errors...
Send a shared pin for the given topics.
def send_shared_pin(self, topics, pin, skip_validation=False): """ Send a shared pin for the given topics. :param list topics: The list of topics. :param dict pin: The pin. :param bool skip_validation: Whether to skip the validation. :raises pypebbleapi.schemas.DocumentE...
Delete a shared pin.
def delete_shared_pin(self, pin_id): """ Delete a shared pin. :param str pin_id: The id of the pin to delete. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ if not self.api_key: raise ValueError("You need to specify an api_key.") ...
Send a user pin.
def send_user_pin(self, user_token, pin, skip_validation=False): """ Send a user pin. :param str user_token: The token of the user. :param dict pin: The pin. :param bool skip_validation: Whether to skip the validation. :raises pypebbleapi.schemas.DocumentError: If the va...
Delete a user pin.
def delete_user_pin(self, user_token, pin_id): """ Delete a user pin. :param str user_token: The token of the user. :param str pin_id: The id of the pin to delete. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ response = _request('DELET...
Subscribe a user to the given topic.
def subscribe(self, user_token, topic): """ Subscribe a user to the given topic. :param str user_token: The token of the user. :param str topic: The topic. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ response = _request('POST', ...
Get the list of the topics which a user is subscribed to.
def list_subscriptions(self, user_token): """ Get the list of the topics which a user is subscribed to. :param str user_token: The token of the user. :return: The list of the topics. :rtype: list :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. ...
Decorate a function to automatically begin and end a task on the progressmonitor. The function must have a parameter called monitor
def monitored(total: int, name=None, message=None): """ Decorate a function to automatically begin and end a task on the progressmonitor. The function must have a parameter called 'monitor' """ def decorator(f): nonlocal name monitor_index = list(inspect.signature(f).parameters.keys(...
Call before starting work on a monitor specifying name and amount of work
def begin(self, total: int, name=None, message=None): """Call before starting work on a monitor, specifying name and amount of work""" self.total = total message = message or name or "Working..." self.name = name or "ProgressMonitor" self.update(0, message)
Wrap code into a begin and end call on this monitor
def task(self, total: int, name=None, message=None): """Wrap code into a begin and end call on this monitor""" self.begin(total, name, message) try: yield self finally: self.done()
Create a submonitor with the given units
def subtask(self, units: int): """Create a submonitor with the given units""" sm = self.submonitor(units) try: yield sm finally: if sm.total is None: # begin was never called, so the subtask cannot be closed self.update(units) ...
What percentage ( range 0 - 1 ) of work is done ( including submonitors )
def progress(self)-> float: """What percentage (range 0-1) of work is done (including submonitors)""" if self.total is None: return 0 my_progress = self.worked my_progress += sum(s.progress * weight for (s, weight) in self.sub_monitors.items()) ...
Increment the monitor with N units worked and an optional message
def update(self, units: int=1, message: str=None): """Increment the monitor with N units worked and an optional message""" if self.total is None: raise Exception("Cannot call progressmonitor.update before calling begin") self.worked = min(self.total, self.worked+units) if mes...
Create a sub monitor that stands for N units of work in this monitor The sub task should call. begin ( or use
def submonitor(self, units: int, *args, **kargs) -> 'ProgressMonitor': """ Create a sub monitor that stands for N units of work in this monitor The sub task should call .begin (or use @monitored / with .task) before calling updates """ submonitor = ProgressMonitor(*args, **kargs)...
Signal that this task is done. This is completely optional and will just call. update with the remaining work.
def done(self, message: str=None): """ Signal that this task is done. This is completely optional and will just call .update with the remaining work. """ if message is None: message = "{self.name} done".format(**locals()) if self.name else "Done" self.update(u...
Print a string piping through a pager.
def page(strng, start=0, screen_lines=0, pager_cmd=None, html=None, auto_html=False): """Print a string, piping through a pager. This version ignores the screen_lines and pager_cmd arguments and uses IPython's payload system instead. Parameters ---------- strng : str Text to pag...
Creates an InstallRequirement from a name which might be a requirement directory containing setup. py filename or URL.
def from_line(cls, name, comes_from=None, isolated=False): """Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. """ from pip.index import Link url = None if is_url(name): marker_sep = '...
If the build location was a temporary directory this will move it to a new more permanent location
def correct_build_location(self): """If the build location was a temporary directory, this will move it to a new more permanent location""" if self.source_dir is not None: return assert self.req is not None assert self._temp_build_dir old_location = self._temp...
Uninstall the distribution currently satisfying this requirement.
def uninstall(self, auto_confirm=False): """ Uninstall the distribution currently satisfying this requirement. Prompts before removing or modifying files unless ``auto_confirm`` is True. Refuses to delete or modify files outside of ``sys.prefix`` - thus uninstallation w...
Load multiple Python config files merging each of them in turn.
def load_pyconfig_files(config_files, path): """Load multiple Python config files, merging each of them in turn. Parameters ========== config_files : list of str List of config files names to load and merge into the config. path : unicode The full path to the location of the config ...
Load the config from a file and return it as a Struct.
def load_config(self): """Load the config from a file and return it as a Struct.""" self.clear() try: self._find_file() except IOError as e: raise ConfigFileNotFound(str(e)) self._read_file_as_dict() self._convert_to_config() return self.co...
Load the config file into self. config with recursive loading.
def _read_file_as_dict(self): """Load the config file into self.config, with recursive loading.""" # This closure is made available in the namespace that is used # to exec the config file. It allows users to call # load_subconfig('myconfig.py') to load config files recursively. ...
execute self. config. <lhs > = <rhs > * expands ~ with expanduser * tries to assign with raw eval otherwise assigns with just the string allowing -- C. a = foobar and -- C. a = foobar to be equivalent. * Not * equivalent are -- C. a = 4 and -- C. a = 4.
def _exec_config_str(self, lhs, rhs): """execute self.config.<lhs> = <rhs> * expands ~ with expanduser * tries to assign with raw eval, otherwise assigns with just the string, allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not* equivalent are `--C.a...
update self. config from a flag which can be a dict or Config
def _load_flag(self, cfg): """update self.config from a flag, which can be a dict or Config""" if isinstance(cfg, (dict, Config)): # don't clobber whole config sections, update # each section from config: for sec,c in cfg.iteritems(): self.config[sec]....
decode argv if bytes using stin. encoding falling back on default enc
def _decode_argv(self, argv, enc=None): """decode argv if bytes, using stin.encoding, falling back on default enc""" uargv = [] if enc is None: enc = DEFAULT_ENCODING for arg in argv: if not isinstance(arg, unicode): # only decode if not already de...
Parse the configuration and generate the Config object.
def load_config(self, argv=None, aliases=None, flags=None): """Parse the configuration and generate the Config object. After loading, any arguments that are not key-value or flags will be stored in self.extra_args - a list of unparsed command-line arguments. This is used for ar...
Parse command line arguments and return as a Config object.
def load_config(self, argv=None, aliases=None, flags=None): """Parse command line arguments and return as a Config object. Parameters ---------- args : optional, list If given, a list with the structure of sys.argv[1:] to parse arguments from. If not given, the inst...
self. parser - > self. parsed_data
def _parse_args(self, args): """self.parser->self.parsed_data""" # decode sys.argv to support unicode command-line options enc = DEFAULT_ENCODING uargs = [py3compat.cast_unicode(a, enc) for a in args] self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs)
self. parsed_data - > self. config
def _convert_to_config(self): """self.parsed_data->self.config""" for k, v in vars(self.parsed_data).iteritems(): exec "self.config.%s = v"%k in locals(), globals()
self. parsed_data - > self. config parse unrecognized extra args via KVLoader.
def _convert_to_config(self): """self.parsed_data->self.config, parse unrecognized extra args via KVLoader.""" # remove subconfigs list from namespace before transforming the Namespace if '_flags' in self.parsed_data: subcs = self.parsed_data._flags del self.parsed_data._...
imp. find_module variant that only return path of module. The imp. find_module returns a filehandle that we are not interested in. Also we ignore any bytecode files that imp. find_module finds.
def find_module(name, path=None): """imp.find_module variant that only return path of module. The `imp.find_module` returns a filehandle that we are not interested in. Also we ignore any bytecode files that `imp.find_module` finds. Parameters ---------- name : str name of module to...
Get __init__ file path for module directory Parameters ---------- dirname: str Find the __init__ file in directory dirname
def get_init(dirname): """Get __init__ file path for module directory Parameters ---------- dirname : str Find the __init__ file in directory `dirname` Returns ------- init_path : str Path to __init__ file """ fbase = os.path.join(dirname, "__init__") for e...
Find module module_name on sys. path Return the path to module module_name. If module_name refers to a module directory then return path to __init__ file. Return full path of module or None if module is missing or does not have. py or. pyw extension. We are not interested in running bytecode. Parameters ---------- modu...
def find_mod(module_name): """Find module `module_name` on sys.path Return the path to module `module_name`. If `module_name` refers to a module directory then return path to __init__ file. Return full path of module or None if module is missing or does not have .py or .pyw extension. We are n...
Register a callback to be called with this Launcher s stop_data when the process actually finishes.
def on_stop(self, f): """Register a callback to be called with this Launcher's stop_data when the process actually finishes. """ if self.state=='after': return f(self.stop_data) else: self.stop_callbacks.append(f)
Call this to trigger startup actions.
def notify_start(self, data): """Call this to trigger startup actions. This logs the process startup and sets the state to 'running'. It is a pass-through so it can be used as a callback. """ self.log.debug('Process %r started: %r', self.args[0], data) self.start_data ...
Call this to trigger process stop actions.
def notify_stop(self, data): """Call this to trigger process stop actions. This logs the process stopping and sets the state to 'after'. Call this to trigger callbacks registered via :meth:`on_stop`.""" self.log.debug('Process %r stopped: %r', self.args[0], data) self.stop_data...
Send INT wait a delay and then send KILL.
def interrupt_then_kill(self, delay=2.0): """Send INT, wait a delay and then send KILL.""" try: self.signal(SIGINT) except Exception: self.log.debug("interrupt failed") pass self.killer = ioloop.DelayedCallback(lambda : self.signal(SIGKILL), delay*100...
Start n engines by profile or profile_dir.
def start(self, n): """Start n engines by profile or profile_dir.""" dlist = [] for i in range(n): if i > 0: time.sleep(self.delay) el = self.launcher_class(work_dir=self.work_dir, config=self.config, log=self.log, profi...
Build self. args using all the fields.
def find_args(self): """Build self.args using all the fields.""" return self.mpi_cmd + ['-n', str(self.n)] + self.mpi_args + \ self.program + self.program_args
Start n instances of the program using mpiexec.
def start(self, n): """Start n instances of the program using mpiexec.""" self.n = n return super(MPILauncher, self).start()
Start n engines by profile or profile_dir.
def start(self, n): """Start n engines by profile or profile_dir.""" self.n = n return super(MPIEngineSetLauncher, self).start(n)
send a single file
def _send_file(self, local, remote): """send a single file""" remote = "%s:%s" % (self.location, remote) for i in range(10): if not os.path.exists(local): self.log.debug("waiting for %s" % local) time.sleep(1) else: break ...
send our files ( called before start )
def send_files(self): """send our files (called before start)""" if not self.to_send: return for local_file, remote_file in self.to_send: self._send_file(local_file, remote_file)
fetch a single file
def _fetch_file(self, remote, local): """fetch a single file""" full_remote = "%s:%s" % (self.location, remote) self.log.info("fetching %s from %s", local, full_remote) for i in range(10): # wait up to 10s for remote file to exist check = check_output(self.ssh_cmd...
fetch remote files ( called after start )
def fetch_files(self): """fetch remote files (called after start)""" if not self.to_fetch: return for remote_file, local_file in self.to_fetch: self._fetch_file(remote_file, local_file)
turns/ home/ you/. ipython/ profile_foo into. ipython/ profile_foo
def _remote_profile_dir_default(self): """turns /home/you/.ipython/profile_foo into .ipython/profile_foo """ home = get_home_dir() if not home.endswith('/'): home = home+'/' if self.profile_dir.startswith(home): return self.profile_dir[len(home):]...
determine engine count from engines dict
def engine_count(self): """determine engine count from `engines` dict""" count = 0 for n in self.engines.itervalues(): if isinstance(n, (tuple,list)): n,args = n count += n return count
Start engines by profile or profile_dir. n is ignored and the engines config property is used instead.
def start(self, n): """Start engines by profile or profile_dir. `n` is ignored, and the `engines` config property is used instead. """ dlist = [] for host, n in self.engines.iteritems(): if isinstance(n, (tuple, list)): n, args = n else: ...
Start n copies of the process using the Win HPC job scheduler.
def start(self, n): """Start n copies of the process using the Win HPC job scheduler.""" self.write_job_file(n) args = [ 'submit', '/jobfile:%s' % self.job_file, '/scheduler:%s' % self.scheduler ] self.log.debug("Starting Win HPC Job: %s" % (se...
load the default context with the default values for the basic keys
def _context_default(self): """load the default context with the default values for the basic keys because the _trait_changed methods only load the context if they are set to something other than the default value. """ return dict(n=1, queue=u'', profile_dir=u'', cluster_id=u'')
Take the output of the submit command and return the job id.
def parse_job_id(self, output): """Take the output of the submit command and return the job id.""" m = self.job_id_regexp.search(output) if m is not None: job_id = m.group() else: raise LauncherError("Job id couldn't be determined: %s" % output) self.job_i...
Instantiate and write the batch script to the work_dir.
def write_batch_script(self, n): """Instantiate and write the batch script to the work_dir.""" self.n = n # first priority is batch_template if set if self.batch_template_file and not self.batch_template: # second priority is batch_template_file with open(self.bat...
Start n copies of the process using a batch system.
def start(self, n): """Start n copies of the process using a batch system.""" self.log.debug("Starting %s: %r", self.__class__.__name__, self.args) # Here we save profile_dir in the context so they # can be used in the batch script template as {profile_dir} self.write_batch_scrip...
Start n copies of the process using LSF batch system. This cant inherit from the base class because bsub expects to be piped a shell script in order to honor the #BSUB directives: bsub < script
def start(self, n): """Start n copies of the process using LSF batch system. This cant inherit from the base class because bsub expects to be piped a shell script in order to honor the #BSUB directives : bsub < script """ # Here we save profile_dir in the context so they ...
Return True if file matches ( permission ) which should be entered in octal.
def check_filemode(filepath, mode): """Return True if 'file' matches ('permission') which should be entered in octal. """ filemode = stat.S_IMODE(os.stat(filepath).st_mode) return (oct(filemode) == mode)
Reimplemented to return a custom context menu for images.
def _context_menu_make(self, pos): """ Reimplemented to return a custom context menu for images. """ format = self._control.cursorForPosition(pos).charFormat() name = format.stringProperty(QtGui.QTextFormat.ImageName) if name: menu = QtGui.QMenu() menu.ad...
Append the Out [] prompt and make the output nicer
def _pre_image_append(self, msg, prompt_number): """ Append the Out[] prompt and make the output nicer Shared code for some the following if statement """ self.log.debug("pyout: %s", msg.get('content', '')) self._append_plain_text(self.output_sep, True) self._append_htm...
Overridden to handle rich data types like SVG.
def _handle_pyout(self, msg): """ Overridden to handle rich data types, like SVG. """ if not self._hidden and self._is_from_this_session(msg): content = msg['content'] prompt_number = content.get('execution_count', 0) data = content['data'] if data...
Overridden to handle rich data types like SVG.
def _handle_display_data(self, msg): """ Overridden to handle rich data types, like SVG. """ if not self._hidden and self._is_from_this_session(msg): source = msg['content']['source'] data = msg['content']['data'] metadata = msg['content']['metadata'] ...
Append raw JPG data to the widget.
def _append_jpg(self, jpg, before_prompt=False): """ Append raw JPG data to the widget.""" self._append_custom(self._insert_jpg, jpg, before_prompt)
Append raw PNG data to the widget.
def _append_png(self, png, before_prompt=False): """ Append raw PNG data to the widget. """ self._append_custom(self._insert_png, png, before_prompt)
Append raw SVG data to the widget.
def _append_svg(self, svg, before_prompt=False): """ Append raw SVG data to the widget. """ self._append_custom(self._insert_svg, svg, before_prompt)
Adds the specified QImage to the document and returns a QTextImageFormat that references it.
def _add_image(self, image): """ Adds the specified QImage to the document and returns a QTextImageFormat that references it. """ document = self._control.document() name = str(image.cacheKey()) document.addResource(QtGui.QTextDocument.ImageResource, ...
Copies the ImageResource with name to the clipboard.
def _copy_image(self, name): """ Copies the ImageResource with 'name' to the clipboard. """ image = self._get_image(name) QtGui.QApplication.clipboard().setImage(image)
Returns the QImage stored as the ImageResource with name.
def _get_image(self, name): """ Returns the QImage stored as the ImageResource with 'name'. """ document = self._control.document() image = document.resource(QtGui.QTextDocument.ImageResource, QtCore.QUrl(name)) return image
Return ( X ) HTML mark - up for the image - tag given by match.
def _get_image_tag(self, match, path = None, format = "png"): """ Return (X)HTML mark-up for the image-tag given by match. Parameters ---------- match : re.SRE_Match A match to an HTML image tag as exported by Qt, with match.group("Name") containing the matched i...
insert a raw image jpg or png
def _insert_img(self, cursor, img, fmt): """ insert a raw image, jpg or png """ try: image = QtGui.QImage() image.loadFromData(img, fmt.upper()) except ValueError: self._insert_plain_text(cursor, 'Received invalid %s data.'%fmt) else: forma...
Insert raw SVG data into the widet.
def _insert_svg(self, cursor, svg): """ Insert raw SVG data into the widet. """ try: image = svg_to_image(svg) except ValueError: self._insert_plain_text(cursor, 'Received invalid SVG data.') else: format = self._add_image(image) se...
Shows a save dialog for the ImageResource with name.
def _save_image(self, name, format='PNG'): """ Shows a save dialog for the ImageResource with 'name'. """ dialog = QtGui.QFileDialog(self._control, 'Save Image') dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) dialog.setDefaultSuffix(format.lower()) dialog.setNameFilte...
unicode ( e ) with various fallbacks. Used for exceptions which may not be safe to call unicode () on.
def safe_unicode(e): """unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on. """ try: return unicode(e) except UnicodeError: pass try: return py3compat.str_to_unicode(str(e)) except UnicodeError: pass try: ...
stop eventloop when exit_now fires
def _exit_now_changed(self, name, old, new): """stop eventloop when exit_now fires""" if new: loop = ioloop.IOLoop.instance() loop.add_timeout(time.time()+0.1, loop.stop)
Configure the user s environment.
def init_environment(self): """Configure the user's environment. """ env = os.environ # These two ensure 'ls' produces nice coloring on BSD-derived systems env['TERM'] = 'xterm-color' env['CLICOLOR'] = '1' # Since normal pagers don't work at all (over pexpect we ...
Called to show the auto - rewritten input for autocall and friends.
def auto_rewrite_input(self, cmd): """Called to show the auto-rewritten input for autocall and friends. FIXME: this payload is currently not correctly processed by the frontend. """ new = self.prompt_manager.render('rewrite') + cmd payload = dict( source='IPy...
Engage the exit actions.
def ask_exit(self): """Engage the exit actions.""" self.exit_now = True payload = dict( source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', exit=True, keepkernel=self.keepkernel_on_exit, ) self.payload_manager.write_payload(payload)
Send the specified text to the frontend to be presented at the next input cell.
def set_next_input(self, text): """Send the specified text to the frontend to be presented at the next input cell.""" payload = dict( source='IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input', text=text ) self.payload_manager.write_payload(payload)
CHECK if process ( default = apache2 ) is not running
def check_running(process_name="apache2"): ''' CHECK if process (default=apache2) is not running ''' if not gurumate.base.get_pid_list(process_name): fail("Apache process '%s' doesn't seem to be working" % process_name) return False #unreachable return True
returns a list of listening ports for running process ( default = apache2 )
def get_listening_ports(process_name="apache2"): ''' returns a list of listening ports for running process (default=apache2) ''' ports = set() for _, address_info in gurumate.base.get_listening_ports(process_name): ports.add(address_info[1]) return list(ports)
Read a filename as UTF - 8 configuration data.
def read(self, filename): """Read a filename as UTF-8 configuration data.""" kwargs = {} if sys.version_info >= (3, 2): kwargs['encoding'] = "utf-8" return configparser.RawConfigParser.read(self, filename, **kwargs)
Read a list of strings.
def getlist(self, section, option): """Read a list of strings. The value of `section` and `option` is treated as a comma- and newline- separated list of strings. Each value is stripped of whitespace. Returns the list of strings. """ value_list = self.get(section, opti...
Read a list of full - line strings.
def getlinelist(self, section, option): """Read a list of full-line strings. The value of `section` and `option` is treated as a newline-separated list of strings. Each value is stripped of whitespace. Returns the list of strings. """ value_list = self.get(section, op...
Read configuration from the env_var environment variable.
def from_environment(self, env_var): """Read configuration from the `env_var` environment variable.""" # Timidity: for nose users, read an environment variable. This is a # cheap hack, since the rest of the command line arguments aren't # recognized, but it solves some users' problems. ...
Read config values from kwargs.
def from_args(self, **kwargs): """Read config values from `kwargs`.""" for k, v in iitems(kwargs): if v is not None: if k in self.MUST_BE_LIST and isinstance(v, string_class): v = [v] setattr(self, k, v)
Read configuration from a. rc file.
def from_file(self, filename): """Read configuration from a .rc file. `filename` is a file name to read. """ self.attempted_config_files.append(filename) cp = HandyConfigParser() files_read = cp.read(filename) if files_read is not None: # return value changed ...
Set an attribute on self if it exists in the ConfigParser.
def set_attr_from_config_option(self, cp, attr, where, type_=''): """Set an attribute on self if it exists in the ConfigParser.""" section, option = where.split(":") if cp.has_option(section, option): method = getattr(cp, 'get'+type_) setattr(self, attr, method(section, o...
Expand ~ - style usernames in strings.
def expand_user(path): """Expand '~'-style usernames in strings. This is similar to :func:`os.path.expanduser`, but it computes and returns extra information that will be useful if the input was being used in computing completions, and you wish to return the completions with the original '~' instea...
Set the delimiters for line splitting.
def delims(self, delims): """Set the delimiters for line splitting.""" expr = '[' + ''.join('\\'+ c for c in delims) + ']' self._delim_re = re.compile(expr) self._delims = delims self._delim_expr = expr