def linteract(input_context, run=None, print_return=True): context = { 'message': '>>> ', 'history': History(), 'style': DocumentStyle, 'enable_system_prompt': True, } context.update(input_context) while True: try: text = get_input(**context) except EOFError: break except KeyboardInterrupt: print('KeyboardInterrupt') continue if run: try: if print_return: print(run(text)) else: run(text) except: print(traceback.format_exc(), end='')
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 create_cli(message='', multiline=False, is_password=False, vi_mode=False, lexer=None, enable_system_prompt=False, enable_open_in_editor=False, validator=None, completer=None, style=None, history=None, get_bottom_toolbar_tokens=None): # Create history instance. if history is None: history = History() # Load all key bindings. manager = KeyBindingManager(enable_vi_mode=vi_mode, enable_system_prompt=enable_system_prompt, enable_open_in_editor=enable_open_in_editor) # Create interface. return CommandLineInterface( layout=create_default_layout(message=message, lexer=lexer, is_password=is_password, reserve_space_for_menu=(completer is not None), get_bottom_toolbar_tokens=get_bottom_toolbar_tokens), buffer=Buffer( is_multiline=multiline, history=history, validator=validator, completer=completer, ), key_bindings_registry=manager.registry, style=style)
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 create_cli(eventloop, message='', multiline=False, is_password=False, vi_mode=False, lexer=None, enable_system_prompt=False, enable_open_in_editor=False, validator=None, completer=None, style=None, history=None, get_prompt_tokens=None, get_bottom_toolbar_tokens=None, extra_input_processors=None, key_bindings_registry=None, output=None, on_abort=AbortAction.RAISE_EXCEPTION, on_exit=AbortAction.RAISE_EXCEPTION, on_accept=AcceptAction.RETURN_DOCUMENT): """ Create a `CommandLineInterface` instance. """ assert isinstance(eventloop, EventLoop) # Create history instance. if history is None: history = History() # Use default registry from KeyBindingManager if none was given. if key_bindings_registry is None: key_bindings_registry = KeyBindingManager( enable_vi_mode=vi_mode, enable_system_prompt=enable_system_prompt, enable_open_in_editor=enable_open_in_editor).registry # Create interface. return CommandLineInterface( eventloop=eventloop, layout=create_default_layout( message=message, lexer=lexer, is_password=is_password, reserve_space_for_menu=(completer is not None), get_prompt_tokens=get_prompt_tokens, get_bottom_toolbar_tokens=get_bottom_toolbar_tokens, extra_input_processors=extra_input_processors), buffer=Buffer( is_multiline=(Always() if multiline else Never()), history=history, validator=validator, completer=completer, ), key_bindings_registry=key_bindings_registry, style=style, output=output, on_abort=on_abort, on_exit=on_exit)
def main(database): history = History() connection = sqlite3.connect(database) while True: text = get_input('> ', lexer=SqlLexer, completer=sql_completer, style=DocumentStyle, history=history) if text is None: break with connection: messages = connection.execute(text) for message in messages: print(message) 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, 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 main(): plugin_base = PluginBase(package="pycollect.plugins") plugin_source = plugin_base.make_plugin_source(searchpath=[PLUGIN_DIR]) history = History() all_commands = dict() all_shortcuts = dict() # Load all plugins with plugin_source: for file in os.listdir(PLUGIN_DIR): if '.py' in file and '.pyc' not in file: mod = plugin_source.load_plugin(file.replace('.py', '')) cmd = mod.main_class() # Add the registered commands to the commands dict all_commands.update(cmd.commands) all_shortcuts.update(cmd.shortcuts) while True: text = get_input(u'> ', history=history, completer=WordCompleter(all_commands.keys())) cmd_name = text.split(' ')[0] command = None if cmd_name in all_commands: command = all_commands[cmd_name] elif cmd_name in all_shortcuts: command = all_shortcuts[cmd_name] else: Command.error("Command not found.") try: if command is not None: run(command(), text) except UsageException: command.help() except KeyboardInterrupt: pass except EOFError: sys.exit(0)
def __init__( self, eventloop, get_globals=None, get_locals=None, stdin=None, stdout=None, vi_mode=False, history_filename=None, style=PythonStyle, # For internal use. _completer=None, _validator=None, _lexer=None, _python_prompt_control=None, _extra_buffers=None, _extra_buffer_processors=None, _extra_sidebars=None): self.settings = PythonCLISettings() self.get_globals = get_globals or (lambda: {}) self.get_locals = get_locals or self.get_globals self.completer = _completer or PythonCompleter(self.get_globals, self.get_locals) self.validator = _validator or PythonValidator() self.history = FileHistory( history_filename) if history_filename else History() self.python_prompt_control = _python_prompt_control or PythonPrompt( self.settings) self._extra_sidebars = _extra_sidebars or [] self._extra_buffer_processors = _extra_buffer_processors or [] self._lexer = _lexer or PythonLexer # Use a KeyBindingManager for loading the key bindings. self.key_bindings_manager = KeyBindingManager( enable_vi_mode=vi_mode, enable_open_in_editor=True, enable_system_prompt=True) load_python_bindings(self.key_bindings_manager, self.settings) self.get_signatures_thread_running = False buffers = { 'default': self._create_python_buffer(), 'docstring': Buffer(), # XXX: make docstring read only. } buffers.update(_extra_buffers or {}) self.cli = CommandLineInterface( eventloop=eventloop, style=style, key_bindings_registry=self.key_bindings_manager.registry, buffers=buffers, paste_mode=Condition(lambda cli: self.settings.paste_mode), layout=self._create_layout(), on_abort=AbortAction.RETRY, on_exit=AbortAction.RAISE_EXCEPTION) def on_input_timeout(): """ When there is no input activity, in another thread, get the signature of the current code. """ if self.cli.focus_stack.current != 'default': return # Never run multiple get-signature threads. if self.get_signatures_thread_running: return self.get_signatures_thread_running = True buffer = self.cli.current_buffer document = buffer.document def run(): script = get_jedi_script_from_document(document, self.get_locals(), self.get_globals()) # Show signatures in help text. if script: try: signatures = script.call_signatures() except ValueError: # e.g. in case of an invalid \\x escape. signatures = [] except Exception: # Sometimes we still get an exception (TypeError), because # of probably bugs in jedi. We can silence them. # See: https://github.com/davidhalter/jedi/issues/492 signatures = [] else: signatures = [] self.get_signatures_thread_running = False # Set signatures and redraw if the text didn't change in the # meantime. Otherwise request new signatures. if buffer.text == document.text: self.settings.signatures = signatures # Set docstring in docstring buffer. if signatures: string = signatures[0].docstring() if not isinstance(string, six.text_type): string = string.decode('utf-8') self.cli.buffers['docstring'].reset( initial_document=Document(string, cursor_position=0)) else: self.cli.buffers['docstring'].reset() self.cli.request_redraw() else: on_input_timeout() self.cli.eventloop.run_in_executor(run) def reset(): self.key_bindings_manager.reset() self.settings.signatures = [] self.cli.onReset += reset self.cli.onInputTimeout += on_input_timeout
def __init__( self, get_globals=None, get_locals=None, stdin=None, stdout=None, vi_mode=False, history_filename=None, style=PythonStyle, autocompletion_style=AutoCompletionStyle.POPUP_MENU, always_multiline=False, # For internal use. _completer=None, _validator=None): self.get_globals = get_globals or (lambda: {}) self.get_locals = get_locals or self.get_globals self.always_multiline = always_multiline self.autocompletion_style = autocompletion_style self.completer = _completer or PythonCompleter(self.get_globals, self.get_locals) validator = _validator or PythonValidator() layout = Layout( input_processors=[BracketsMismatchProcessor()], min_height=7, lexer=PythonLexer, left_margin=PythonLeftMargin(), menus=[CompletionsMenu()] if autocompletion_style == AutoCompletionStyle.POPUP_MENU else [], bottom_toolbars=[ ArgToolbar(), SignatureToolbar(), SearchToolbar(), SystemToolbar(), ValidationToolbar(), ] + ([CompletionsToolbar()] if autocompletion_style == AutoCompletionStyle.HORIZONTAL_MENU else []) + [ PythonToolbar(vi_mode=vi_mode), ], show_tildes=True) if history_filename: history = FileHistory(history_filename) else: history = History() if vi_mode: key_binding_factories = [vi_bindings, python_bindings] else: key_binding_factories = [emacs_bindings, python_bindings] line = PythonLine(always_multiline=always_multiline, tempfile_suffix='.py', history=history, completer=self.completer, validator=validator) #: Incremeting integer counting the current statement. self.current_statement_index = 1 self.get_signatures_thread_running = False super(PythonCommandLineInterface, self).__init__(layout=layout, style=style, key_binding_factories=key_binding_factories, line=line, create_async_autocompleters=True) def on_input_timeout(): """ When there is no input activity, in another thread, get the signature of the current code. """ # Never run multiple get-signature threads. if self.get_signatures_thread_running: return self.get_signatures_thread_running = True document = self.line.document def run(): script = get_jedi_script_from_document(document, self.get_locals(), self.get_globals()) # Show signatures in help text. if script: try: signatures = script.call_signatures() except ValueError: # e.g. in case of an invalid \\x escape. signatures = [] except Exception: # Sometimes we still get an exception (TypeError), because # of probably bugs in jedi. We can silence them. # See: https://github.com/davidhalter/jedi/issues/492 signatures = [] else: signatures = [] self.get_signatures_thread_running = False # Set signatures and redraw if the text didn't change in the # meantime. Otherwise request new signatures. if self.line.text == document.text: self.line.signatures = signatures self.request_redraw() else: on_input_timeout() self.run_in_executor(run) self.onInputTimeout += on_input_timeout