def run_main(tc): """:type tc: ToolContract""" print "Loaded tc {c}".format(c=tc) if tc.task.nproc == SymbolTypes.MAX_NPROC: nproc = get_input("Enter max nproc: ") else: # not quite right nproc = 1 output_dir = get_input("Output Directory: ", enable_system_bindings=Always()) output_dir = os.path.abspath(output_dir) input_files = [] for i, input_type in enumerate(tc.task.input_file_types): in_path = get_input(" {i} file {p} path :".format(i=i, p=input_type)) if not os.path.exists(in_path): warnings.warn("Unable to find {p}".format(p=in_path)) input_files.append(in_path) tool_options = {} rtc = resolve_tool_contract(tc, input_files, output_dir, "/tmp", int(nproc), tool_options) print rtc file_name = tc.task.task_id + "_resolved_tool_contract.json" rtc_path = os.path.join(output_dir, file_name) print "writing RTC to {f}".format(f=rtc_path) write_resolved_tool_contract(rtc, rtc_path) return rtc
def run_main(tc): """:type tc: ToolContract""" print "Loaded tc {c}".format(c=tc) h = History() if tc.task.nproc == SymbolTypes.MAX_NPROC: nproc = get_input('Enter max nproc: ') else: # not quite right nproc = 1 output_dir = get_input('Output Directory: ', enable_system_bindings=Always()) output_dir = os.path.abspath(output_dir) input_files = [] for i, input_type in enumerate(tc.task.input_file_types): in_path = get_input(" {i} file {p} path :".format(i=i, p=input_type)) if not os.path.exists(in_path): warnings.warn("Unable to find {p}".format(p=in_path)) input_files.append(in_path) tool_options = {} rtc = resolve_tool_contract(tc, input_files, output_dir, '/tmp', int(nproc), tool_options) print rtc print "writing RTC" file_name = tc.task.task_id + "_resolved_tool_contract.json" rtc_path = os.path.join(output_dir, file_name) write_resolved_tool_contract(rtc, rtc_path) return rtc
def set_bridge(self): bridge = get_input('bridge device [example=>br0]:') mode = get_input('[dhcp(d)/static(s)]:') if mode == 'dhcp' or mode == 'd': self.set_bridge_dhcp(bridge) else: ip = get_input('ip:') mask = get_input('mask:') gateway = get_input('gateway:') self.set_bridge_static(bridge, ip, mask, gateway)
def run_main(tc): """:type tc: ToolContract""" print("Loaded tc {c}".format(c=tc)) if tc.task.nproc == SymbolTypes.MAX_NPROC: nproc = get_input('Enter max nproc: ') else: # not quite right nproc = 1 output_dir = get_input('Output Directory: ', enable_system_bindings=Always()) output_dir = os.path.abspath(output_dir) input_files = [] for i, input_type in enumerate(tc.task.input_file_types): in_path = get_input(" {i} file {p} path :".format(i=i, p=input_type)) if not os.path.exists(in_path): warnings.warn("Unable to find {p}".format(p=in_path)) # Make sure all inputs are abspaths p = in_path if os.path.isabs(in_path) else os.path.abspath(in_path) input_files.append(p) tool_options = {} rtc = resolve_tool_contract(tc, input_files, output_dir, '/tmp', int(nproc), tool_options, is_distributable=False) print(rtc) def to_n(ext): return "resolved_tool_contract." + ext def to_f(ext): return "_".join([tc.task.task_id, to_n(ext)]) def to_p(ext): return os.path.join(output_dir, to_f(ext)) rtc_path = to_p("json") print("writing RTC to {f}".format(f=rtc_path)) # Always write the JSON RTC file write_resolved_tool_contract(rtc, rtc_path) if rtc.driver.serialization.lower() == "avro": avro_rtc_path = to_p("avro") print("writing AVRO RTC to {f}".format(f=avro_rtc_path)) write_resolved_tool_contract_avro(rtc, avro_rtc_path) return rtc
def set_route(self): net = get_input('net:') via = get_input('via:') dev = get_input('dev:') command = '{} via {} dev {}\n'.format(net, via, dev) # TODO: if the gw is exist, warning! click.secho('configuration information:\n' '{}'.format(command), fg='yellow') ret = get_input('Please confirm the above information [y/n]:') if ret.lower() == 'y': with open(self.route_file + dev, 'a') as f: f.write(command) click.secho('successful', fg='green')
def add_source_interactive(source_name, source_rss, source_info=None): if SOURCE_NAME_REGEX.match(source_name) is None: raise ValueError( "Source name {} didn't match regex".format(source_name)) parsed = feedparser.parse(source_rss) if "bozo_exception" in parsed: print "Couldn't parse: {} {}".format(source_rss, parsed["bozo_exception"]) return False link = url_to_name(parsed.feed.link) # TODO check that link is a real page if link != source_name: print "Warning: source name != name from feed link: {} != {}".format( source_name, link) print "Source name: {}".format(source_name) print "Source RSS url: {}".format(source_rss) print "Source info: {}".format(source_info) if 'n' == get_input(u'Add this source? ', validator=YnValidator()): return source_list = get_source_list() if source_name in source_list: if 'n' == get_input(u'Replace existing source? {} '.format( source_list[source_name]), validator=YnValidator()): return proportion = float( get_input(u'Proportion of entries that are articles: ', validator=ProportionValidator())) source_list[source_name] = make_source_list_entry(source_rss, proportion) write_source_list(source_list) print "Source added\n" source_tree = get_source_tree() paths = [ ":".join(path) for path in tree_to_paths(strip_tree_leaves(source_tree)) ] path = get_input(u'Where? ', completer=WordCompleter(paths, match_middle=True)) if add_to_tree_interactive(source_tree, path.split(":"), source_name): write_source_tree(source_tree) print "Source added to tree at {}\n".format(path) else: print "Source not added"
def run_main(tc): """:type tc: ToolContract""" print "Loaded tc {c}".format(c=tc) if tc.task.nproc == SymbolTypes.MAX_NPROC: nproc = get_input('Enter max nproc: ') else: # not quite right nproc = 1 output_dir = get_input('Output Directory: ', enable_system_bindings=Always()) output_dir = os.path.abspath(output_dir) input_files = [] for i, input_type in enumerate(tc.task.input_file_types): in_path = get_input(" {i} file {p} path :".format(i=i, p=input_type)) if not os.path.exists(in_path): warnings.warn("Unable to find {p}".format(p=in_path)) # Make sure all inputs are abspaths p = in_path if os.path.isabs(in_path) else os.path.abspath(in_path) input_files.append(p) tool_options = {} rtc = resolve_tool_contract(tc, input_files, output_dir, '/tmp', int(nproc), tool_options, is_distributable=False) print rtc def to_n(ext): return "resolved_tool_contract." + ext def to_f(ext): return "_".join([tc.task.task_id, to_n(ext)]) def to_p(ext): return os.path.join(output_dir, to_f(ext)) rtc_path = to_p("json") print "writing RTC to {f}".format(f=rtc_path) # Always write the JSON RTC file write_resolved_tool_contract(rtc, rtc_path) if rtc.driver.serialization.lower() == "avro": avro_rtc_path = to_p("avro") print "writing AVRO RTC to {f}".format(f=avro_rtc_path) write_resolved_tool_contract_avro(rtc, avro_rtc_path) return rtc
def run_shell(self): """ Run interactive shell """ print('Welcome to ws shell (v{}) '.format(VERSION_STR)) print('type :help for help, type :q or press ^D to quit') setup_user_directories() histfile = os.path.join(os.path.expanduser("~/.ws"), "history") history = FileHistory(histfile) prompt = 'ws: ' completer = WsCompleter() while True: try: line = get_input(prompt, history=history, validator=WsCmdValidator( self.service_manager), completer=completer, lexer=WsLexer(self.service_manager)).strip() except EOFError: quit() wscmd = WsCommand(None, service_manager=self.service_manager) try: wscmd.parse(tokenize(line)) wscmd.run() except Exception as e: print('error: ' + repr(e), file=sys.stderr) traceback.print_exc(file=sys.stderr)
def main(): # We start with a `KeyBindingManager` instance, because this will already # nicely load all the default key bindings. key_bindings_manager = KeyBindingManager() # Add our own key binding to the registry of the key bindings manager. @key_bindings_manager.registry.add_binding(Keys.F4) def _(event): """ When F4 has been pressed. Insert "hello world" as text. """ event.cli.current_buffer.insert_text('hello world') @key_bindings_manager.registry.add_binding('x', 'y') def _(event): """ (Useless, but for demoing.) Typing 'xy' will insert 'z'. Note that when you type for instance 'xa', the insertion of 'x' is postponed until the 'a' is typed. because we don't know earlier whether or not a 'y' will follow. """ event.cli.current_buffer.insert_text('z') # Read input. print('Press F4 to insert "hello world", type "xy" to insert "z":') text = get_input(key_bindings_registry=key_bindings_manager.registry) print('You said: %s' % text)
def main(): def get_bottom_toolbar_tokens(cli): global status global current state = status['state'] volume = status['volume'] tb = "State: " + state + " Volume: " + str(volume) if current: artist = current['artist'] title = current['title'] current_time = int(float(status['current_time'] / 1000)) current_time = datetime.timedelta(seconds=current_time) duration = int(float(status['duration'] / 1000)) duration = datetime.timedelta(seconds=duration) tb = tb + " Playing: " + artist + " - " + title + " " + str(current_time) + "/" + str(duration) return [(Token.Toolbar, tb)] while True: try: text = get_input('>> ', get_bottom_toolbar_tokens=get_bottom_toolbar_tokens, style=TestStyle, completer=command_completer) except EOFError: break except KeyboardInterrupt: break run_command(text) now_playing()
def prompt_songs(r): songs = r.json()['results'] if len(songs) == 0: print("No results.") return print_songs(songs) res = get_input("Song? ") if not res: return try: num = int(res) except ValueError: print("not an integer") if 1 <= num <= len(songs): song = songs[num-1] else: print("not in range") return response = requests.post(beats_url() + "/v1/queue/add", data={'token':session['token'], 'id':str(song['id'])}) json = response.json() if response.status_code is not 200: get_login() else: # print("Added " + song['artist'] + " - " + song['title']) print_queue(response)
def run(self): """ Main entry function. """ history = History() while True: # (re)load the todo.txt file (only if it has been modified) self._load_file() try: user_input = get_input(u'topydo> ', history=history, completer=self.completer).split() except (EOFError, KeyboardInterrupt): sys.exit(0) mtime_after = _todotxt_mtime() if self.mtime != mtime_after: # refuse to perform operations such as 'del' and 'do' if the # todo.txt file has been changed in the background. error("WARNING: todo.txt file was modified by another application.\nTo prevent unintended changes, this operation was not executed.") continue (subcommand, args) = get_subcommand(user_input) try: if self._execute(subcommand, args) != False: self._post_execute() except TypeError: usage()
def main(): # We start with a `KeyBindingManager` instance, because this will already # nicely load all the default key bindings. key_bindings_manager = KeyBindingManager() # We add a custom key binding to space. @key_bindings_manager.registry.add_binding(' ') def _(event): """ When space is pressed, we check the word before the cursor, and autocorrect that. """ b = event.cli.current_buffer w = b.document.get_word_before_cursor() if w is not None: if w in corrections: b.delete_before_cursor(count=len(w)) b.insert_text(corrections[w]) b.insert_text(' ') # Read input. print('Say something') text = get_input(key_bindings_registry=key_bindings_manager.registry) print('You said: %s' % text)
def run(self): """ Main entry function. """ history = History() while True: # (re)load the todo.txt file (only if it has been modified) self._load_file() try: user_input = get_input(u'topydo> ', history=history, completer=self.completer).split() except (EOFError, KeyboardInterrupt): sys.exit(0) mtime_after = _todotxt_mtime() if self.mtime != mtime_after: # refuse to perform operations such as 'del' and 'do' if the # todo.txt file has been changed in the background. error( "WARNING: todo.txt file was modified by another application.\nTo prevent unintended changes, this operation was not executed." ) continue (subcommand, args) = get_subcommand(user_input) try: if self._execute(subcommand, args) != False: self._post_execute() except TypeError: usage()
def cmdloop(self, intro=None): """Enters a loop that reads and execute input from user.""" if intro: print(intro) _auto_suggest = AutoSuggestFromHistory() while not builtins.__xonsh_exit__: try: token_func, style_cls = self._get_prompt_tokens_and_style() mouse_support = builtins.__xonsh_env__.get('MOUSE_SUPPORT') if builtins.__xonsh_env__.get('AUTO_SUGGEST'): auto_suggest = _auto_suggest else: auto_suggest = None completions_display = builtins.__xonsh_env__.get('COMPLETIONS_DISPLAY') multicolumn = (completions_display == 'multi') completer = None if completions_display == 'none' else self.pt_completer line = get_input( mouse_support=mouse_support, auto_suggest=auto_suggest, get_prompt_tokens=token_func, style=style_cls, completer=completer, history=self.history, key_bindings_registry=self.key_bindings_manager.registry, display_completions_in_columns=multicolumn) if not line: self.emptyline() else: line = self.precmd(line) self.default(line) except KeyboardInterrupt: self.reset_buffer() except EOFError: break
def run(): """The function that runs the CLI""" backend = CLIBackend(*read_config()) history = InMemoryHistory() completer = WordCompleter(backend.get_completion_list()) user_id = backend.get_user_id() while True: try: text = get_input( user_id + '> ', completer=completer, history=history, on_abort=AbortAction.RETRY, key_bindings_registry=key_bindings_manager.registry) except EOFError: # Control-D pressed. break else: if text.strip() == 'exit': break try: backend.execute_command(text) except CommandError as e: print e.message except Exception: backend.close() raise else: # update word completer completer = WordCompleter(backend.get_completion_list()) backend.close()
def main(self): self.database = db history = History() while True: try: text = get_input('> ', lexer=SqlLexer, completer=sql_completer, style=DocumentStyle, history=history) except EOFError: break # Control-D pressed. with self.connection.cursor() as cursor: messages = cursor.execute(text) fetchall = cursor.fetchall() result = [] description = cursor.description headers = [] rowcount = cursor.rowcount for i in description: headers.append(i[0]) for record in fetchall: result.append([self.None2NULL(record[d]) for d in headers]) print(tabulate(result, headers, tablefmt="grid")) print(str(rowcount) + ' rows\n') print('GoodBye!')
def prompt_albums(r): albums = r.json()['results'] if len(albums) == 0: print("No results.") return n = 0 total_songs = 0 x = PrettyTable(["#", "Album", "Songs"]) x.border = False x.align['Album'] = "l" x.align['Songs'] = "r" for album in albums: n += 1 total_songs += album['num_songs'] x.add_row([n, colored(album['name'], "blue"), colored(str(album['num_songs']), "magenta")]) print(colored("Albums by " + r.json()['query'] + ":", attrs=['underline'])) print(x) print("Total songs: " + str(total_songs)) res = get_input("Album? ") if not res: return try: num = int(res) except ValueError: print("not an integer") if 1 <= num <= len(albums): album = albums[num-1] else: print("not in range") return search("album:" + album['name'])
def process_io(self): text = self._input_text line_num = self.line_num try: if not self.condition: text = get_input( get_prompt_tokens=self.get_in_prompt_tokens, lexer=IokeLexer, history=self._history, completer=ioke_completer, style=DocumentStyle) else: if self.restart is not None: text = get_input( get_prompt_tokens=self.get_restart_prompt_tokens, style=DocumentStyle) else: text = get_input( get_prompt_tokens=self.get_condition_prompt_tokens, style=DocumentStyle) self._input_text = text if self.prompt is None: self.prompt = self._ioke.current_prompt except (EOFError, pexpect.EOF) as err: raise ExitRepl(err) except KeyboardInterrupt: self._input_text = text = "" print("**Keyboard interrupt**") print("Enter ctrl-d to exit") else: if text: self.prompt = prompt = self.execute(text) if prompt == IOKE_PROMPT: self.condition = False printed, result = self._ioke.output if printed: print(printed) if result != 'nil': print(OUT_PROMPT.format(line_num, result)) print() elif prompt == IOKE_DEBUG: self.condition = True options, _ = self._ioke.output self.debug_level = self._ioke.debug_level self.restart = self._ioke.restart options = options.strip() if options: print(options) # TODO: Format and colorise traceback/options self.inc_line()
def main(): history = History() while True: text = get_input('> ', lexer=BashLexer, history=history) print('You entered:', text) print('GoodBye!')
def main(): def get_bottom_toolbar_tokens(cli): return [(Token.Toolbar, ' This is a toolbar. ')] text = get_input('Say something: ', get_bottom_toolbar_tokens=get_bottom_toolbar_tokens, style=TestStyle) print('You said: %s' % text)
def create_commit(): a = sites() isAll = True; if type(a.list(isAll=isAll)) is dict and 'detail' in a.list(isAll=isAll).keys(): isAll = False my_sites = a.list(isAll=isAll) if len(my_sites)>0: col_name = ['id','name', 'create_time', 'status'] table_layout('sites', my_sites, caption_row=col_name) site_id = get_input(u'Please Input the site ID which you would like to commit: ') tag = get_input(u'Please Input the image tag ') image = get_input(u'Please Input the image name: ') c = image_commit() print(c.createCommit(site_id, tag, image))
def add_source_interactive(source_name, source_rss, source_info=None): if SOURCE_NAME_REGEX.match(source_name) is None: raise ValueError("Source name {} didn't match regex".format(source_name)) parsed = feedparser.parse(source_rss) if "bozo_exception" in parsed: print "Couldn't parse: {} {}".format(source_rss, parsed["bozo_exception"]) return False link = url_to_name(parsed.feed.link) # TODO check that link is a real page if link != source_name: print "Warning: source name != name from feed link: {} != {}".format(source_name, link) print "Source name: {}".format(source_name) print "Source RSS url: {}".format(source_rss) print "Source info: {}".format(source_info) if 'n' == get_input(u'Add this source? ', validator=YnValidator()): return source_list = get_source_list() if source_name in source_list: if 'n' == get_input( u'Replace existing source? {} '.format(source_list[source_name]), validator=YnValidator() ): return proportion = float(get_input(u'Proportion of entries that are articles: ', validator=ProportionValidator())) source_list[source_name] = make_source_list_entry(source_rss, proportion) write_source_list(source_list) print "Source added\n" source_tree = get_source_tree() paths = [":".join(path) for path in tree_to_paths(strip_tree_leaves(source_tree))] path = get_input( u'Where? ', completer=WordCompleter(paths, match_middle=True) ) if add_to_tree_interactive(source_tree, path.split(":"), source_name): write_source_tree(source_tree) print "Source added to tree at {}\n".format(path) else: print "Source not added"
def __init__(self, bot, prompt=DEFAULT_PROMPT, intro=DEFAULT_INTRO): self.bot, self.finished = bot, False # launch bot as thread self.bot_thread = threading.Thread(target=self.bot.start) self.bot_thread.start() # Initial plugins self.available_plugins = tuple(p(bot) for p in config.import_plugins()) # Add whitelisted plugins automatically # TODO for plugin in self.available_plugins: plugin.load_persistent_data() self.bot.add_plugin(plugin) LOGGER.info('PLUGIN LOADED: ' + str(plugin)) assert all(self.active(f) for f in self.available_plugins) # main loop control LOGGER.info('Connected !') print(intro, end='') grammar = commands_grammar() while not self.finished: try: text = get_input(prompt) except (EOFError, KeyboardInterrupt): self.__disconnect() continue match = grammar.match(text) if match is not None: values = match.variables() cmd = values.get('cmd') subcmd = values.get('subcmd') args = values.get('args') LOGGER.debug('LINE:' + str(cmd) + str(subcmd) + str(args)) if cmd in COMMAND_NAMES['plugins']: self.__plugins(subcmd, args) elif cmd in COMMAND_NAMES['quit']: self.__disconnect() elif cmd in COMMAND_NAMES['say']: self.__say(args) elif cmd in COMMAND_NAMES['irc']: self.__last_words(args) elif cmd in COMMAND_NAMES['help']: self.__help() elif cmd in COMMAND_NAMES['operate']: self.__operate() elif cmd in COMMAND_NAMES['sudoers']: self.__sudoers(subcmd, args) elif cmd in COMMAND_NAMES['debug']: self.__debug() elif cmd in COMMAND_NAMES['save']: self.__save_persistant_data() else: print('not a valid command') # finalize all treatments LOGGER.info('Disconnected !')
def get_route(self): card = get_input('card name:') card_conf = self.route_file + card if not os.path.exists(card_conf): click.secho('can\'t find configure', fg='red') return with open(card_conf, 'r') as r: routes = r.read() click.secho(routes, fg='green')
def main(): history = History() while True: sql_completer = WordCompleter(['create', 'select', 'insert', 'drop', 'delete', 'from', 'where', 'table'], ignore_case=True) text = get_input('> ', completer=sql_completer, history=history) print('You entered:', text) print('GoodBye!')
def main(): # creating instance of history # If you want to keep your history across several ``get_input`` calls, you # have to create a :class:`History` instance and pass it every time. history = History() while True: text = get_input("> ", history=history) print("You entered:", text) print("GoodBye!")
def del_route(self): net = get_input('net:') command = 'ip route show | grep {}'.format(net) out, error, code = self.run_shell(command) if not code and out: ret = get_input('route "{}" will be deleted! [y/n]:'.format( out.strip())) if ret.lower() == 'y': dev = out.split()[-1] route_file = os.path.join(self.route_file + dev) if not os.path.exists(route_file): click.secho('route file can\'t find!') else: command = 'sed -i \'/^{}/d\' {}'.format( net.replace('/', '\/'), route_file) out, error, code = self.run_shell(command) self.secho(out, error, code) else: click.secho('can\'t find route!', fg='red')
def Prompt(): cmd = "" try: cmd = get_input(header, completer=completer) except EOFError: return except KeyboardInterrupt: exit() except Exception as e: print("%s%s" % (header, e)) Parse(cmd)
def update_ifcfg(self, device, info): click.secho('configuration information:\n{}'.format(info), fg='yellow') ret = get_input('Please confirm the above information [y/n]:') if ret.lower() == 'y': with open( os.path.join(self.base_if_path, 'ifcfg-{}'.format(device)), 'w') as w: w.write(info) click.secho('successful!', fg='green') else: click.secho('cancel!', fg='green')
def __init__(self, bot, prompt=DEFAULT_PROMPT, intro=DEFAULT_INTRO): self.bot, self.finished = bot, False # launch bot as thread self.bot_thread = threading.Thread(target=self.bot.start) self.bot_thread.start() # Initial plugins self.available_plugins = tuple(p(bot) for p in config.import_plugins()) # Add whitelisted plugins automatically # TODO for plugin in self.available_plugins: self.bot.add_plugin(plugin) LOGGER.info('PLUGIN LOADED: ' + str(plugin)) assert all(self.active(f) for f in self.available_plugins) # main loop control LOGGER.info('Connected !') print(intro, end='') grammar = commands_grammar() while not self.finished: try: text = get_input(prompt) except EOFError: self.__disconnect() continue match = grammar.match(text) if match is not None: values = match.variables() cmd = values.get('cmd') subcmd = values.get('subcmd') args = values.get('args') LOGGER.debug('LINE:' + str(cmd) + str(subcmd) + str(args)) if cmd in COMMAND_NAMES['sudo']: self.__sudo(subcmd, args) elif cmd in COMMAND_NAMES['plugins']: self.__plugins(subcmd, args) elif cmd in COMMAND_NAMES['quit']: self.__disconnect() elif cmd in COMMAND_NAMES['say']: self.__say(args) elif cmd in COMMAND_NAMES['irc']: self.__last_words(args) elif cmd in COMMAND_NAMES['help']: self.__help() elif cmd in COMMAND_NAMES['operate']: self.__operate() else: print('not a valid command') LOGGER.info('Disconnected !') # finalize all treatments self.bot_thread.join()
def cli(ctx, env): """Enters a shell for slcli.""" # Set up the environment env = copy.deepcopy(env) env.load_modules_from_python(routes.ALL_ROUTES) env.aliases.update(routes.ALL_ALIASES) env.vars['global_args'] = ctx.parent.params env.vars['is_shell'] = True env.vars['last_exit_code'] = 0 # Set up prompt_toolkit settings app_path = click.get_app_dir('softlayer') if not os.path.exists(app_path): os.makedirs(app_path) history = p_history.FileHistory(os.path.join(app_path, 'history')) complete = completer.ShellCompleter() while True: try: line = p_shortcuts.get_input( u"(%s)> " % env.vars['last_exit_code'], completer=complete, history=history, ) try: args = shlex.split(line) except ValueError as ex: print("Invalid Command: %s" % ex) continue if not args: continue # Reset client so that the client gets refreshed env.client = None core.main(args=list(get_env_args(env)) + args, obj=env, prog_name="", reraise_exceptions=True) except SystemExit as ex: env.vars['last_exit_code'] = ex.code except KeyboardInterrupt: env.vars['last_exit_code'] = 1 except EOFError: return except ShellExit: return except Exception as ex: env.vars['last_exit_code'] = 1 traceback.print_exc(file=sys.stderr)
def main(): history = History() cmd_completer = WordCompleter(makeCmdList(), ignore_case=True) while True: try: text = get_input('> ', completer=cmd_completer, style=DocumentStyle, history=history) except EOFError: print("Exiting program.") return 0 else: print('You entered:', text) print('GoodBye!')
def get_login(): global session if os.path.isfile(SESSION_FILE): with open(SESSION_FILE, 'rb') as f: session = pickle.load(f) if is_session_valid() == True: return else: print("Session has expired.") os.remove(SESSION_FILE) username = get_input("Username: "******"Password: "******"/v1/session", data={"username":username, "password":password}) if r.status_code is not 201: print("couldn't log in: " + r.json()['reason']) get_login() else: session = dict(r.json()) with open(SESSION_FILE, 'wb') as f: pickle.dump(session, f, pickle.HIGHEST_PROTOCOL)
def set_bond(self): cards, _, _ = self.run_shell('ls /sys/class/net/') bond = get_input('bond device [example=>bond0]:') bond_mode = get_input('bond mode:') miimon = get_input('bond miimon:') onboot = get_input('onboot [yes/no]:') mode = get_input('select the mode [dhcp(d)/static(s)//bridge(e)]:') if mode == 'dhcp' or mode == 'd': self.set_bond_dhcp(bond, bond_mode, miimon, onboot) elif mode == 'bridge' or mode == 'e': bridge = get_input('bridge name:') self.add_bond_to_bridge(bond, bond_mode, miimon, onboot, bridge) else: ipaddr = get_input('ipaddr:') netmask = get_input('netmask:') gateway = get_input('gateway:') self.set_bond_static(bond, bond_mode, miimon, ipaddr, netmask, gateway, onboot)
def main(): hidden = [True] # Nonlocal key_bindings_manager = KeyBindingManager() @key_bindings_manager.registry.add_binding(Keys.ControlT) def _(event): ' When ControlT has been pressed, toggle visibility. ' hidden[0] = not hidden[0] print('Type Control-T to toggle password visible.') password = get_input('Password: '******'You said: %s' % password)
def main(): history = FileHistory('.example-history-file') while True: try: text = get_input(get_prompt_tokens=get_prompt_tokens, lexer=BashLexer, completer=openstack_completer, style=DocumentStyle, history=history, on_abort=AbortAction.RETRY) except EOFError: break # Control-D pressed. if text in commands: # FIXME: make the update meaningfull openstack_completer.commands.update([]) print('GoodBye!')
def main(database): history = History() connection = sqlite3.connect(database) while True: try: text = get_input('> ', lexer=SqlLexer, completer=sql_completer, style=DocumentStyle, history=history) except EOFError: break # Control-D pressed. with connection: messages = connection.execute(text) for message in messages: print(message) print('GoodBye!')
def run_repl_loop(db, data_path): history = FileHistory(str(data_path / 'history')) glos = {} locs = {'db': db} def get_locals(): return locs def get_globals(): return glos while True: try: inp = get_input( '>>> ', completer=PythonCompleter( get_locals=get_locals, get_globals=get_globals, ), history=history, lexer=PythonLexer, ) except KeyboardInterrupt: continue except EOFError: break result = None try: result = eval(inp, glos, locs) except SyntaxError: try: six.exec_(inp, glos, locs) except: print_exc(chain=False) except SystemExit: break except: print_exc(chain=False) if result is None: pass # HACK: Eval iterators automatically so that find() calls and others # return the result without iterating manually. # TODO: Find a better solution for this. elif (six.PY3 and hasattr(result, '__next__') or six.PY2 and hasattr(result, 'next')): output([x for x in result]) else: output(result)
def cli(): tag = "Name" filters = {} instances = ec2_active_instances(tag, filters) instance_ips = [item for sublist in instances.values() for item in sublist] instance_completer = WordCompleter(instances.keys(), meta_dict=instances, match_middle=True, WORD=True, ignore_case=True) history = History() selecting_instance = True supported_commands = ['ssh', 'info'] while selecting_instance: try: input = get_input('Pick an instance: ', completer=instance_completer, history=history, on_abort=AbortAction.RETRY, enable_system_bindings=Always()) command = '' hostname = input if input.find(' ') >= 0: input_parts = input.split(' ') input_word = input_parts[0].lower() if any(input_word in item for item in supported_commands): hostname = ' '.join(input_parts[1:]) command = input_parts[0].lower() instance_id = instances[hostname] instance_info = get_instance_info(instance_id) if command.startswith('i'): print tabulate(instance_info) else: # Always try with public ip if instance_info[1][1]: ip = instance_info[1][1] else: ip = instance_info[0][1] if netaddr.valid_ipv4(ip) == True: subprocess.call(['ssh', ip]) selecting_instance = False else: print 'Invalid IP: %s' % ip except EOFError: break # Control-D pressed.
def main(): # Create user interface. hello_world_window() # Enable threading in GTK. (Otherwise, GTK will keep the GIL.) gtk.gdk.threads_init() # Read input from the command line, using an event loop with this hook. # We say `patch_stdout=True`, because clicking the button will print # something; and that should print nicely 'above' the input line. result = get_input('Python >>> ', eventloop=create_eventloop(inputhook=inputhook), lexer=PythonLexer, patch_stdout=True) print('You said: %s' % result)
def get_user_input(get_prompt_tokens, history=None, lexer=None, key_bindings_registry=None, completer=None): """Customized function that mostly mimics promp_toolkit's get_input. Main difference between this and prompt_toolkit's get_input() is that it allows to pass get_tokens() function instead of text prompt. """ return get_input(lexer=lexer, completer=completer, history=history, get_prompt_tokens=get_prompt_tokens, key_bindings_registry=key_bindings_registry)
def run_repl_loop(db, data_path, with_color): history = FileHistory(str(data_path / 'history')) glos = {} locs = {'db': db} def get_locals(): return locs def get_globals(): return glos while True: try: inp = get_input( '>>> ', completer=PythonCompleter( get_locals=get_locals, get_globals=get_globals, ), history=history, lexer=PythonLexer, ) except KeyboardInterrupt: continue except EOFError: break result = None try: result = eval(inp, glos, locs) except SyntaxError: try: six.exec_(inp, glos, locs) except: print_exc(with_color=with_color, chain=False) except SystemExit: break except: print_exc(with_color=with_color, chain=False) if result is None: pass # HACK: Eval iterators automatically so that find() calls and others # return the result without iterating manually. # TODO: Find a better solution for this. elif (six.PY3 and hasattr(result, '__next__') or six.PY2 and hasattr(result, 'next')): output([x for x in result], with_color=with_color) else: output(result, with_color=with_color)
def get_user_input(get_prompt_tokens, history=None, lexer=None, key_bindings_registry=None, completer=None): """Customized function that mostly mimics promp_toolkit's get_input. Main difference between this and prompt_toolkit's get_input() is that it allows to pass get_tokens() function instead of text prompt. """ return get_input( lexer=lexer, completer=completer, history=history, get_prompt_tokens=get_prompt_tokens, key_bindings_registry=key_bindings_registry)
def prompt_for_api_key(pushbullet): print( 'Your PushBullet access token must be configured first.\n' 'I can attempt to set it for you, please visit https://www.pushbullet.com/#settings/account\n' 'and paste it below') key = get_input('ACCESS TOKEN> ') pushbullet.api_key = key if pushbullet.api_key == key: print('Access token configured') return True else: print( 'Unable to set your environment variable automatically.\n' 'Please manually set the variable "PUSHBULLET_API_KEY" to the access token' ) return False
def __init__(self, bot, prompt=DEFAULT_PROMPT, intro=DEFAULT_INTRO): self.bot, self.finished = bot, False # launch bot as thread self.bot_thread = threading.Thread(target=self.bot.start) self.bot_thread.start() # Initial plugins self.available_plugins = tuple(p() for p in config.import_plugins()) # Add whitelisted plugins automatically # TODO for plugin in self.available_plugins: self.bot.add_plugin(plugin) LOGGER.info("PLUGIN LOADED: " + str(plugin)) assert all(self.active(f) for f in self.available_plugins) # main loop control LOGGER.info("Connected !") print(intro, end="") grammar = commands_grammar() while True: text = get_input(prompt) match = grammar.match(text) if match is not None: values = match.variables() cmd = values.get("cmd") subcmd = values.get("subcmd") args = values.get("args") LOGGER.debug("LINE:" + str(cmd) + str(subcmd) + str(args)) if cmd in COMMAND_NAMES["sudo"]: self.__sudo(subcmd, args) elif cmd in COMMAND_NAMES["plugins"]: self.__plugins(subcmd, args) elif cmd in COMMAND_NAMES["quit"]: self.__disconnect() elif cmd in COMMAND_NAMES["say"]: self.__say(args) elif cmd in COMMAND_NAMES["irc"]: self.__last_words(args) # elif cmd in ('', ''): # self. else: print("not a valid command") LOGGER.info("Disconnected !") # finalize all treatments self.bot_thread.join()
def prompt_for_api_key(pushbullet): print( "Your PushBullet access token must be configured first.\n" "I can attempt to set it for you, please visit https://www.pushbullet.com/#settings/account\n" "and paste it below" ) key = get_input("ACCESS TOKEN> ") pushbullet.api_key = key if pushbullet.api_key == key: print("Access token configured") return True else: print( "Unable to set your environment variable automatically.\n" 'Please manually set the variable "PUSHBULLET_API_KEY" to the access token' ) return False
def getPhabOption( prompt, dbKey, getFunc ): while True: store = False values = promptSettings.get( dbKey ) #this is a little hacky. if its a list, printValues = [] if len(values): if type(values[0]) == list: for l in values: printValues.append( l[0] ) else: printValues = values for i in range( 0, len(printValues)): print(' ' + str(i+1) + ': ' + printValues[i]) print(' a: add ' + prompt + ' r: remove ' + prompt ) text = get_input('select ' + prompt + '> ', key_bindings_registry=key_bindings_manager.registry) if len(text) and text.isdigit(): i = int( text ) if i >= 1 and i <= (len(values) + 1): return values[i-1] else: print("invalid option!") elif len(text) == 0: return None elif text == "a" or text == "add": newValue = getFunc( prompt ) if None != newValue: values.append( newValue ) store = True elif text == "r" or text == "remove": oldValue = getText( prompt + " to remove" ) if None != oldValue and len(oldValue) and oldValue.isdigit(): i = int( oldValue ) if i >= 1 and i <= (len(values) + 1): values.remove( values[i-1] ) store = True if store: promptSettings.set( dbKey, values ) promptSettings.dump()
def main(): # Print a counter every second in another thread. running = True def thread(): i = 0 while running: i += 1 print('i=%i' % i) time.sleep(1) threading.Thread(target=thread).start() # Now read the input. The print statements of the other thread # should not disturb anything. result = get_input('Say something: ', patch_stdout=True) print('You said: %s' % result) # Stop thrad. running = False
def main(): # Create some history first. (Easy for testing.) history = InMemoryHistory() history.append('import os') history.append('print("hello")') history.append('print("world")') history.append('import path') # Print help. print('This CLI has up-arrow partial string matching enabled.') print('Type for instance "pri" followed by up-arrow and you') print('get the last items starting with "pri".') print('Press Control-C to retry. Control-D to exit.') print() text = get_input('Say something: ', history=history, enable_history_search=Always(), on_abort=AbortAction.RETRY) print('You said: %s' % text)
def main(database): history = InMemoryHistory() connection = sqlite3.connect(database) while True: try: text = get_input('> ', lexer=SqlLexer, completer=sql_completer, style=DocumentStyle, history=history, on_abort=AbortAction.RETRY) except EOFError: break # Control-D pressed. with connection: try: messages = connection.execute(text) except Exception as e: print(repr(e)) else: for message in messages: print(message) print('GoodBye!')
def add_to_tree_interactive(source_tree, path_to_new_source, source_name): """ MODIFIES IN PLACE. :param source_tree: :param list[str] path_to_new_source: :param source_name: :return: True if this was added, otherwise false """ node = source_tree for child in path_to_new_source: if child not in node: if 'y' == get_input(u'Add child {}? '.format(child), validator=YnValidator()): node[child] = {} else: return False node = node[child] node[source_name] = {} return True
def set_if(self): eth = get_input('network card:') mode = get_input( 'select the mode [dhcp(d)/static(s)/bond(b)/bridge(e)]:') if mode == 'static' or mode == 's': ip = get_input('ip:') mask = get_input('mask:') gateway = get_input('gateway:') self.set_if_static(eth, ip, mask, gateway) elif mode == 'dhcp' or mode == 'd': self.set_if_dhcp(eth) elif mode == 'bond' or mode == 'b': bond = get_input('bond name:') self.add_if_to_bond(eth, bond) elif mode == 'bridge' or mode == 'e': bridge = get_input('bridge name:') self.add_if_to_bridge(eth, bridge) else: click.secho('Please select an available option!', fg='red')