_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3 values | text stringlengths 75 19.8k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q34000 | Cmd.runcmds_plus_hooks | train | def runcmds_plus_hooks(self, cmds: List[str]) -> bool:
"""Convenience method to run multiple commands by onecmd_plus_hooks.
This method adds the given cmds to the command queue and processes the
queue until completion or an error causes it to abort. Scripts that are
loaded will have their commands added to the queue. Scripts may even
load other scripts recursively. This means, however, that you should not
use this method if there is a running cmdloop or some other event-loop.
This method is only intended to be used in "one-off" scenarios.
NOTE: You may need this method even if you only have one command. If
that command is a load, then you will need this command to fully process
all the subsequent commands that are loaded from the script file. This
is an improvement over onecmd_plus_hooks, which expects to be used
inside of a command loop which does the processing of loaded commands.
Example: cmd_obj.runcmds_plus_hooks(['load myscript.txt'])
:param cmds: command strings suitable for onecmd_plus_hooks.
:return: True implies the entire application should exit.
"""
stop = False
self.cmdqueue = list(cmds) + self.cmdqueue
try:
while self.cmdqueue and not stop:
line = self.cmdqueue.pop(0)
if self.echo and line != 'eos':
self.poutput('{}{}'.format(self.prompt, line))
stop = self.onecmd_plus_hooks(line)
finally:
# Clear out the command queue and script directory stack, just in
# case we hit an error and they were not completed.
self.cmdqueue = []
self._script_dir = []
# NOTE: placing this return here inside the finally block will
# swallow exceptions. This is consistent with what is done in
# onecmd_plus_hooks and _cmdloop, although it may not be
# necessary/desired here.
return stop | python | {
"resource": ""
} |
q34001 | Cmd._complete_statement | train | def _complete_statement(self, line: str) -> Statement:
"""Keep accepting lines of input until the command is complete.
There is some pretty hacky code here to handle some quirks of
self.pseudo_raw_input(). It returns a literal 'eof' if the input
pipe runs out. We can't refactor it because we need to retain
backwards compatibility with the standard library version of cmd.
"""
while True:
try:
statement = self.statement_parser.parse(line)
if statement.multiline_command and statement.terminator:
# we have a completed multiline command, we are done
break
if not statement.multiline_command:
# it's not a multiline command, but we parsed it ok
# so we are done
break
except ValueError:
# we have unclosed quotation marks, lets parse only the command
# and see if it's a multiline
statement = self.statement_parser.parse_command_only(line)
if not statement.multiline_command:
# not a multiline command, so raise the exception
raise
# if we get here we must have:
# - a multiline command with no terminator
# - a multiline command with unclosed quotation marks
try:
self.at_continuation_prompt = True
newline = self.pseudo_raw_input(self.continuation_prompt)
if newline == 'eof':
# they entered either a blank line, or we hit an EOF
# for some other reason. Turn the literal 'eof'
# into a blank line, which serves as a command
# terminator
newline = '\n'
self.poutput(newline)
line = '{}\n{}'.format(statement.raw, newline)
except KeyboardInterrupt as ex:
if self.quit_on_sigint:
raise ex
else:
self.poutput('^C')
statement = self.statement_parser.parse('')
break
finally:
self.at_continuation_prompt = False
if not statement.command:
raise EmptyStatement()
return statement | python | {
"resource": ""
} |
q34002 | Cmd._redirect_output | train | def _redirect_output(self, statement: Statement) -> Tuple[bool, utils.RedirectionSavedState]:
"""Handles output redirection for >, >>, and |.
:param statement: a parsed statement from the user
:return: A bool telling if an error occurred and a utils.RedirectionSavedState object
"""
import io
import subprocess
redir_error = False
# Initialize the saved state
saved_state = utils.RedirectionSavedState(self.stdout, sys.stdout, self.cur_pipe_proc_reader)
if not self.allow_redirection:
return redir_error, saved_state
if statement.pipe_to:
# Create a pipe with read and write sides
read_fd, write_fd = os.pipe()
# Open each side of the pipe
subproc_stdin = io.open(read_fd, 'r')
new_stdout = io.open(write_fd, 'w')
# We want Popen to raise an exception if it fails to open the process. Thus we don't set shell to True.
try:
# Set options to not forward signals to the pipe process. If a Ctrl-C event occurs,
# our sigint handler will forward it only to the most recent pipe process. This makes
# sure pipe processes close in the right order (most recent first).
if sys.platform == 'win32':
creationflags = subprocess.CREATE_NEW_PROCESS_GROUP
start_new_session = False
else:
creationflags = 0
start_new_session = True
# For any stream that is a StdSim, we will use a pipe so we can capture its output
proc = \
subprocess.Popen(statement.pipe_to,
stdin=subproc_stdin,
stdout=subprocess.PIPE if isinstance(self.stdout, utils.StdSim) else self.stdout,
stderr=subprocess.PIPE if isinstance(sys.stderr, utils.StdSim) else sys.stderr,
creationflags=creationflags,
start_new_session=start_new_session)
saved_state.redirecting = True
saved_state.pipe_proc_reader = utils.ProcReader(proc, self.stdout, sys.stderr)
sys.stdout = self.stdout = new_stdout
except Exception as ex:
self.perror('Failed to open pipe because - {}'.format(ex), traceback_war=False)
subproc_stdin.close()
new_stdout.close()
redir_error = True
elif statement.output:
import tempfile
if (not statement.output_to) and (not self.can_clip):
self.perror("Cannot redirect to paste buffer; install 'pyperclip' and re-run to enable",
traceback_war=False)
redir_error = True
elif statement.output_to:
# going to a file
mode = 'w'
# statement.output can only contain
# REDIRECTION_APPEND or REDIRECTION_OUTPUT
if statement.output == constants.REDIRECTION_APPEND:
mode = 'a'
try:
new_stdout = open(statement.output_to, mode)
saved_state.redirecting = True
sys.stdout = self.stdout = new_stdout
except OSError as ex:
self.perror('Failed to redirect because - {}'.format(ex), traceback_war=False)
redir_error = True
else:
# going to a paste buffer
new_stdout = tempfile.TemporaryFile(mode="w+")
saved_state.redirecting = True
sys.stdout = self.stdout = new_stdout
if statement.output == constants.REDIRECTION_APPEND:
self.poutput(get_paste_buffer())
return redir_error, saved_state | python | {
"resource": ""
} |
q34003 | Cmd._restore_output | train | def _restore_output(self, statement: Statement, saved_state: utils.RedirectionSavedState) -> None:
"""Handles restoring state after output redirection as well as
the actual pipe operation if present.
:param statement: Statement object which contains the parsed input from the user
:param saved_state: contains information needed to restore state data
"""
if saved_state.redirecting:
# If we redirected output to the clipboard
if statement.output and not statement.output_to:
self.stdout.seek(0)
write_to_paste_buffer(self.stdout.read())
try:
# Close the file or pipe that stdout was redirected to
self.stdout.close()
except BrokenPipeError:
pass
# Restore the stdout values
self.stdout = saved_state.saved_self_stdout
sys.stdout = saved_state.saved_sys_stdout
# Check if we need to wait for the process being piped to
if self.cur_pipe_proc_reader is not None:
self.cur_pipe_proc_reader.wait()
# Restore cur_pipe_proc_reader. This always is done, regardless of whether this command redirected.
self.cur_pipe_proc_reader = saved_state.saved_pipe_proc_reader | python | {
"resource": ""
} |
q34004 | Cmd.cmd_func_name | train | def cmd_func_name(self, command: str) -> str:
"""Get the method name associated with a given command.
:param command: command to look up method name which implements it
:return: method name which implements the given command
"""
target = COMMAND_FUNC_PREFIX + command
return target if callable(getattr(self, target, None)) else '' | python | {
"resource": ""
} |
q34005 | Cmd._run_macro | train | def _run_macro(self, statement: Statement) -> bool:
"""
Resolve a macro and run the resulting string
:param statement: the parsed statement from the command line
:return: a flag indicating whether the interpretation of commands should stop
"""
from itertools import islice
if statement.command not in self.macros.keys():
raise KeyError('{} is not a macro'.format(statement.command))
macro = self.macros[statement.command]
# Make sure enough arguments were passed in
if len(statement.arg_list) < macro.minimum_arg_count:
self.perror("The macro '{}' expects at least {} argument(s)".format(statement.command,
macro.minimum_arg_count),
traceback_war=False)
return False
# Resolve the arguments in reverse and read their values from statement.argv since those
# are unquoted. Macro args should have been quoted when the macro was created.
resolved = macro.value
reverse_arg_list = sorted(macro.arg_list, key=lambda ma: ma.start_index, reverse=True)
for arg in reverse_arg_list:
if arg.is_escaped:
to_replace = '{{' + arg.number_str + '}}'
replacement = '{' + arg.number_str + '}'
else:
to_replace = '{' + arg.number_str + '}'
replacement = statement.argv[int(arg.number_str)]
parts = resolved.rsplit(to_replace, maxsplit=1)
resolved = parts[0] + replacement + parts[1]
# Append extra arguments and use statement.arg_list since these arguments need their quotes preserved
for arg in islice(statement.arg_list, macro.minimum_arg_count, None):
resolved += ' ' + arg
# Run the resolved command
return self.onecmd_plus_hooks(resolved) | python | {
"resource": ""
} |
q34006 | Cmd.pseudo_raw_input | train | def pseudo_raw_input(self, prompt: str) -> str:
"""Began life as a copy of cmd's cmdloop; like raw_input but
- accounts for changed stdin, stdout
- if input is a pipe (instead of a tty), look at self.echo
to decide whether to print the prompt and the input
"""
if self.use_rawinput:
try:
if sys.stdin.isatty():
# Wrap in try since terminal_lock may not be locked when this function is called from unit tests
try:
# A prompt is about to be drawn. Allow asynchronous changes to the terminal.
self.terminal_lock.release()
except RuntimeError:
pass
# Deal with the vagaries of readline and ANSI escape codes
safe_prompt = rl_make_safe_prompt(prompt)
line = input(safe_prompt)
else:
line = input()
if self.echo:
sys.stdout.write('{}{}\n'.format(prompt, line))
except EOFError:
line = 'eof'
finally:
if sys.stdin.isatty():
# The prompt is gone. Do not allow asynchronous changes to the terminal.
self.terminal_lock.acquire()
else:
if self.stdin.isatty():
# on a tty, print the prompt first, then read the line
self.poutput(prompt, end='')
self.stdout.flush()
line = self.stdin.readline()
if len(line) == 0:
line = 'eof'
else:
# we are reading from a pipe, read the line to see if there is
# anything there, if so, then decide whether to print the
# prompt or not
line = self.stdin.readline()
if len(line):
# we read something, output the prompt and the something
if self.echo:
self.poutput('{}{}'.format(prompt, line))
else:
line = 'eof'
return line.strip() | python | {
"resource": ""
} |
q34007 | Cmd._cmdloop | train | def _cmdloop(self) -> bool:
"""Repeatedly issue a prompt, accept input, parse an initial prefix
off the received input, and dispatch to action methods, passing them
the remainder of the line as argument.
This serves the same role as cmd.cmdloop().
:return: True implies the entire application should exit.
"""
# An almost perfect copy from Cmd; however, the pseudo_raw_input portion
# has been split out so that it can be called separately
if self.use_rawinput and self.completekey and rl_type != RlType.NONE:
# Set up readline for our tab completion needs
if rl_type == RlType.GNU:
# Set GNU readline's rl_basic_quote_characters to NULL so it won't automatically add a closing quote
# We don't need to worry about setting rl_completion_suppress_quote since we never declared
# rl_completer_quote_characters.
saved_basic_quotes = ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value
rl_basic_quote_characters.value = None
saved_completer = readline.get_completer()
readline.set_completer(self.complete)
# Break words on whitespace and quotes when tab completing
completer_delims = " \t\n" + ''.join(constants.QUOTES)
if self.allow_redirection:
# If redirection is allowed, then break words on those characters too
completer_delims += ''.join(constants.REDIRECTION_CHARS)
saved_delims = readline.get_completer_delims()
readline.set_completer_delims(completer_delims)
# Enable tab completion
readline.parse_and_bind(self.completekey + ": complete")
stop = False
try:
while not stop:
if self.cmdqueue:
# Run command out of cmdqueue if nonempty (populated by load command or commands at invocation)
line = self.cmdqueue.pop(0)
if self.echo and line != 'eos':
self.poutput('{}{}'.format(self.prompt, line))
else:
# Otherwise, read a command from stdin
try:
line = self.pseudo_raw_input(self.prompt)
except KeyboardInterrupt as ex:
if self.quit_on_sigint:
raise ex
else:
self.poutput('^C')
line = ''
# Run the command along with all associated pre and post hooks
stop = self.onecmd_plus_hooks(line)
finally:
if self.use_rawinput and self.completekey and rl_type != RlType.NONE:
# Restore what we changed in readline
readline.set_completer(saved_completer)
readline.set_completer_delims(saved_delims)
if rl_type == RlType.GNU:
readline.set_completion_display_matches_hook(None)
rl_basic_quote_characters.value = saved_basic_quotes
elif rl_type == RlType.PYREADLINE:
# noinspection PyUnresolvedReferences
readline.rl.mode._display_completions = orig_pyreadline_display
self.cmdqueue.clear()
self._script_dir.clear()
return stop | python | {
"resource": ""
} |
q34008 | Cmd.alias_create | train | def alias_create(self, args: argparse.Namespace) -> None:
"""Create or overwrite an alias"""
# Validate the alias name
valid, errmsg = self.statement_parser.is_valid_command(args.name)
if not valid:
self.perror("Invalid alias name: {}".format(errmsg), traceback_war=False)
return
if args.name in self.macros:
self.perror("Alias cannot have the same name as a macro", traceback_war=False)
return
utils.unquote_redirection_tokens(args.command_args)
# Build the alias value string
value = args.command
if args.command_args:
value += ' ' + ' '.join(args.command_args)
# Set the alias
result = "overwritten" if args.name in self.aliases else "created"
self.aliases[args.name] = value
self.poutput("Alias '{}' {}".format(args.name, result)) | python | {
"resource": ""
} |
q34009 | Cmd.alias_list | train | def alias_list(self, args: argparse.Namespace) -> None:
"""List some or all aliases"""
if args.name:
for cur_name in utils.remove_duplicates(args.name):
if cur_name in self.aliases:
self.poutput("alias create {} {}".format(cur_name, self.aliases[cur_name]))
else:
self.perror("Alias '{}' not found".format(cur_name), traceback_war=False)
else:
sorted_aliases = utils.alphabetical_sort(self.aliases)
for cur_alias in sorted_aliases:
self.poutput("alias create {} {}".format(cur_alias, self.aliases[cur_alias])) | python | {
"resource": ""
} |
q34010 | Cmd.macro_create | train | def macro_create(self, args: argparse.Namespace) -> None:
"""Create or overwrite a macro"""
# Validate the macro name
valid, errmsg = self.statement_parser.is_valid_command(args.name)
if not valid:
self.perror("Invalid macro name: {}".format(errmsg), traceback_war=False)
return
if args.name in self.get_all_commands():
self.perror("Macro cannot have the same name as a command", traceback_war=False)
return
if args.name in self.aliases:
self.perror("Macro cannot have the same name as an alias", traceback_war=False)
return
utils.unquote_redirection_tokens(args.command_args)
# Build the macro value string
value = args.command
if args.command_args:
value += ' ' + ' '.join(args.command_args)
# Find all normal arguments
arg_list = []
normal_matches = re.finditer(MacroArg.macro_normal_arg_pattern, value)
max_arg_num = 0
arg_nums = set()
while True:
try:
cur_match = normal_matches.__next__()
# Get the number string between the braces
cur_num_str = (re.findall(MacroArg.digit_pattern, cur_match.group())[0])
cur_num = int(cur_num_str)
if cur_num < 1:
self.perror("Argument numbers must be greater than 0", traceback_war=False)
return
arg_nums.add(cur_num)
if cur_num > max_arg_num:
max_arg_num = cur_num
arg_list.append(MacroArg(start_index=cur_match.start(), number_str=cur_num_str, is_escaped=False))
except StopIteration:
break
# Make sure the argument numbers are continuous
if len(arg_nums) != max_arg_num:
self.perror("Not all numbers between 1 and {} are present "
"in the argument placeholders".format(max_arg_num), traceback_war=False)
return
# Find all escaped arguments
escaped_matches = re.finditer(MacroArg.macro_escaped_arg_pattern, value)
while True:
try:
cur_match = escaped_matches.__next__()
# Get the number string between the braces
cur_num_str = re.findall(MacroArg.digit_pattern, cur_match.group())[0]
arg_list.append(MacroArg(start_index=cur_match.start(), number_str=cur_num_str, is_escaped=True))
except StopIteration:
break
# Set the macro
result = "overwritten" if args.name in self.macros else "created"
self.macros[args.name] = Macro(name=args.name, value=value, minimum_arg_count=max_arg_num, arg_list=arg_list)
self.poutput("Macro '{}' {}".format(args.name, result)) | python | {
"resource": ""
} |
q34011 | Cmd.macro_list | train | def macro_list(self, args: argparse.Namespace) -> None:
"""List some or all macros"""
if args.name:
for cur_name in utils.remove_duplicates(args.name):
if cur_name in self.macros:
self.poutput("macro create {} {}".format(cur_name, self.macros[cur_name].value))
else:
self.perror("Macro '{}' not found".format(cur_name), traceback_war=False)
else:
sorted_macros = utils.alphabetical_sort(self.macros)
for cur_macro in sorted_macros:
self.poutput("macro create {} {}".format(cur_macro, self.macros[cur_macro].value)) | python | {
"resource": ""
} |
q34012 | Cmd.complete_help_command | train | def complete_help_command(self, text: str, line: str, begidx: int, endidx: int) -> List[str]:
"""Completes the command argument of help"""
# Complete token against topics and visible commands
topics = set(self.get_help_topics())
visible_commands = set(self.get_visible_commands())
strs_to_match = list(topics | visible_commands)
return self.basic_complete(text, line, begidx, endidx, strs_to_match) | python | {
"resource": ""
} |
q34013 | Cmd.complete_help_subcommand | train | def complete_help_subcommand(self, text: str, line: str, begidx: int, endidx: int) -> List[str]:
"""Completes the subcommand argument of help"""
# Get all tokens through the one being completed
tokens, _ = self.tokens_for_completion(line, begidx, endidx)
if not tokens:
return []
# Must have at least 3 args for 'help command sub-command'
if len(tokens) < 3:
return []
# Find where the command is by skipping past any flags
cmd_index = 1
for cur_token in tokens[cmd_index:]:
if not cur_token.startswith('-'):
break
cmd_index += 1
if cmd_index >= len(tokens):
return []
command = tokens[cmd_index]
matches = []
# Check if this is a command with an argparse function
func = self.cmd_func(command)
if func and hasattr(func, 'argparser'):
completer = AutoCompleter(getattr(func, 'argparser'), self)
matches = completer.complete_command_help(tokens[cmd_index:], text, line, begidx, endidx)
return matches | python | {
"resource": ""
} |
q34014 | Cmd.do_help | train | def do_help(self, args: argparse.Namespace) -> None:
"""List available commands or provide detailed help for a specific command"""
if not args.command or args.verbose:
self._help_menu(args.verbose)
else:
# Getting help for a specific command
func = self.cmd_func(args.command)
help_func = getattr(self, HELP_FUNC_PREFIX + args.command, None)
# If the command function uses argparse, then use argparse's help
if func and hasattr(func, 'argparser'):
completer = AutoCompleter(getattr(func, 'argparser'), self)
tokens = [args.command] + args.subcommand
self.poutput(completer.format_help(tokens))
# If there is no help information then print an error
elif help_func is None and (func is None or not func.__doc__):
err_msg = self.help_error.format(args.command)
self.decolorized_write(sys.stderr, "{}\n".format(err_msg))
# Otherwise delegate to cmd base class do_help()
else:
super().do_help(args.command) | python | {
"resource": ""
} |
q34015 | Cmd._help_menu | train | def _help_menu(self, verbose: bool = False) -> None:
"""Show a list of commands which help can be displayed for.
"""
# Get a sorted list of help topics
help_topics = utils.alphabetical_sort(self.get_help_topics())
# Get a sorted list of visible command names
visible_commands = utils.alphabetical_sort(self.get_visible_commands())
cmds_doc = []
cmds_undoc = []
cmds_cats = {}
for command in visible_commands:
func = self.cmd_func(command)
has_help_func = False
if command in help_topics:
# Prevent the command from showing as both a command and help topic in the output
help_topics.remove(command)
# Non-argparse commands can have help_functions for their documentation
if not hasattr(func, 'argparser'):
has_help_func = True
if hasattr(func, HELP_CATEGORY):
category = getattr(func, HELP_CATEGORY)
cmds_cats.setdefault(category, [])
cmds_cats[category].append(command)
elif func.__doc__ or has_help_func:
cmds_doc.append(command)
else:
cmds_undoc.append(command)
if len(cmds_cats) == 0:
# No categories found, fall back to standard behavior
self.poutput("{}\n".format(str(self.doc_leader)))
self._print_topics(self.doc_header, cmds_doc, verbose)
else:
# Categories found, Organize all commands by category
self.poutput('{}\n'.format(str(self.doc_leader)))
self.poutput('{}\n\n'.format(str(self.doc_header)))
for category in sorted(cmds_cats.keys()):
self._print_topics(category, cmds_cats[category], verbose)
self._print_topics('Other', cmds_doc, verbose)
self.print_topics(self.misc_header, help_topics, 15, 80)
self.print_topics(self.undoc_header, cmds_undoc, 15, 80) | python | {
"resource": ""
} |
q34016 | Cmd._print_topics | train | def _print_topics(self, header: str, cmds: List[str], verbose: bool) -> None:
"""Customized version of print_topics that can switch between verbose or traditional output"""
import io
if cmds:
if not verbose:
self.print_topics(header, cmds, 15, 80)
else:
self.stdout.write('{}\n'.format(str(header)))
widest = 0
# measure the commands
for command in cmds:
width = utils.ansi_safe_wcswidth(command)
if width > widest:
widest = width
# add a 4-space pad
widest += 4
if widest < 20:
widest = 20
if self.ruler:
self.stdout.write('{:{ruler}<{width}}\n'.format('', ruler=self.ruler, width=80))
# Try to get the documentation string for each command
topics = self.get_help_topics()
for command in cmds:
cmd_func = self.cmd_func(command)
# Non-argparse commands can have help_functions for their documentation
if not hasattr(cmd_func, 'argparser') and command in topics:
help_func = getattr(self, HELP_FUNC_PREFIX + command)
result = io.StringIO()
# try to redirect system stdout
with redirect_stdout(result):
# save our internal stdout
stdout_orig = self.stdout
try:
# redirect our internal stdout
self.stdout = result
help_func()
finally:
# restore internal stdout
self.stdout = stdout_orig
doc = result.getvalue()
else:
doc = cmd_func.__doc__
# Attempt to locate the first documentation block
if not doc:
doc_block = ['']
else:
doc_block = []
found_first = False
for doc_line in doc.splitlines():
stripped_line = doc_line.strip()
# Don't include :param type lines
if stripped_line.startswith(':'):
if found_first:
break
elif stripped_line:
doc_block.append(stripped_line)
found_first = True
elif found_first:
break
for doc_line in doc_block:
self.stdout.write('{: <{col_width}}{doc}\n'.format(command,
col_width=widest,
doc=doc_line))
command = ''
self.stdout.write("\n") | python | {
"resource": ""
} |
q34017 | Cmd.do_shortcuts | train | def do_shortcuts(self, _: argparse.Namespace) -> None:
"""List available shortcuts"""
result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in sorted(self.shortcuts))
self.poutput("Shortcuts for other commands:\n{}\n".format(result)) | python | {
"resource": ""
} |
q34018 | Cmd.do_quit | train | def do_quit(self, _: argparse.Namespace) -> bool:
"""Exit this application"""
self._should_quit = True
return self._STOP_AND_EXIT | python | {
"resource": ""
} |
q34019 | Cmd.select | train | def select(self, opts: Union[str, List[str], List[Tuple[Any, Optional[str]]]],
prompt: str = 'Your choice? ') -> str:
"""Presents a numbered menu to the user. Modeled after
the bash shell's SELECT. Returns the item chosen.
Argument ``opts`` can be:
| a single string -> will be split into one-word options
| a list of strings -> will be offered as options
| a list of tuples -> interpreted as (value, text), so
that the return value can differ from
the text advertised to the user """
local_opts = opts
if isinstance(opts, str):
local_opts = list(zip(opts.split(), opts.split()))
fulloptions = []
for opt in local_opts:
if isinstance(opt, str):
fulloptions.append((opt, opt))
else:
try:
fulloptions.append((opt[0], opt[1]))
except IndexError:
fulloptions.append((opt[0], opt[0]))
for (idx, (_, text)) in enumerate(fulloptions):
self.poutput(' %2d. %s\n' % (idx + 1, text))
while True:
safe_prompt = rl_make_safe_prompt(prompt)
response = input(safe_prompt)
if rl_type != RlType.NONE:
hlen = readline.get_current_history_length()
if hlen >= 1 and response != '':
readline.remove_history_item(hlen - 1)
try:
choice = int(response)
if choice < 1:
raise IndexError
result = fulloptions[choice - 1][0]
break
except (ValueError, IndexError):
self.poutput("{!r} isn't a valid choice. Pick a number between 1 and {}:\n".format(response,
len(fulloptions)))
return result | python | {
"resource": ""
} |
q34020 | Cmd.show | train | def show(self, args: argparse.Namespace, parameter: str = '') -> None:
"""Shows current settings of parameters.
:param args: argparse parsed arguments from the set command
:param parameter: optional search parameter
"""
param = utils.norm_fold(parameter.strip())
result = {}
maxlen = 0
for p in self.settable:
if (not param) or p.startswith(param):
result[p] = '{}: {}'.format(p, str(getattr(self, p)))
maxlen = max(maxlen, len(result[p]))
if result:
for p in sorted(result):
if args.long:
self.poutput('{} # {}'.format(result[p].ljust(maxlen), self.settable[p]))
else:
self.poutput(result[p])
# If user has requested to see all settings, also show read-only settings
if args.all:
self.poutput('\nRead only settings:{}'.format(self.cmdenvironment()))
else:
self.perror("Parameter '{}' not supported (type 'set' for list of parameters).".format(param),
traceback_war=False) | python | {
"resource": ""
} |
q34021 | Cmd.do_set | train | def do_set(self, args: argparse.Namespace) -> None:
"""Set a settable parameter or show current settings of parameters"""
# Check if param was passed in
if not args.param:
return self.show(args)
param = utils.norm_fold(args.param.strip())
# Check if value was passed in
if not args.value:
return self.show(args, param)
value = args.value
# Check if param points to just one settable
if param not in self.settable:
hits = [p for p in self.settable if p.startswith(param)]
if len(hits) == 1:
param = hits[0]
else:
return self.show(args, param)
# Update the settable's value
current_value = getattr(self, param)
value = utils.cast(current_value, value)
setattr(self, param, value)
self.poutput('{} - was: {}\nnow: {}\n'.format(param, current_value, value))
# See if we need to call a change hook for this settable
if current_value != value:
onchange_hook = getattr(self, '_onchange_{}'.format(param), None)
if onchange_hook is not None:
onchange_hook(old=current_value, new=value) | python | {
"resource": ""
} |
q34022 | Cmd.do_shell | train | def do_shell(self, args: argparse.Namespace) -> None:
"""Execute a command as if at the OS prompt"""
import subprocess
# Create a list of arguments to shell
tokens = [args.command] + args.command_args
# Support expanding ~ in quoted paths
for index, _ in enumerate(tokens):
if tokens[index]:
# Check if the token is quoted. Since parsing already passed, there isn't
# an unclosed quote. So we only need to check the first character.
first_char = tokens[index][0]
if first_char in constants.QUOTES:
tokens[index] = utils.strip_quotes(tokens[index])
tokens[index] = os.path.expanduser(tokens[index])
# Restore the quotes
if first_char in constants.QUOTES:
tokens[index] = first_char + tokens[index] + first_char
expanded_command = ' '.join(tokens)
# Prevent KeyboardInterrupts while in the shell process. The shell process will
# still receive the SIGINT since it is in the same process group as us.
with self.sigint_protection:
# For any stream that is a StdSim, we will use a pipe so we can capture its output
proc = subprocess.Popen(expanded_command,
stdout=subprocess.PIPE if isinstance(self.stdout, utils.StdSim) else self.stdout,
stderr=subprocess.PIPE if isinstance(sys.stderr, utils.StdSim) else sys.stderr,
shell=True)
proc_reader = utils.ProcReader(proc, self.stdout, sys.stderr)
proc_reader.wait() | python | {
"resource": ""
} |
q34023 | Cmd._reset_py_display | train | def _reset_py_display() -> None:
"""
Resets the dynamic objects in the sys module that the py and ipy consoles fight over.
When a Python console starts it adopts certain display settings if they've already been set.
If an ipy console has previously been run, then py uses its settings and ends up looking
like an ipy console in terms of prompt and exception text. This method forces the Python
console to create its own display settings since they won't exist.
IPython does not have this problem since it always overwrites the display settings when it
is run. Therefore this method only needs to be called before creating a Python console.
"""
# Delete any prompts that have been set
attributes = ['ps1', 'ps2', 'ps3']
for cur_attr in attributes:
try:
del sys.__dict__[cur_attr]
except KeyError:
pass
# Reset functions
sys.displayhook = sys.__displayhook__
sys.excepthook = sys.__excepthook__ | python | {
"resource": ""
} |
q34024 | Cmd.do_pyscript | train | def do_pyscript(self, args: argparse.Namespace) -> bool:
"""Run a Python script file inside the console"""
script_path = os.path.expanduser(args.script_path)
py_return = False
# Save current command line arguments
orig_args = sys.argv
try:
# Overwrite sys.argv to allow the script to take command line arguments
sys.argv = [script_path] + args.script_arguments
# Run the script - use repr formatting to escape things which
# need to be escaped to prevent issues on Windows
py_return = self.do_py("run({!r})".format(script_path))
except KeyboardInterrupt:
pass
finally:
# Restore command line arguments to original state
sys.argv = orig_args
return py_return | python | {
"resource": ""
} |
q34025 | Cmd._generate_transcript | train | def _generate_transcript(self, history: List[Union[HistoryItem, str]], transcript_file: str) -> None:
"""Generate a transcript file from a given history of commands."""
import io
# Validate the transcript file path to make sure directory exists and write access is available
transcript_path = os.path.abspath(os.path.expanduser(transcript_file))
transcript_dir = os.path.dirname(transcript_path)
if not os.path.isdir(transcript_dir) or not os.access(transcript_dir, os.W_OK):
self.perror("{!r} is not a directory or you don't have write access".format(transcript_dir),
traceback_war=False)
return
try:
with self.sigint_protection:
# Disable echo while we manually redirect stdout to a StringIO buffer
saved_echo = self.echo
saved_stdout = self.stdout
self.echo = False
# The problem with supporting regular expressions in transcripts
# is that they shouldn't be processed in the command, just the output.
# In addition, when we generate a transcript, any slashes in the output
# are not really intended to indicate regular expressions, so they should
# be escaped.
#
# We have to jump through some hoops here in order to catch the commands
# separately from the output and escape the slashes in the output.
transcript = ''
for history_item in history:
# build the command, complete with prompts. When we replay
# the transcript, we look for the prompts to separate
# the command from the output
first = True
command = ''
for line in history_item.splitlines():
if first:
command += '{}{}\n'.format(self.prompt, line)
first = False
else:
command += '{}{}\n'.format(self.continuation_prompt, line)
transcript += command
# create a new string buffer and set it to stdout to catch the output
# of the command
membuf = io.StringIO()
self.stdout = membuf
# then run the command and let the output go into our buffer
self.onecmd_plus_hooks(history_item)
# rewind the buffer to the beginning
membuf.seek(0)
# get the output out of the buffer
output = membuf.read()
# and add the regex-escaped output to the transcript
transcript += output.replace('/', r'\/')
finally:
with self.sigint_protection:
# Restore altered attributes to their original state
self.echo = saved_echo
self.stdout = saved_stdout
# finally, we can write the transcript out to the file
try:
with open(transcript_file, 'w') as fout:
fout.write(transcript)
except OSError as ex:
self.perror('Failed to save transcript: {}'.format(ex), traceback_war=False)
else:
# and let the user know what we did
if len(history) > 1:
plural = 'commands and their outputs'
else:
plural = 'command and its output'
msg = '{} {} saved to transcript file {!r}'
self.pfeedback(msg.format(len(history), plural, transcript_file)) | python | {
"resource": ""
} |
q34026 | Cmd.do_edit | train | def do_edit(self, args: argparse.Namespace) -> None:
"""Edit a file in a text editor"""
if not self.editor:
raise EnvironmentError("Please use 'set editor' to specify your text editing program of choice.")
command = utils.quote_string_if_needed(os.path.expanduser(self.editor))
if args.file_path:
command += " " + utils.quote_string_if_needed(os.path.expanduser(args.file_path))
self.do_shell(command) | python | {
"resource": ""
} |
q34027 | Cmd.do_eos | train | def do_eos(self, _: argparse.Namespace) -> None:
"""Handle cleanup when a script has finished executing"""
if self._script_dir:
self._script_dir.pop() | python | {
"resource": ""
} |
q34028 | Cmd.async_alert | train | def async_alert(self, alert_msg: str, new_prompt: Optional[str] = None) -> None: # pragma: no cover
"""
Display an important message to the user while they are at the prompt in between commands.
To the user it appears as if an alert message is printed above the prompt and their current input
text and cursor location is left alone.
IMPORTANT: This function will not print an alert unless it can acquire self.terminal_lock to ensure
a prompt is onscreen. Therefore it is best to acquire the lock before calling this function
to guarantee the alert prints.
:param alert_msg: the message to display to the user
:param new_prompt: if you also want to change the prompt that is displayed, then include it here
see async_update_prompt() docstring for guidance on updating a prompt
:raises RuntimeError if called while another thread holds terminal_lock
"""
if not (vt100_support and self.use_rawinput):
return
import shutil
import colorama.ansi as ansi
from colorama import Cursor
# Sanity check that can't fail if self.terminal_lock was acquired before calling this function
if self.terminal_lock.acquire(blocking=False):
# Figure out what prompt is displaying
current_prompt = self.continuation_prompt if self.at_continuation_prompt else self.prompt
# Only update terminal if there are changes
update_terminal = False
if alert_msg:
alert_msg += '\n'
update_terminal = True
# Set the prompt if its changed
if new_prompt is not None and new_prompt != self.prompt:
self.prompt = new_prompt
# If we aren't at a continuation prompt, then it's OK to update it
if not self.at_continuation_prompt:
rl_set_prompt(self.prompt)
update_terminal = True
if update_terminal:
# Get the size of the terminal
terminal_size = shutil.get_terminal_size()
# Split the prompt lines since it can contain newline characters.
prompt_lines = current_prompt.splitlines()
# Calculate how many terminal lines are taken up by all prompt lines except for the last one.
# That will be included in the input lines calculations since that is where the cursor is.
num_prompt_terminal_lines = 0
for line in prompt_lines[:-1]:
line_width = utils.ansi_safe_wcswidth(line)
num_prompt_terminal_lines += int(line_width / terminal_size.columns) + 1
# Now calculate how many terminal lines are take up by the input
last_prompt_line = prompt_lines[-1]
last_prompt_line_width = utils.ansi_safe_wcswidth(last_prompt_line)
input_width = last_prompt_line_width + utils.ansi_safe_wcswidth(readline.get_line_buffer())
num_input_terminal_lines = int(input_width / terminal_size.columns) + 1
# Get the cursor's offset from the beginning of the first input line
cursor_input_offset = last_prompt_line_width + rl_get_point()
# Calculate what input line the cursor is on
cursor_input_line = int(cursor_input_offset / terminal_size.columns) + 1
# Create a string that when printed will clear all input lines and display the alert
terminal_str = ''
# Move the cursor down to the last input line
if cursor_input_line != num_input_terminal_lines:
terminal_str += Cursor.DOWN(num_input_terminal_lines - cursor_input_line)
# Clear each line from the bottom up so that the cursor ends up on the first prompt line
total_lines = num_prompt_terminal_lines + num_input_terminal_lines
terminal_str += (ansi.clear_line() + Cursor.UP(1)) * (total_lines - 1)
# Clear the first prompt line
terminal_str += ansi.clear_line()
# Move the cursor to the beginning of the first prompt line and print the alert
terminal_str += '\r' + alert_msg
if rl_type == RlType.GNU:
sys.stderr.write(terminal_str)
elif rl_type == RlType.PYREADLINE:
# noinspection PyUnresolvedReferences
readline.rl.mode.console.write(terminal_str)
# Redraw the prompt and input lines
rl_force_redisplay()
self.terminal_lock.release()
else:
raise RuntimeError("another thread holds terminal_lock") | python | {
"resource": ""
} |
q34029 | Cmd.set_window_title | train | def set_window_title(self, title: str) -> None: # pragma: no cover
"""
Set the terminal window title
IMPORTANT: This function will not set the title unless it can acquire self.terminal_lock to avoid
writing to stderr while a command is running. Therefore it is best to acquire the lock
before calling this function to guarantee the title changes.
:param title: the new window title
:raises RuntimeError if called while another thread holds terminal_lock
"""
if not vt100_support:
return
# Sanity check that can't fail if self.terminal_lock was acquired before calling this function
if self.terminal_lock.acquire(blocking=False):
try:
import colorama.ansi as ansi
sys.stderr.write(ansi.set_title(title))
except AttributeError:
# Debugging in Pycharm has issues with setting terminal title
pass
finally:
self.terminal_lock.release()
else:
raise RuntimeError("another thread holds terminal_lock") | python | {
"resource": ""
} |
q34030 | Cmd._initialize_plugin_system | train | def _initialize_plugin_system(self) -> None:
"""Initialize the plugin system"""
self._preloop_hooks = []
self._postloop_hooks = []
self._postparsing_hooks = []
self._precmd_hooks = []
self._postcmd_hooks = []
self._cmdfinalization_hooks = [] | python | {
"resource": ""
} |
q34031 | Cmd._validate_callable_param_count | train | def _validate_callable_param_count(cls, func: Callable, count: int) -> None:
"""Ensure a function has the given number of parameters."""
signature = inspect.signature(func)
# validate that the callable has the right number of parameters
nparam = len(signature.parameters)
if nparam != count:
raise TypeError('{} has {} positional arguments, expected {}'.format(
func.__name__,
nparam,
count,
)) | python | {
"resource": ""
} |
q34032 | Cmd._validate_prepostloop_callable | train | def _validate_prepostloop_callable(cls, func: Callable[[None], None]) -> None:
"""Check parameter and return types for preloop and postloop hooks."""
cls._validate_callable_param_count(func, 0)
# make sure there is no return notation
signature = inspect.signature(func)
if signature.return_annotation is not None:
raise TypeError("{} must declare return a return type of 'None'".format(
func.__name__,
)) | python | {
"resource": ""
} |
q34033 | Cmd.register_preloop_hook | train | def register_preloop_hook(self, func: Callable[[None], None]) -> None:
"""Register a function to be called at the beginning of the command loop."""
self._validate_prepostloop_callable(func)
self._preloop_hooks.append(func) | python | {
"resource": ""
} |
q34034 | Cmd.register_postloop_hook | train | def register_postloop_hook(self, func: Callable[[None], None]) -> None:
"""Register a function to be called at the end of the command loop."""
self._validate_prepostloop_callable(func)
self._postloop_hooks.append(func) | python | {
"resource": ""
} |
q34035 | Cmd.register_postparsing_hook | train | def register_postparsing_hook(self, func: Callable[[plugin.PostparsingData], plugin.PostparsingData]) -> None:
"""Register a function to be called after parsing user input but before running the command"""
self._validate_postparsing_callable(func)
self._postparsing_hooks.append(func) | python | {
"resource": ""
} |
q34036 | Cmd._validate_prepostcmd_hook | train | def _validate_prepostcmd_hook(cls, func: Callable, data_type: Type) -> None:
"""Check parameter and return types for pre and post command hooks."""
signature = inspect.signature(func)
# validate that the callable has the right number of parameters
cls._validate_callable_param_count(func, 1)
# validate the parameter has the right annotation
paramname = list(signature.parameters.keys())[0]
param = signature.parameters[paramname]
if param.annotation != data_type:
raise TypeError('argument 1 of {} has incompatible type {}, expected {}'.format(
func.__name__,
param.annotation,
data_type,
))
# validate the return value has the right annotation
if signature.return_annotation == signature.empty:
raise TypeError('{} does not have a declared return type, expected {}'.format(
func.__name__,
data_type,
))
if signature.return_annotation != data_type:
raise TypeError('{} has incompatible return type {}, expected {}'.format(
func.__name__,
signature.return_annotation,
data_type,
)) | python | {
"resource": ""
} |
q34037 | Cmd.register_precmd_hook | train | def register_precmd_hook(self, func: Callable[[plugin.PrecommandData], plugin.PrecommandData]) -> None:
"""Register a hook to be called before the command function."""
self._validate_prepostcmd_hook(func, plugin.PrecommandData)
self._precmd_hooks.append(func) | python | {
"resource": ""
} |
q34038 | Cmd.register_postcmd_hook | train | def register_postcmd_hook(self, func: Callable[[plugin.PostcommandData], plugin.PostcommandData]) -> None:
"""Register a hook to be called after the command function."""
self._validate_prepostcmd_hook(func, plugin.PostcommandData)
self._postcmd_hooks.append(func) | python | {
"resource": ""
} |
q34039 | Cmd._validate_cmdfinalization_callable | train | def _validate_cmdfinalization_callable(cls, func: Callable[[plugin.CommandFinalizationData],
plugin.CommandFinalizationData]) -> None:
"""Check parameter and return types for command finalization hooks."""
cls._validate_callable_param_count(func, 1)
signature = inspect.signature(func)
_, param = list(signature.parameters.items())[0]
if param.annotation != plugin.CommandFinalizationData:
raise TypeError("{} must have one parameter declared with type "
"'cmd2.plugin.CommandFinalizationData'".format(func.__name__))
if signature.return_annotation != plugin.CommandFinalizationData:
raise TypeError("{} must declare return a return type of "
"'cmd2.plugin.CommandFinalizationData'".format(func.__name__)) | python | {
"resource": ""
} |
q34040 | Cmd.register_cmdfinalization_hook | train | def register_cmdfinalization_hook(self, func: Callable[[plugin.CommandFinalizationData],
plugin.CommandFinalizationData]) -> None:
"""Register a hook to be called after a command is completed, whether it completes successfully or not."""
self._validate_cmdfinalization_callable(func)
self._cmdfinalization_hooks.append(func) | python | {
"resource": ""
} |
q34041 | StatementParser.is_valid_command | train | def is_valid_command(self, word: str) -> Tuple[bool, str]:
"""Determine whether a word is a valid name for a command.
Commands can not include redirection characters, whitespace,
or termination characters. They also cannot start with a
shortcut.
If word is not a valid command, return False and error text
This string is suitable for inclusion in an error message of your
choice:
valid, errmsg = statement_parser.is_valid_command('>')
if not valid:
errmsg = "Alias {}".format(errmsg)
"""
valid = False
if not word:
return False, 'cannot be an empty string'
if word.startswith(constants.COMMENT_CHAR):
return False, 'cannot start with the comment character'
for (shortcut, _) in self.shortcuts:
if word.startswith(shortcut):
# Build an error string with all shortcuts listed
errmsg = 'cannot start with a shortcut: '
errmsg += ', '.join(shortcut for (shortcut, _) in self.shortcuts)
return False, errmsg
errmsg = 'cannot contain: whitespace, quotes, '
errchars = []
errchars.extend(constants.REDIRECTION_CHARS)
errchars.extend(self.terminators)
errmsg += ', '.join([shlex.quote(x) for x in errchars])
match = self._command_pattern.search(word)
if match:
if word == match.group(1):
valid = True
errmsg = ''
return valid, errmsg | python | {
"resource": ""
} |
q34042 | StatementParser.tokenize | train | def tokenize(self, line: str, expand: bool = True) -> List[str]:
"""
Lex a string into a list of tokens. Shortcuts and aliases are expanded and comments are removed
:param line: the command line being lexed
:param expand: If True, then aliases and shortcuts will be expanded.
Set this to False if no expansion should occur because the command name is already known.
Otherwise the command could be expanded if it matched an alias name. This is for cases where
a do_* method was called manually (e.g do_help('alias').
:return: A list of tokens
:raises ValueError if there are unclosed quotation marks.
"""
# expand shortcuts and aliases
if expand:
line = self._expand(line)
# check if this line is a comment
if line.lstrip().startswith(constants.COMMENT_CHAR):
return []
# split on whitespace
tokens = shlex_split(line)
# custom lexing
tokens = self._split_on_punctuation(tokens)
return tokens | python | {
"resource": ""
} |
q34043 | StatementParser.parse | train | def parse(self, line: str, expand: bool = True) -> Statement:
"""
Tokenize the input and parse it into a Statement object, stripping
comments, expanding aliases and shortcuts, and extracting output
redirection directives.
:param line: the command line being parsed
:param expand: If True, then aliases and shortcuts will be expanded.
Set this to False if no expansion should occur because the command name is already known.
Otherwise the command could be expanded if it matched an alias name. This is for cases where
a do_* method was called manually (e.g do_help('alias').
:return: A parsed Statement
:raises ValueError if there are unclosed quotation marks
"""
# handle the special case/hardcoded terminator of a blank line
# we have to do this before we tokenize because tokenizing
# destroys all unquoted whitespace in the input
terminator = ''
if line[-1:] == constants.LINE_FEED:
terminator = constants.LINE_FEED
command = ''
args = ''
arg_list = []
# lex the input into a list of tokens
tokens = self.tokenize(line, expand)
# of the valid terminators, find the first one to occur in the input
terminator_pos = len(tokens) + 1
for pos, cur_token in enumerate(tokens):
for test_terminator in self.terminators:
if cur_token.startswith(test_terminator):
terminator_pos = pos
terminator = test_terminator
# break the inner loop, and we want to break the
# outer loop too
break
else:
# this else clause is only run if the inner loop
# didn't execute a break. If it didn't, then
# continue to the next iteration of the outer loop
continue
# inner loop was broken, break the outer
break
if terminator:
if terminator == constants.LINE_FEED:
terminator_pos = len(tokens) + 1
# everything before the first terminator is the command and the args
(command, args) = self._command_and_args(tokens[:terminator_pos])
arg_list = tokens[1:terminator_pos]
# we will set the suffix later
# remove all the tokens before and including the terminator
tokens = tokens[terminator_pos + 1:]
else:
(testcommand, testargs) = self._command_and_args(tokens)
if testcommand in self.multiline_commands:
# no terminator on this line but we have a multiline command
# everything else on the line is part of the args
# because redirectors can only be after a terminator
command = testcommand
args = testargs
arg_list = tokens[1:]
tokens = []
# check for a pipe to a shell process
# if there is a pipe, everything after the pipe needs to be passed
# to the shell, even redirected output
# this allows '(Cmd) say hello | wc > countit.txt'
try:
# find the first pipe if it exists
pipe_pos = tokens.index(constants.REDIRECTION_PIPE)
# save everything after the first pipe as tokens
pipe_to = tokens[pipe_pos + 1:]
for pos, cur_token in enumerate(pipe_to):
unquoted_token = utils.strip_quotes(cur_token)
pipe_to[pos] = os.path.expanduser(unquoted_token)
# remove all the tokens after the pipe
tokens = tokens[:pipe_pos]
except ValueError:
# no pipe in the tokens
pipe_to = []
# check for output redirect
output = ''
output_to = ''
try:
output_pos = tokens.index(constants.REDIRECTION_OUTPUT)
output = constants.REDIRECTION_OUTPUT
# Check if we are redirecting to a file
if len(tokens) > output_pos + 1:
unquoted_path = utils.strip_quotes(tokens[output_pos + 1])
output_to = os.path.expanduser(unquoted_path)
# remove all the tokens after the output redirect
tokens = tokens[:output_pos]
except ValueError:
pass
try:
output_pos = tokens.index(constants.REDIRECTION_APPEND)
output = constants.REDIRECTION_APPEND
# Check if we are redirecting to a file
if len(tokens) > output_pos + 1:
unquoted_path = utils.strip_quotes(tokens[output_pos + 1])
output_to = os.path.expanduser(unquoted_path)
# remove all tokens after the output redirect
tokens = tokens[:output_pos]
except ValueError:
pass
if terminator:
# whatever is left is the suffix
suffix = ' '.join(tokens)
else:
# no terminator, so whatever is left is the command and the args
suffix = ''
if not command:
# command could already have been set, if so, don't set it again
(command, args) = self._command_and_args(tokens)
arg_list = tokens[1:]
# set multiline
if command in self.multiline_commands:
multiline_command = command
else:
multiline_command = ''
# build the statement
statement = Statement(args,
raw=line,
command=command,
arg_list=arg_list,
multiline_command=multiline_command,
terminator=terminator,
suffix=suffix,
pipe_to=pipe_to,
output=output,
output_to=output_to,
)
return statement | python | {
"resource": ""
} |
q34044 | StatementParser.parse_command_only | train | def parse_command_only(self, rawinput: str) -> Statement:
"""Partially parse input into a Statement object.
The command is identified, and shortcuts and aliases are expanded.
Multiline commands are identified, but terminators and output
redirection are not parsed.
This method is used by tab completion code and therefore must not
generate an exception if there are unclosed quotes.
The `Statement` object returned by this method can at most contain values
in the following attributes:
- args
- raw
- command
- multiline_command
`Statement.args` includes all output redirection clauses and command
terminators.
Different from parse(), this method does not remove redundant whitespace
within args. However, it does ensure args has no leading or trailing
whitespace.
"""
# expand shortcuts and aliases
line = self._expand(rawinput)
command = ''
args = ''
match = self._command_pattern.search(line)
if match:
# we got a match, extract the command
command = match.group(1)
# take everything from the end of the first match group to
# the end of the line as the arguments (stripping leading
# and trailing spaces)
args = line[match.end(1):].strip()
# if the command is empty that means the input was either empty
# or something weird like '>'. args should be empty if we couldn't
# parse a command
if not command or not args:
args = ''
# set multiline
if command in self.multiline_commands:
multiline_command = command
else:
multiline_command = ''
# build the statement
statement = Statement(args,
raw=rawinput,
command=command,
multiline_command=multiline_command,
)
return statement | python | {
"resource": ""
} |
q34045 | StatementParser._expand | train | def _expand(self, line: str) -> str:
"""Expand shortcuts and aliases"""
# expand aliases
# make a copy of aliases so we can edit it
tmp_aliases = list(self.aliases.keys())
keep_expanding = bool(tmp_aliases)
while keep_expanding:
for cur_alias in tmp_aliases:
keep_expanding = False
# apply our regex to line
match = self._command_pattern.search(line)
if match:
# we got a match, extract the command
command = match.group(1)
if command and command == cur_alias:
# rebuild line with the expanded alias
line = self.aliases[cur_alias] + match.group(2) + line[match.end(2):]
tmp_aliases.remove(cur_alias)
keep_expanding = bool(tmp_aliases)
break
# expand shortcuts
for (shortcut, expansion) in self.shortcuts:
if line.startswith(shortcut):
# If the next character after the shortcut isn't a space, then insert one
shortcut_len = len(shortcut)
if len(line) == shortcut_len or line[shortcut_len] != ' ':
expansion += ' '
# Expand the shortcut
line = line.replace(shortcut, expansion, 1)
break
return line | python | {
"resource": ""
} |
q34046 | StatementParser._command_and_args | train | def _command_and_args(tokens: List[str]) -> Tuple[str, str]:
"""Given a list of tokens, return a tuple of the command
and the args as a string.
"""
command = ''
args = ''
if tokens:
command = tokens[0]
if len(tokens) > 1:
args = ' '.join(tokens[1:])
return command, args | python | {
"resource": ""
} |
q34047 | StatementParser._split_on_punctuation | train | def _split_on_punctuation(self, tokens: List[str]) -> List[str]:
"""Further splits tokens from a command line using punctuation characters
Punctuation characters are treated as word breaks when they are in
unquoted strings. Each run of punctuation characters is treated as a
single token.
:param tokens: the tokens as parsed by shlex
:return: the punctuated tokens
"""
punctuation = []
punctuation.extend(self.terminators)
if self.allow_redirection:
punctuation.extend(constants.REDIRECTION_CHARS)
punctuated_tokens = []
for cur_initial_token in tokens:
# Save tokens up to 1 character in length or quoted tokens. No need to parse these.
if len(cur_initial_token) <= 1 or cur_initial_token[0] in constants.QUOTES:
punctuated_tokens.append(cur_initial_token)
continue
# Iterate over each character in this token
cur_index = 0
cur_char = cur_initial_token[cur_index]
# Keep track of the token we are building
new_token = ''
while True:
if cur_char not in punctuation:
# Keep appending to new_token until we hit a punctuation char
while cur_char not in punctuation:
new_token += cur_char
cur_index += 1
if cur_index < len(cur_initial_token):
cur_char = cur_initial_token[cur_index]
else:
break
else:
cur_punc = cur_char
# Keep appending to new_token until we hit something other than cur_punc
while cur_char == cur_punc:
new_token += cur_char
cur_index += 1
if cur_index < len(cur_initial_token):
cur_char = cur_initial_token[cur_index]
else:
break
# Save the new token
punctuated_tokens.append(new_token)
new_token = ''
# Check if we've viewed all characters
if cur_index >= len(cur_initial_token):
break
return punctuated_tokens | python | {
"resource": ""
} |
q34048 | ArgumentAndOptionPrinter.do_aprint | train | def do_aprint(self, statement):
"""Print the argument string this basic command is called with."""
self.poutput('aprint was called with argument: {!r}'.format(statement))
self.poutput('statement.raw = {!r}'.format(statement.raw))
self.poutput('statement.argv = {!r}'.format(statement.argv))
self.poutput('statement.command = {!r}'.format(statement.command)) | python | {
"resource": ""
} |
q34049 | HelpCategories.do_disable_commands | train | def do_disable_commands(self, _):
"""Disable the Application Management commands"""
message_to_print = "{} is not available while {} commands are disabled".format(COMMAND_NAME,
self.CMD_CAT_APP_MGMT)
self.disable_category(self.CMD_CAT_APP_MGMT, message_to_print)
self.poutput("The Application Management commands have been disabled") | python | {
"resource": ""
} |
q34050 | register_custom_actions | train | def register_custom_actions(parser: argparse.ArgumentParser) -> None:
"""Register custom argument action types"""
parser.register('action', None, _StoreRangeAction)
parser.register('action', 'store', _StoreRangeAction)
parser.register('action', 'append', _AppendRangeAction) | python | {
"resource": ""
} |
q34051 | ACArgumentParser.error | train | def error(self, message: str) -> None:
"""Custom error override. Allows application to control the error being displayed by argparse"""
if len(self._custom_error_message) > 0:
message = self._custom_error_message
self._custom_error_message = ''
lines = message.split('\n')
linum = 0
formatted_message = ''
for line in lines:
if linum == 0:
formatted_message = 'Error: ' + line
else:
formatted_message += '\n ' + line
linum += 1
sys.stderr.write(Fore.LIGHTRED_EX + '{}\n\n'.format(formatted_message) + Fore.RESET)
# sys.stderr.write('{}\n\n'.format(formatted_message))
self.print_help()
sys.exit(1) | python | {
"resource": ""
} |
q34052 | TabCompleteExample.instance_query_movie_ids | train | def instance_query_movie_ids(self) -> List[str]:
"""Demonstrates showing tabular hinting of tab completion information"""
completions_with_desc = []
# Sort the movie id strings with a natural sort since they contain numbers
for movie_id in utils.natural_sort(self.MOVIE_DATABASE_IDS):
if movie_id in self.MOVIE_DATABASE:
movie_entry = self.MOVIE_DATABASE[movie_id]
completions_with_desc.append(argparse_completer.CompletionItem(movie_id, movie_entry['title']))
# Mark that we already sorted the matches
self.matches_sorted = True
return completions_with_desc | python | {
"resource": ""
} |
q34053 | TabCompleteExample.do_video | train | def do_video(self, args):
"""Video management command demonstrates multiple layers of sub-commands being handled by AutoCompleter"""
func = getattr(args, 'func', None)
if func is not None:
# Call whatever subcommand function was selected
func(self, args)
else:
# No subcommand was provided, so call help
self.do_help('video') | python | {
"resource": ""
} |
q34054 | TabCompleteExample.complete_media | train | def complete_media(self, text, line, begidx, endidx):
""" Adds tab completion to media"""
choices = {'actor': query_actors, # function
'director': TabCompleteExample.static_list_directors, # static list
'movie_file': (self.path_complete,)
}
completer = argparse_completer.AutoCompleter(TabCompleteExample.media_parser,
self,
arg_choices=choices)
tokens, _ = self.tokens_for_completion(line, begidx, endidx)
results = completer.complete_command(tokens, text, line, begidx, endidx)
return results | python | {
"resource": ""
} |
q34055 | HistoryItem.pr | train | def pr(self, script=False, expanded=False, verbose=False) -> str:
"""Represent a HistoryItem in a pretty fashion suitable for printing.
If you pass verbose=True, script and expanded will be ignored
:return: pretty print string version of a HistoryItem
"""
if verbose:
ret_str = self.listformat.format(self.idx, str(self).rstrip())
if self != self.expanded:
ret_str += self.ex_listformat.format(self.idx, self.expanded.rstrip())
else:
if script:
# display without entry numbers
if expanded or self.statement.multiline_command:
ret_str = self.expanded.rstrip()
else:
ret_str = str(self)
else:
# display a numbered list
if expanded or self.statement.multiline_command:
ret_str = self.listformat.format(self.idx, self.expanded.rstrip())
else:
ret_str = self.listformat.format(self.idx, str(self).rstrip())
return ret_str | python | {
"resource": ""
} |
q34056 | History._zero_based_index | train | def _zero_based_index(self, onebased: Union[int, str]) -> int:
"""Convert a one-based index to a zero-based index."""
result = int(onebased)
if result > 0:
result -= 1
return result | python | {
"resource": ""
} |
q34057 | History.append | train | def append(self, new: Statement) -> None:
"""Append a HistoryItem to end of the History list
:param new: command line to convert to HistoryItem and add to the end of the History list
"""
new = HistoryItem(new)
list.append(self, new)
new.idx = len(self) | python | {
"resource": ""
} |
q34058 | History.get | train | def get(self, index: Union[int, str]) -> HistoryItem:
"""Get item from the History list using 1-based indexing.
:param index: optional item to get (index as either integer or string)
:return: a single HistoryItem
"""
index = int(index)
if index == 0:
raise IndexError('The first command in history is command 1.')
elif index < 0:
return self[index]
else:
return self[index - 1] | python | {
"resource": ""
} |
q34059 | History.span | train | def span(self, span: str) -> List[HistoryItem]:
"""Return an index or slice of the History list,
:param span: string containing an index or a slice
:return: a list of HistoryItems
This method can accommodate input in any of these forms:
a
-a
a..b or a:b
a.. or a:
..a or :a
-a.. or -a:
..-a or :-a
Different from native python indexing and slicing of arrays, this method
uses 1-based array numbering. Users who are not programmers can't grok
0 based numbering. Programmers can usually grok either. Which reminds me,
there are only two hard problems in programming:
- naming
- cache invalidation
- off by one errors
"""
if span.lower() in ('*', '-', 'all'):
span = ':'
results = self.spanpattern.search(span)
if not results:
# our regex doesn't match the input, bail out
raise ValueError('History indices must be positive or negative integers, and may not be zero.')
sep = results.group('separator')
start = results.group('start')
if start:
start = self._zero_based_index(start)
end = results.group('end')
if end:
end = int(end)
# modify end so it's inclusive of the last element
if end == -1:
# -1 as the end means include the last command in the array, which in pythonic
# terms means to not provide an ending index. If you put -1 as the ending index
# python excludes the last item in the list.
end = None
elif end < -1:
# if the ending is smaller than -1, make it one larger so it includes
# the element (python native indices exclude the last referenced element)
end += 1
if start is not None and end is not None:
# we have both start and end, return a slice of history
result = self[start:end]
elif start is not None and sep is not None:
# take a slice of the array
result = self[start:]
elif end is not None and sep is not None:
result = self[:end]
elif start is not None:
# there was no separator so it's either a posative or negative integer
result = [self[start]]
else:
# we just have a separator, return the whole list
result = self[:]
return result | python | {
"resource": ""
} |
q34060 | History.str_search | train | def str_search(self, search: str) -> List[HistoryItem]:
"""Find history items which contain a given string
:param search: the string to search for
:return: a list of history items, or an empty list if the string was not found
"""
def isin(history_item):
"""filter function for string search of history"""
sloppy = utils.norm_fold(search)
return sloppy in utils.norm_fold(history_item) or sloppy in utils.norm_fold(history_item.expanded)
return [item for item in self if isin(item)] | python | {
"resource": ""
} |
q34061 | History.regex_search | train | def regex_search(self, regex: str) -> List[HistoryItem]:
"""Find history items which match a given regular expression
:param regex: the regular expression to search for.
:return: a list of history items, or an empty list if the string was not found
"""
regex = regex.strip()
if regex.startswith(r'/') and regex.endswith(r'/'):
regex = regex[1:-1]
finder = re.compile(regex, re.DOTALL | re.MULTILINE)
def isin(hi):
"""filter function for doing a regular expression search of history"""
return finder.search(hi) or finder.search(hi.expanded)
return [itm for itm in self if isin(itm)] | python | {
"resource": ""
} |
q34062 | PagedOutput.page_file | train | def page_file(self, file_path: str, chop: bool=False):
"""Helper method to prevent having too much duplicated code."""
filename = os.path.expanduser(file_path)
try:
with open(filename, 'r') as f:
text = f.read()
self.ppaged(text, chop=chop)
except FileNotFoundError:
self.perror('ERROR: file {!r} not found'.format(filename), traceback_war=False) | python | {
"resource": ""
} |
q34063 | PagedOutput.do_page_wrap | train | def do_page_wrap(self, args: List[str]):
"""Read in a text file and display its output in a pager, wrapping long lines if they don't fit.
Usage: page_wrap <file_path>
"""
if not args:
self.perror('page_wrap requires a path to a file as an argument', traceback_war=False)
return
self.page_file(args[0], chop=False) | python | {
"resource": ""
} |
q34064 | PagedOutput.do_page_truncate | train | def do_page_truncate(self, args: List[str]):
"""Read in a text file and display its output in a pager, truncating long lines if they don't fit.
Truncated lines can still be accessed by scrolling to the right using the arrow keys.
Usage: page_chop <file_path>
"""
if not args:
self.perror('page_truncate requires a path to a file as an argument', traceback_war=False)
return
self.page_file(args[0], chop=True) | python | {
"resource": ""
} |
q34065 | rl_force_redisplay | train | def rl_force_redisplay() -> None: # pragma: no cover
"""
Causes readline to display the prompt and input text wherever the cursor is and start
reading input from this location. This is the proper way to restore the input line after
printing to the screen
"""
if not sys.stdout.isatty():
return
if rl_type == RlType.GNU:
readline_lib.rl_forced_update_display()
# After manually updating the display, readline asks that rl_display_fixed be set to 1 for efficiency
display_fixed = ctypes.c_int.in_dll(readline_lib, "rl_display_fixed")
display_fixed.value = 1
elif rl_type == RlType.PYREADLINE:
# Call _print_prompt() first to set the new location of the prompt
readline.rl.mode._print_prompt()
readline.rl.mode._update_line() | python | {
"resource": ""
} |
q34066 | rl_get_point | train | def rl_get_point() -> int: # pragma: no cover
"""
Returns the offset of the current cursor position in rl_line_buffer
"""
if rl_type == RlType.GNU:
return ctypes.c_int.in_dll(readline_lib, "rl_point").value
elif rl_type == RlType.PYREADLINE:
return readline.rl.mode.l_buffer.point
else:
return 0 | python | {
"resource": ""
} |
q34067 | rl_make_safe_prompt | train | def rl_make_safe_prompt(prompt: str) -> str: # pragma: no cover
"""Overcome bug in GNU Readline in relation to calculation of prompt length in presence of ANSI escape codes.
:param prompt: original prompt
:return: prompt safe to pass to GNU Readline
"""
if rl_type == RlType.GNU:
# start code to tell GNU Readline about beginning of invisible characters
start = "\x01"
# end code to tell GNU Readline about end of invisible characters
end = "\x02"
escaped = False
result = ""
for c in prompt:
if c == "\x1b" and not escaped:
result += start + c
escaped = True
elif c.isalpha() and escaped:
result += c + end
escaped = False
else:
result += c
return result
else:
return prompt | python | {
"resource": ""
} |
q34068 | CmdLineApp._set_prompt | train | def _set_prompt(self):
"""Set prompt so it displays the current working directory."""
self.cwd = os.getcwd()
self.prompt = Fore.CYAN + '{!r} $ '.format(self.cwd) + Fore.RESET | python | {
"resource": ""
} |
q34069 | CmdLineApp.postcmd | train | def postcmd(self, stop: bool, line: str) -> bool:
"""Hook method executed just after a command dispatch is finished.
:param stop: if True, the command has indicated the application should exit
:param line: the command line text for this command
:return: if this is True, the application will exit after this command and the postloop() will run
"""
"""Override this so prompt always displays cwd."""
self._set_prompt()
return stop | python | {
"resource": ""
} |
q34070 | CmdLineApp.do_dir | train | def do_dir(self, args, unknown):
"""List contents of current directory."""
# No arguments for this command
if unknown:
self.perror("dir does not take any positional arguments:", traceback_war=False)
self.do_help('dir')
self._last_result = cmd2.CommandResult('', 'Bad arguments')
return
# Get the contents as a list
contents = os.listdir(self.cwd)
fmt = '{} '
if args.long:
fmt = '{}\n'
for f in contents:
self.stdout.write(fmt.format(f))
self.stdout.write('\n')
self._last_result = cmd2.CommandResult(data=contents) | python | {
"resource": ""
} |
q34071 | pop_density | train | def pop_density(data: CityInfo) -> str:
"""Calculate the population density from the data entry"""
if not isinstance(data, CityInfo):
raise AttributeError("Argument to pop_density() must be an instance of CityInfo")
return no_dec(data.get_population() / data.get_area()) | python | {
"resource": ""
} |
q34072 | make_table_parser | train | def make_table_parser() -> cmd2.argparse_completer.ACArgumentParser:
"""Create a unique instance of an argparse Argument parser for processing table arguments.
NOTE: The two cmd2 argparse decorators require that each parser be unique, even if they are essentially a deep copy
of each other. For cases like that, you can create a function to return a unique instance of a parser, which is
what is being done here.
"""
table_parser = cmd2.argparse_completer.ACArgumentParser()
table_item_group = table_parser.add_mutually_exclusive_group()
table_item_group.add_argument('-c', '--color', action='store_true', help='Enable color')
table_item_group.add_argument('-f', '--fancy', action='store_true', help='Fancy Grid')
table_item_group.add_argument('-s', '--sparse', action='store_true', help='Sparse Grid')
return table_parser | python | {
"resource": ""
} |
q34073 | TableDisplay.ptable | train | def ptable(self, rows, columns, grid_args, row_stylist):
"""Format tabular data for pretty-printing as a fixed-width table and then display it using a pager.
:param rows: can be a list-of-lists (or another iterable of iterables), a two-dimensional
NumPy array, or an Iterable of non-iterable objects
:param columns: column headers and formatting options per column
:param grid_args: argparse arguments for formatting the grid
:param row_stylist: function to determine how each row gets styled
"""
if grid_args.color:
grid = tf.AlternatingRowGrid(BACK_PRI, BACK_ALT)
elif grid_args.fancy:
grid = tf.FancyGrid()
elif grid_args.sparse:
grid = tf.SparseGrid()
else:
grid = None
formatted_table = tf.generate_table(rows=rows, columns=columns, grid_style=grid, row_tagger=row_stylist)
self.ppaged(formatted_table, chop=True) | python | {
"resource": ""
} |
q34074 | Pirate.postcmd | train | def postcmd(self, stop, line):
"""Runs right before a command is about to return."""
if self.gold != self.initial_gold:
self.poutput('Now we gots {0} doubloons'.format(self.gold))
if self.gold < 0:
self.poutput("Off to debtorrr's prison.")
stop = True
return stop | python | {
"resource": ""
} |
q34075 | Pirate.do_sing | train | def do_sing(self, arg):
"""Sing a colorful song."""
color_escape = COLORS.get(self.songcolor, Fore.RESET)
self.poutput(arg, color=color_escape) | python | {
"resource": ""
} |
q34076 | Pirate.do_yo | train | def do_yo(self, args):
"""Compose a yo-ho-ho type chant with flexible options."""
chant = ['yo'] + ['ho'] * args.ho
separator = ', ' if args.commas else ' '
chant = separator.join(chant)
self.poutput('{0} and a bottle of {1}'.format(chant, args.beverage)) | python | {
"resource": ""
} |
q34077 | get_sub_commands | train | def get_sub_commands(parser: argparse.ArgumentParser) -> List[str]:
"""Get a list of sub-commands for an ArgumentParser"""
sub_cmds = []
# Check if this is parser has sub-commands
if parser is not None and parser._subparsers is not None:
# Find the _SubParsersAction for the sub-commands of this parser
for action in parser._subparsers._actions:
if isinstance(action, argparse._SubParsersAction):
for sub_cmd, sub_cmd_parser in action.choices.items():
sub_cmds.append(sub_cmd)
# Look for nested sub-commands
for nested_sub_cmd in get_sub_commands(sub_cmd_parser):
sub_cmds.append('{} {}'.format(sub_cmd, nested_sub_cmd))
break
sub_cmds.sort()
return sub_cmds | python | {
"resource": ""
} |
q34078 | main | train | def main() -> None:
"""Main function of this script"""
# Make sure we have access to self
if 'self' not in globals():
print("Run 'set locals_in_py true' and then rerun this script")
return
# Make sure the user passed in an output file
if len(sys.argv) != 2:
print("Usage: {} <output_file>".format(os.path.basename(sys.argv[0])))
return
# Open the output file
outfile_path = os.path.expanduser(sys.argv[1])
try:
outfile = open(outfile_path, 'w')
except OSError as e:
print("Error opening {} because: {}".format(outfile_path, e))
return
# Write the help summary
header = '{0}\nSUMMARY\n{0}\n'.format(ASTERISKS)
outfile.write(header)
result = app('help -v')
outfile.write(result.stdout)
# Get a list of all commands and help topics and then filter out duplicates
all_commands = set(self.get_all_commands())
all_topics = set(self.get_help_topics())
to_save = list(all_commands | all_topics)
to_save.sort()
for item in to_save:
is_command = item in all_commands
add_help_to_file(item, outfile, is_command)
if is_command:
# Add any sub-commands
for subcmd in get_sub_commands(getattr(self.cmd_func(item), 'argparser', None)):
full_cmd = '{} {}'.format(item, subcmd)
add_help_to_file(full_cmd, outfile, is_command)
outfile.close()
print("Output written to {}".format(outfile_path)) | python | {
"resource": ""
} |
q34079 | cached | train | def cached(cache, key=keys.hashkey, lock=None):
"""Decorator to wrap a function with a memoizing callable that saves
results in a cache.
"""
def decorator(func):
if cache is None:
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
elif lock is None:
def wrapper(*args, **kwargs):
k = key(*args, **kwargs)
try:
return cache[k]
except KeyError:
pass # key not found
v = func(*args, **kwargs)
try:
cache[k] = v
except ValueError:
pass # value too large
return v
else:
def wrapper(*args, **kwargs):
k = key(*args, **kwargs)
try:
with lock:
return cache[k]
except KeyError:
pass # key not found
v = func(*args, **kwargs)
try:
with lock:
cache[k] = v
except ValueError:
pass # value too large
return v
return _update_wrapper(wrapper, func)
return decorator | python | {
"resource": ""
} |
q34080 | cachedmethod | train | def cachedmethod(cache, key=keys.hashkey, lock=None):
"""Decorator to wrap a class or instance method with a memoizing
callable that saves results in a cache.
"""
def decorator(method):
if lock is None:
def wrapper(self, *args, **kwargs):
c = cache(self)
if c is None:
return method(self, *args, **kwargs)
k = key(*args, **kwargs)
try:
return c[k]
except KeyError:
pass # key not found
v = method(self, *args, **kwargs)
try:
c[k] = v
except ValueError:
pass # value too large
return v
else:
def wrapper(self, *args, **kwargs):
c = cache(self)
if c is None:
return method(self, *args, **kwargs)
k = key(*args, **kwargs)
try:
with lock(self):
return c[k]
except KeyError:
pass # key not found
v = method(self, *args, **kwargs)
try:
with lock(self):
c[k] = v
except ValueError:
pass # value too large
return v
return _update_wrapper(wrapper, method)
return decorator | python | {
"resource": ""
} |
q34081 | iter_result_proxy | train | def iter_result_proxy(rp, step=None):
"""Iterate over the ResultProxy."""
while True:
if step is None:
chunk = rp.fetchall()
else:
chunk = rp.fetchmany(step)
if not chunk:
break
for row in chunk:
yield row | python | {
"resource": ""
} |
q34082 | normalize_column_name | train | def normalize_column_name(name):
"""Check if a string is a reasonable thing to use as a column name."""
if not isinstance(name, six.string_types):
raise ValueError('%r is not a valid column name.' % name)
# limit to 63 characters
name = name.strip()[:63]
# column names can be 63 *bytes* max in postgresql
if isinstance(name, six.text_type):
while len(name.encode('utf-8')) >= 64:
name = name[:len(name) - 1]
if not len(name) or '.' in name or '-' in name:
raise ValueError('%r is not a valid column name.' % name)
return name | python | {
"resource": ""
} |
q34083 | safe_url | train | def safe_url(url):
"""Remove password from printed connection URLs."""
parsed = urlparse(url)
if parsed.password is not None:
pwd = ':%s@' % parsed.password
url = url.replace(pwd, ':*****@')
return url | python | {
"resource": ""
} |
q34084 | index_name | train | def index_name(table, columns):
"""Generate an artificial index name."""
sig = '||'.join(columns)
key = sha1(sig.encode('utf-8')).hexdigest()[:16]
return 'ix_%s_%s' % (table, key) | python | {
"resource": ""
} |
q34085 | ensure_tuple | train | def ensure_tuple(obj):
"""Try and make the given argument into a tuple."""
if obj is None:
return tuple()
if isinstance(obj, Iterable) and not isinstance(obj, six.string_types):
return tuple(obj)
return obj, | python | {
"resource": ""
} |
q34086 | pad_chunk_columns | train | def pad_chunk_columns(chunk):
"""Given a set of items to be inserted, make sure they all have the
same columns by padding columns with None if they are missing."""
columns = set()
for record in chunk:
columns.update(record.keys())
for record in chunk:
for column in columns:
record.setdefault(column, None)
return chunk | python | {
"resource": ""
} |
q34087 | Types.guess | train | def guess(cls, sample):
"""Given a single sample, guess the column type for the field.
If the sample is an instance of an SQLAlchemy type, the type will be
used instead.
"""
if isinstance(sample, TypeEngine):
return sample
if isinstance(sample, bool):
return cls.boolean
elif isinstance(sample, int):
return cls.integer
elif isinstance(sample, float):
return cls.float
elif isinstance(sample, datetime):
return cls.datetime
elif isinstance(sample, date):
return cls.date
return cls.text | python | {
"resource": ""
} |
q34088 | Table.insert | train | def insert(self, row, ensure=None, types=None):
"""Add a ``row`` dict by inserting it into the table.
If ``ensure`` is set, any of the keys of the row are not
table columns, they will be created automatically.
During column creation, ``types`` will be checked for a key
matching the name of a column to be created, and the given
SQLAlchemy column type will be used. Otherwise, the type is
guessed from the row value, defaulting to a simple unicode
field.
::
data = dict(title='I am a banana!')
table.insert(data)
Returns the inserted row's primary key.
"""
row = self._sync_columns(row, ensure, types=types)
res = self.db.executable.execute(self.table.insert(row))
if len(res.inserted_primary_key) > 0:
return res.inserted_primary_key[0]
return True | python | {
"resource": ""
} |
q34089 | Table.insert_ignore | train | def insert_ignore(self, row, keys, ensure=None, types=None):
"""Add a ``row`` dict into the table if the row does not exist.
If rows with matching ``keys`` exist they will be added to the table.
Setting ``ensure`` results in automatically creating missing columns,
i.e., keys of the row are not table columns.
During column creation, ``types`` will be checked for a key
matching the name of a column to be created, and the given
SQLAlchemy column type will be used. Otherwise, the type is
guessed from the row value, defaulting to a simple unicode
field.
::
data = dict(id=10, title='I am a banana!')
table.insert_ignore(data, ['id'])
"""
row = self._sync_columns(row, ensure, types=types)
if self._check_ensure(ensure):
self.create_index(keys)
args, _ = self._keys_to_args(row, keys)
if self.count(**args) == 0:
return self.insert(row, ensure=False)
return False | python | {
"resource": ""
} |
q34090 | Table.insert_many | train | def insert_many(self, rows, chunk_size=1000, ensure=None, types=None):
"""Add many rows at a time.
This is significantly faster than adding them one by one. Per default
the rows are processed in chunks of 1000 per commit, unless you specify
a different ``chunk_size``.
See :py:meth:`insert() <dataset.Table.insert>` for details on
the other parameters.
::
rows = [dict(name='Dolly')] * 10000
table.insert_many(rows)
"""
chunk = []
for row in rows:
row = self._sync_columns(row, ensure, types=types)
chunk.append(row)
if len(chunk) == chunk_size:
chunk = pad_chunk_columns(chunk)
self.table.insert().execute(chunk)
chunk = []
if len(chunk):
chunk = pad_chunk_columns(chunk)
self.table.insert().execute(chunk) | python | {
"resource": ""
} |
q34091 | Table.update | train | def update(self, row, keys, ensure=None, types=None, return_count=False):
"""Update a row in the table.
The update is managed via the set of column names stated in ``keys``:
they will be used as filters for the data to be updated, using the
values in ``row``.
::
# update all entries with id matching 10, setting their title columns
data = dict(id=10, title='I am a banana!')
table.update(data, ['id'])
If keys in ``row`` update columns not present in the table, they will
be created based on the settings of ``ensure`` and ``types``, matching
the behavior of :py:meth:`insert() <dataset.Table.insert>`.
"""
row = self._sync_columns(row, ensure, types=types)
args, row = self._keys_to_args(row, keys)
clause = self._args_to_clause(args)
if not len(row):
return self.count(clause)
stmt = self.table.update(whereclause=clause, values=row)
rp = self.db.executable.execute(stmt)
if rp.supports_sane_rowcount():
return rp.rowcount
if return_count:
return self.count(clause) | python | {
"resource": ""
} |
q34092 | Table.upsert | train | def upsert(self, row, keys, ensure=None, types=None):
"""An UPSERT is a smart combination of insert and update.
If rows with matching ``keys`` exist they will be updated, otherwise a
new row is inserted in the table.
::
data = dict(id=10, title='I am a banana!')
table.upsert(data, ['id'])
"""
row = self._sync_columns(row, ensure, types=types)
if self._check_ensure(ensure):
self.create_index(keys)
row_count = self.update(row, keys, ensure=False, return_count=True)
if row_count == 0:
return self.insert(row, ensure=False)
return True | python | {
"resource": ""
} |
q34093 | Table.delete | train | def delete(self, *clauses, **filters):
"""Delete rows from the table.
Keyword arguments can be used to add column-based filters. The filter
criterion will always be equality:
::
table.delete(place='Berlin')
If no arguments are given, all records are deleted.
"""
if not self.exists:
return False
clause = self._args_to_clause(filters, clauses=clauses)
stmt = self.table.delete(whereclause=clause)
rp = self.db.executable.execute(stmt)
return rp.rowcount > 0 | python | {
"resource": ""
} |
q34094 | Table._reflect_table | train | def _reflect_table(self):
"""Load the tables definition from the database."""
with self.db.lock:
try:
self._table = SQLATable(self.name,
self.db.metadata,
schema=self.db.schema,
autoload=True)
except NoSuchTableError:
pass | python | {
"resource": ""
} |
q34095 | Table._sync_table | train | def _sync_table(self, columns):
"""Lazy load, create or adapt the table structure in the database."""
if self._table is None:
# Load an existing table from the database.
self._reflect_table()
if self._table is None:
# Create the table with an initial set of columns.
if not self._auto_create:
raise DatasetException("Table does not exist: %s" % self.name)
# Keep the lock scope small because this is run very often.
with self.db.lock:
self._threading_warn()
self._table = SQLATable(self.name,
self.db.metadata,
schema=self.db.schema)
if self._primary_id is not False:
# This can go wrong on DBMS like MySQL and SQLite where
# tables cannot have no columns.
primary_id = self._primary_id or self.PRIMARY_DEFAULT
primary_type = self._primary_type or Types.integer
increment = primary_type in [Types.integer, Types.bigint]
column = Column(primary_id, primary_type,
primary_key=True,
autoincrement=increment)
self._table.append_column(column)
for column in columns:
if not column.name == self._primary_id:
self._table.append_column(column)
self._table.create(self.db.executable, checkfirst=True)
elif len(columns):
with self.db.lock:
self._reflect_table()
self._threading_warn()
for column in columns:
if not self.has_column(column.name):
self.db.op.add_column(self.name, column, self.db.schema)
self._reflect_table() | python | {
"resource": ""
} |
q34096 | Table.drop | train | def drop(self):
"""Drop the table from the database.
Deletes both the schema and all the contents within it.
"""
with self.db.lock:
if self.exists:
self._threading_warn()
self.table.drop(self.db.executable, checkfirst=True)
self._table = None | python | {
"resource": ""
} |
q34097 | Table.has_index | train | def has_index(self, columns):
"""Check if an index exists to cover the given ``columns``."""
if not self.exists:
return False
columns = set([normalize_column_name(c) for c in columns])
if columns in self._indexes:
return True
for column in columns:
if not self.has_column(column):
return False
indexes = self.db.inspect.get_indexes(self.name, schema=self.db.schema)
for index in indexes:
if columns == set(index.get('column_names', [])):
self._indexes.append(columns)
return True
return False | python | {
"resource": ""
} |
q34098 | Table.create_index | train | def create_index(self, columns, name=None, **kw):
"""Create an index to speed up queries on a table.
If no ``name`` is given a random name is created.
::
table.create_index(['name', 'country'])
"""
columns = [normalize_column_name(c) for c in ensure_tuple(columns)]
with self.db.lock:
if not self.exists:
raise DatasetException("Table has not been created yet.")
for column in columns:
if not self.has_column(column):
return
if not self.has_index(columns):
self._threading_warn()
name = name or index_name(self.name, columns)
columns = [self.table.c[c] for c in columns]
idx = Index(name, *columns, **kw)
idx.create(self.db.executable) | python | {
"resource": ""
} |
q34099 | Table.find | train | def find(self, *_clauses, **kwargs):
"""Perform a simple search on the table.
Simply pass keyword arguments as ``filter``.
::
results = table.find(country='France')
results = table.find(country='France', year=1980)
Using ``_limit``::
# just return the first 10 rows
results = table.find(country='France', _limit=10)
You can sort the results by single or multiple columns. Append a minus
sign to the column name for descending order::
# sort results by a column 'year'
results = table.find(country='France', order_by='year')
# return all rows sorted by multiple columns (descending by year)
results = table.find(order_by=['country', '-year'])
To perform complex queries with advanced filters or to perform
aggregation, use :py:meth:`db.query() <dataset.Database.query>`
instead.
"""
if not self.exists:
return iter([])
_limit = kwargs.pop('_limit', None)
_offset = kwargs.pop('_offset', 0)
order_by = kwargs.pop('order_by', None)
_streamed = kwargs.pop('_streamed', False)
_step = kwargs.pop('_step', QUERY_STEP)
if _step is False or _step == 0:
_step = None
order_by = self._args_to_order_by(order_by)
args = self._args_to_clause(kwargs, clauses=_clauses)
query = self.table.select(whereclause=args,
limit=_limit,
offset=_offset)
if len(order_by):
query = query.order_by(*order_by)
conn = self.db.executable
if _streamed:
conn = self.db.engine.connect()
conn = conn.execution_options(stream_results=True)
return ResultIter(conn.execute(query),
row_type=self.db.row_type,
step=_step) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.