def rlinput(prompt, prefill=''): 'https://stackoverflow.com/questions/2533120/show-default-value-for-editing-on-python-input-possible/2533134' readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: return raw_input(prompt) finally: readline.set_startup_hook()
def prompt_edit(self, label, value, choices=None): """ prompt choice edit :param label: :param value: :param choices: :return: """ if not value: value = "" if choices: label += " (" label += "|".join(choices) label += ") " while True: readline.set_startup_hook(lambda: readline.insert_text(value)) try: input = raw_input except NameError: from builtins import input try: reply = input(label).strip() if not choices or reply in choices: return reply print("Please enter one of the " "following: %s" % " | ".join(choices)) finally: readline.set_startup_hook()
def main(): """ This is the core of the program, get input and execute. """ signal.signal(signal.SIGTSTP, signal.SIG_IGN) while True: try: readline.set_startup_hook() orchestra = input(get_input_display()) History.history_conten.append(orchestra) if orchestra == "": continue command, arguments = handle_input(orchestra) # print(command) try: Vars.variations["_"] = arguments[-1] except IndexError: pass if command == "": continue result, Vars.variations['?'] = run_command(command, arguments) if result == "exit": return Vars.variations['?'] except EOFError: return 1 except KeyboardInterrupt: print("^C") continue
def rlinput(prompt, prefill=''): readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: # This was raw_input, but that's deprecated in py3 return input(prompt) finally: readline.set_startup_hook()
def read_input(prompt, prefill = ''): """ Function to read input from stdin Args: prompt: Prompt for the input prefill: A default value for the input """ try: if not prefill: raise Exception #if readline is present, use to prefill the input import readline as c_readline value, prefill = prefill, '' #in this case we are resetting the prefill so as to not return the prefill c_readline.set_startup_hook(lambda: c_readline.insert_text(value)) except ImportError: #otherwise modify the prompt to show the prefill c_readline = None prompt = '%s[%s] ' % (prompt, prefill) except: c_readline = None #Python 2.x vs 3.x try: c_input = raw_input except: c_input = input try: #read the input or return any prefill values return c_input(prompt) or prefill finally: c_readline and c_readline.set_startup_hook() #unbind startup hook
def get(self, field, value=None): """Gets :field: value from stdin. :field: Field's name. :value: Default value for editing. :returns: Value got from stdin. """ readline.set_startup_hook(lambda: readline.insert_text( value is not None and str(value) or "" )) try: value = input("{0}> ".format(field)) except KeyboardInterrupt: print() exit(0) readline.set_startup_hook() if field == 'priority': try: value = int(value) except ValueError: if value == '': return None print("Invalid priority value!") exit(0) else: if value not in [1, 2, 3, 4, 5]: print("Invalid priority value!") exit(0) return value return value
def getinput(question, default="", reader=raw_input, completer=None, width=_defaultwidth): # pragma: no cover """ http://stackoverflow.com/questions/2617057/\ supply-inputs-to-python-unittests """ if reader == raw_input: if not _readline_available: val = raw_input(question.ljust(width)) if val: return val else: return default else: def defaulter(): """define default behavior startup""" if _readline_available: readline.insert_text(default) readline.set_startup_hook(defaulter) readline.get_completer() readline.set_completer(completer) x = raw_input(question.ljust(width)) readline.set_completer(completer) readline.set_startup_hook() if not x: return default return x else: return reader()
def rlinput(prompt, prefill=''): """kind of like ras_input but with readline support and pre-filled answer""" readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: return raw_input(prompt) finally: readline.set_startup_hook()
def silent_invariant_raw_input(prompt,comp=None,wipe=False, echo = True,color = Colors.NONE,completion=None): prompt = color+prompt+Colors.ENDC if not Control.silent: readline.set_startup_hook(lambda: readline.insert_text(comp)) if completion=="Files": readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(fileCompleter) elif not completion is None: readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(lambda a,b:listCompleter(a,b,completion)) try: if Control.silent: prompt = "" if echo: ret = raw_input(prompt) else: ret = getpass.getpass(prompt) wipe = False if wipe: l = readline.get_current_history_length() if l > 0: readline.remove_history_item(l-1) return ret finally: if not Control.silent: readline.set_startup_hook() if not completion is None: readline.parse_and_bind("set disable-completion On") readline.set_completer(None) #readline.parse_and_bind("tab: \t") readline.set_completer_delims("")
def export_gcal(v, y, m, d, tid, sid): cmd = [] cmd.append("gcalcli") cmd.append("--calendar") readline.set_startup_hook(lambda: readline.insert_text("")) t = tabCompleter() t.createListCompleter(["calender", "NSC absences", "NSC shared calender"]) readline.set_completer_delims('\t') readline.parse_and_bind("tab: complete") readline.set_completer(t.listCompleter) calender = raw_input("Name of calender: ").strip() cmd.append(calender) cmd.append("--title") v[y][m][d][tid][sid]["subtask title"] cmd.append(v[y][m][d][tid][sid]["subtask title"]) cmd.append("--where") cmd.append("''") cmd.append("--when") dt = str(m)+ "/" + str(d) + "/" + str(y) + " " + v[y][m][d][tid][sid]["start"] cmd.append(dt) cmd.append("--duration") (h1, m1) = tuple(v[y][m][d][tid][sid]["start"].split(':')) (h2, m2) = tuple(v[y][m][d][tid][sid]["end"].split(':')) dur = str((int(h2) - int(h1)) * 60 + (int(m2) -int(m1))) cmd.append(dur) cmd.append("--description") cmd.append("''") cmd.append("--reminder") cmd.append("0") cmd.append("add") job = subprocess.Popen(cmd) job.wait() raw_input("Press enter to continue")
def rlinput(prompt, prefill: str = '') -> Optional[str]: """See https://stackoverflow.com/a/36607077""" readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: return input(prompt) finally: readline.set_startup_hook()
def rlinput(prompt, prefill='', oneline=False, ctxkey=''): """ Get user input with readline editing support. """ sentinel = '' if prefill is None: prefill = '' def only_once(text): """ generator for startup hook """ readline.insert_text(text) yield while True: yield savedhist = NamedTemporaryFile() readline.write_history_file(savedhist.name) ctxhistname = ".tl" + ctxkey + "history" ctxhistfile = os.path.join(G.ProjectFolder, ctxhistname) try: readline.clear_history() except AttributeError: print "This readline doesn't support clear_history()" raise savedcompleter = readline.get_completer() try: ulines = uniqify(ctxhistfile) readline.read_history_file(ctxhistfile) readline.set_completer(HistoryCompleter(ulines).complete) except IOError: pass readline.parse_and_bind('tab: complete') saveddelims = readline.get_completer_delims() readline.set_completer_delims('') ## No delims. Complete entire lines. readline.set_completion_display_matches_hook(match_display_hook) gen = only_once(prefill) readline.set_startup_hook(gen.next) try: if oneline: edited = raw_input(prompt) else: print prompt edited = "\n".join(iter(raw_input, sentinel)) if edited.endswith(r'%%'): ## Invoke external editor edited = external_edit(edited[0:-2]) return edited finally: ## Restore readline state readline.write_history_file(ctxhistfile) readline.clear_history() readline.read_history_file(savedhist.name) savedhist.close() readline.set_completer(savedcompleter) readline.set_completer_delims(saveddelims) readline.set_startup_hook()
def main(): env = pickle.load(open(path.ENV, "r")) user = imp.load_source("settings", path.SETTINGS) readline.read_history_file(path.HISTORY) for component in user.CLIENT_COMPONENTS: component.initialize(env, user) for line in open(path.RC, "r"): execute(env, user, line.strip()) while True: try: line = raw_input(user.PROMPT_FORMAT % env) readline.set_startup_hook(None) if not line: continue except EOFError: print readline.write_history_file(path.HISTORY) break execute(env, user, line) for component in user.CLIENT_COMPONENTS: component.terminate(env, user) pickle.dump(env, open(path.ENV, "w"))
def _rlinput(self, prompt, prefill): readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: return raw_input(prompt) finally: readline.set_startup_hook() return prefill
def getWithDefault(question, value): question += ": " readline.set_startup_hook(lambda: readline.insert_text(value)) try: return ask(question) finally: readline.set_startup_hook()
def do_history(self, args): """ Prints cloudmonkey history """ if self.pipe_runner("history " + args): return startIdx = 1 endIdx = readline.get_current_history_length() numLen = len(str(endIdx)) historyArg = args.split(' ')[0] if historyArg.isdigit(): startIdx = endIdx - long(historyArg) if startIdx < 1: startIdx = 1 elif historyArg == "clear" or historyArg == "c": readline.clear_history() print "CloudMonkey history cleared" return elif len(historyArg) > 1 and historyArg[0] == "!" and historyArg[1:].isdigit(): command = readline.get_history_item(long(historyArg[1:])) readline.set_startup_hook(lambda: readline.insert_text(command)) self.hook_count = 1 return for idx in xrange(startIdx, endIdx): self.monkeyprint("%s %s" % (str(idx).rjust(numLen), readline.get_history_item(idx)))
def defaulter(): """define default behavior startup""" if _readline_available: readline.insert_text(default) readline.set_startup_hook(defaulter) readline.get_completer() readline.set_completer(completer)
def get_user_input(obj, attr, opts, no_prefill=False): if attr == 'collection' and not getattr(obj, attr) and obj.project: setattr(obj, attr, obj.project.collection) if opts: optlist = ', '.join(['%s=%s' % (k, v) for k, v in opts.items()]) prompt = '%s [Options: %s]: ' % (attr, optlist) else: prompt = '%s: ' % attr if no_prefill or not getattr(obj, attr): prefill = '' else: if (hasattr(obj, 'relations') and attr in obj.relations) \ or (getattr(obj, attr) and hasattr(getattr(obj, attr), 'id')): prefill = getattr(obj, attr).id else: prefill = getattr(obj, attr) readline.set_startup_hook(lambda: readline.insert_text(prefill)) readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(complete) try: return raw_input(prompt) finally: readline.set_startup_hook()
def prompt(prompt, prefill=""): readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: data = raw_input(prompt) print return data finally: readline.set_startup_hook()
def readline_input(prompt, prefill=''): """work just like input() but with optional prefill""" readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: return input(prompt) finally: readline.set_startup_hook()
def readline_input(prompt, prefill=''): """Provide an editable default for ``input()``.""" # see: https://stackoverflow.com/q/2533120/ readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: return six.moves.input(prompt) finally: readline.set_startup_hook()
def input_default(prompt, default): def startup_hook(): readline.insert_text(default) readline.set_startup_hook(startup_hook) try: return raw_input(prompt) finally: readline.set_startup_hook(None)
def _input_default(prompt, default): def startup_hook(): readline.insert_text(default) readline.set_startup_hook(startup_hook) try: return raw_input(prompt) finally: readline.set_startup_hook(None)
def prompt_entry_for(table_description: str, entry_text: str) -> str: prompt = "\t{0:20}: ".format(table_description) readline.set_startup_hook(lambda: readline.insert_text(entry_text)) try: pass finally: readline.set_startup_hook() return input(prompt)
def raw_input_default(prompt, value = None): if value: readline.set_startup_hook(lambda: readline.insert_text(value)) try: return raw_input(prompt) finally: if value: readline.set_startup_hook(None)
def getUserInWithDef(msg, default): readline.set_startup_hook(lambda: readline.insert_text(default)) var = raw_input(colors.BOLDON + "%s: " % (msg) + colors.BOLDOFF) readline.set_startup_hook(lambda: readline.insert_text('')) if var == "": print("No input given, try again.") return getUserIn(msg) return var
def prefill_input(prompt, prefill): """prompt for input with supplied prefill text""" readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: result = input(prompt) finally: readline.set_startup_hook() return result
def getinput(question, default="", width=_defaultwidth): if (not _readline_available): return raw_input(question.ljust(width)) else: def defaulter(): readline.insert_text(default) readline.set_startup_hook(defaulter) x = raw_input(question.ljust(width)) readline.set_startup_hook() return x
def input(prompt, prefill=""): """ FIXME: this does not work on Darwin, even with brew readline-6.2.4? """ readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: return input(prompt) finally: readline.set_startup_hook()
def read_input(prompt, prefill=''): if prefill: # We need to cast text since insert_text only takes strings prefill = unicode(prefill) readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: return get_input(prompt) finally: readline.set_startup_hook()
def default_input(prompt, prefill=''): ''' get CLI input, with a default value already specified ''' readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: return raw_input(prompt) finally: readline.set_startup_hook()
def read_input_prefill(prompt, prefill = ''): """ Provides user input through readline with 'prefill' default values. """ readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: return raw_input(prompt) finally: readline.set_startup_hook()
def rlinput(prompt, prefill=''): if prefill is None: prefill = '' if not isinstance(prefill, str): prefill = str(prefill) readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: return input(prompt) finally: readline.set_startup_hook()
def close(self): # --- Finish writing the buffers self._writesessionlog() # --- Close the file self.logfile.close() # --- Remove readline startup hook and reset stdout and err readline.set_startup_hook() sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__
def readline(self, prompt, first_char=None): if first_char is not None: def startup_hook(): readline.insert_text(first_char) readline.set_startup_hook(None) readline.set_startup_hook(startup_hook) with self.term.shell_mode(): line = input(prompt) return line
def prompt_for_file(self, infile): if infile: print >>sys.stderr, 'file: %s' % infile else: readline.set_startup_hook() readline.parse_and_bind('') readline.set_completer() infile = raw_input('file: ') if infile == '': infile = None return infile
def variable(name, default=A_UNIQUE_VALUE): variables, variables_path = load_variables() # if the name of the variable is not defined, we need to prompt the user for it if name not in variables: has_default = default is not A_UNIQUE_VALUE comment = get_preceeding_comments() if comment: print(info(comment)) if has_default: # write the default to stdin when input is promoted for readline.set_startup_hook(lambda: readline.insert_text(repr(default))) while name not in variables: # make sure we are at a tty device if not os.isatty(sys.stdin.fileno()): raise KeyError("You need to set the variable '%s' in %s (or somewhere else in your python path)." % (name, variables_path)) val = input(warning(name) + " = ") # clear the startup hook since we only want to show the default # value once readline.set_startup_hook() if has_default and val == "": val = default else: try: val = eval(val) except Exception as e: print(danger(str(e))) continue # we need to ensure the repr of the value is valid Python try: ast.literal_eval(repr(val)) except Exception as e: print(danger("The value must have a repr that is valid Python (like a number, list, dict, or string)!")) continue # everything is good, so we can actually save the value variables[name] = val # append the variable to the variables.py file with open(variables_path, "a+") as f: # write a newline if we're not at the beginning of the file, and # the previous line didn't end with \n write_new_line = f.tell() != 0 and not f.read().endswith("\n") if write_new_line: f.write("\n") f.write("%s" % comment + "\n" if comment else "") f.write("%s = %s\n" % (name, repr(val))) return variables[name]
def prompt_for_source(self, sources): if sources: readline.set_startup_hook(lambda: readline.insert_text(sources[0])) elif self.db: sources = self.db.get_terms('source') readline.parse_and_bind("tab: complete") completer = Completer(sources) readline.set_completer(completer.terms) source = raw_input('source: ') if source == '': source = None return source